instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm coming from Eclipse, working in Visual Studio 2008 Express and just want to highlight code, right-click and comment it out.</p> <ul> <li>nothing in right-click</li> <li>looking in Tools | Options, Toolbars, Commands, can't find a button for it...</li> </ul> <p>How do I activate this the comment/uncomment feature, I know Visual Studio 2003 had it.</p> <p>HERE ARE THE ANSWERS, TURNS OUT IT DEPENDS WHAT YOU ARE USING:</p> <p><strong>Visual Studio 2008 Full Version:</strong></p> <p>Comment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br /> Uncomment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p> <p><strong>Visual Web Developer 2008 Express:</strong></p> <p>Comment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br /> Uncomment <kbd>Ctrl</kbd>-<kbd>K</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p> <p><strong>Visual C# 2008 Express:</strong></p> <p>Comment <kbd>Ctrl</kbd>-<kbd>E</kbd> , <kbd>Ctrl</kbd>-<kbd>C</kbd><br /> Uncomment <kbd>Ctrl</kbd>-<kbd>E</kbd> , <kbd>Ctrl</kbd>-<kbd>U</kbd></p>
<p>Weird it's <kbd>Ctrl</kbd>+<kbd>E</kbd>, <kbd>C</kbd> (Comment) and <kbd>Ctrl</kbd>+<kbd>E</kbd>, <kbd>U</kbd> (Uncomment)</p> <p><a href="http://picasaweb.google.com/lh/photo/jS75c4D1FfUA9kBy92nB5Q?authkey=-b3uGjHkX3g" rel="nofollow noreferrer"><img src="https://lh4.ggpht.com/_nxgDpneh8yk/SSmK9owk_dI/AAAAAAAAAZA/CIOm5V9Jbyw/s800/Comment_in_EE.JPG" /></a></p> <p>Normally It's <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>C</kbd> and <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>U</kbd> as Mauro says. Express Edition default (and only) keyboard mapping says otherwise.</p>
<p>Mauro is right about the shortcuts, they're in Express as well. You can also get to the Comment/Uncomment block commands in the Edit->Advanced menu. You probably also have a toolbar icon to do this that looks like a couple of lines, with a few indented blue ones.</p>
40,293
<p>Sometimes you don't have the source code and need to reverse engineer a program or a black box. Any fun war stories?</p> <p>Here's one of mine:</p> <p>Some years ago I needed to rewrite a device driver for which I didn't have source code. The device driver ran on an old CP/M microcomputer and drove a dedicated phototypesetting machine through a serial port. Almost no documentation for the phototypesetting machine was available to me.</p> <p>I finally hacked together a serial port monitor on a DOS PC that mimicked the responses of the phototypesetting machine. I cabled the DOS PC to the CP/M machine and started logging the data coming out of the device driver as I feed data in through the CP/M machine. This enabled me to figure out the handshaking and encoding used by the device driver and re-create an equivalent one for a DOS machine.</p>
<p>Read the story of FCopy for the C-64 here:</p> <p>Back in the 80s, the Commodore C-64 had an intelligent floppy drive, the 1541, i.e. an external unit that had its own CPU and everything.</p> <p>The C-64 would send commands to the drive which in turn would then execute them on its own, reading files, and such, then send the data to the C-64, all over a propriatory serial cable.</p> <p>The manual for the 1541 mentioned, besides the commands for reading and writing files, that one would read and write to its internal memory space. Even more exciting was that one could download 6502 code into the drive's memory and have it executed there.</p> <p>This got me hooked and I wanted to play with that - execute code on the drive. Of course, there was <em>no</em> documention on what code could be executed there, and which functions it could use.</p> <p>A friend of mine had written a disassembler in BASIC. and so I read out all its ROM contents, which was 16KB of 6502 CPU code, and tried to understand what it does. The OS on the drive was quite amazing and advanced IMO - it had a kind of task management, with commands being sent from the communication unit to the disk i/o task handler.</p> <p>I learned enough to understand how to use the disk i/o commands to read/write sectors of the disc. Actually, having read the Apple ]['s DOS 3.3 book which explained all of the workings of its disk format and algos in much detail, was a big help in understanding it all.</p> <p>(I later learned that I could have also found reserve-eng'd info on the more 4032/4016 disk drives for the "business" Commodore models which worked quite much the same as the 1541, but that was not available to me as a rather disconnected hobby programmer at that time.)</p> <p>Most importantly, I also learned how the serial comms worked. I realized that the serial comms, using 4 lines, two for data, two for handshake, was programmed very inefficiently, all in software (though done properly, using classic serial handshaking).</p> <p>Thus I managed to write a much faster comms routine, where I made fixed timing assumtions, using both the data and the handshake line for data transmission.</p> <p>Now I was able to read and write sectors, and also transmit data faster than ever before.</p> <p>Of course, it would have been great if one could simply load some code into the drive which speeds up the comms, and then use the normal commands to read a file, which in turn would use the faster comms. This was no possible, though, as the OS on the drive did not provide any hooks for that (mind that all of the OS was in ROM, unmodifiable).</p> <p>Hence I was wondering how I could turn my exciting findings into a useful application.</p> <p>Having been a programmer for a while already, dealing with data loss all the times (music tapes and floppy discs were not very realiable back then), I thought: Backup!</p> <p>So I wrote a backup program which could duplicate a floppy disc in never-before seen speed: The first version did copy an entire 170 KB disc in only 8 minutes (yes, minutes), the second version did it even in about 4.5 minutes. Whereas the apps before mine took over 25 minutes. (Mind you, the Apple ][, which had its disc OS running on the Apple directly, with fast parallel data access, did this all in a minute or so).</p> <p>And so FCopy for the C-64 was born.</p> <p>It became soon extremely popular. Not as a backup program as I had intended it, but as the primary choice for anyone wanting to copy games and other software for their friends.</p> <p>Turned out that a simplification in my code, which would simply skip unreadable sectors, writing a sector with a bad CRC to the copy, did circumvent most of the then-used copy protection schemes, making it possible to copy most formerly uncopyable discs.</p> <p>I had tried to sell my app and sold it actually 70 times. When it got advertised in the magazines, claiming it would copy a disc in less than 5 minutes, customers would call and not believe it, "knowing better" that it can't be done, yet giving it a try.</p> <p>Not much later, others started to reverse engineer <em>my</em> app, and optimize it, making the comms even faster, leading to copy apps that did it even in 1.5 minutes. Faster was hardly possible, because, due to the limited amount of memory available on the 1541 and the C-64, you had to swap discs several times in the single disc drive to copy all 170 KB of its contents.</p> <p>In the end, FCopy and its optimized successors were probably the most-popular software ever on the C-64 in the 80s. And even though it didn't pay off financially for me, it still made me proud, and I learned a lot about reverse-engineering, futility of copy protection and how stardom feels. (Actually, Jim Butterfield, an editor for a C-64 magazine in Canada, told its readers my story, and soon he had a cheque for about 1000 CA$ for me - collected by the magazine from many grateful users sending 5$-cheques, which was a big bunch of money back then for me.)</p>
<p>I've had to reverse engineer a video-processing app, where I only had part of the source code. It took me weeks and weeks to even work out the control-flow, as it kept using CORBA to call itself, or be called from CORBA in some part of the app that I couldn't access. </p> <p>Sheer idiocy.</p>
23,460
<p>There are lots of questions on how to improve communication between teams. One way to start is to identify what one team actually does that the other team really values and do more of that. </p> <p>For example. Our QA team provided a VM for us with:</p> <ul> <li>The latest release of our server-based commercial software installed and configured (not an easy task in that an installation on-site takes at least 2 days)</li> <li>A database backup of the configured system including sample data</li> <li>an auto-install and configure application that mostly works. (with 12 install packages for the components needed, this is a big time saver)</li> </ul> <p>While we still do most of our testing on our own desktops, this allows us to have a relatively clean environment we can run locally.</p> <p>What has your QA team done for you lately? Conversely, what have you done for your QA team?</p>
<p>"It sucks less."</p> <p>That truly made my day.</p>
<p>"It crashed!" - the bug we were hunting for something like several months was reproduced. </p>
15,750
<p>Inside a windows batch file I'd like to figure out what the fully qualified path name of this batch file is.</p> <p>I have tried <code>%0</code> but this does only gave me the typed command (e.g. just the file name without path or extension).</p>
<pre><code>echo %~f0 </code></pre> <p>works for me.</p> <p>see <code>for /?</code> from <code>cmd</code> and read about variable substitution.</p>
<p>Calling script <code>FIRST.BAT</code>:</p> <pre><code>call second.bat %0 parameter-a parameter-b </code></pre> <p>Called script <code>SECOND.BAT</code>:</p> <pre><code>echo The name of this called script should be "SECOND", proof: %~n0 echo The 1st parameter passed should be "FIRST", proof: %1 shift echo The name of the calling script should be "FIRST", proof: %~n0 echo The 1st parameter should be "parameter-a", proof: %1 </code></pre>
44,672
<p>I have tried to find how to create DLL-s on linux using google, but got very confusing information.</p> <p>Is it possible to write dynamic link libraries on linux? If not, are there other means by which I can call code in another module from several running programs?</p>
<p>That's because DLL is a Windows term. In Linux they are called shared libraries.</p> <p><a href="http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html" rel="noreferrer">http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html</a></p>
<p>I guess .SO files instead of DLL files, meaning shared object, not StackOverflow :), is what you want.</p>
17,572
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
<p>Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.</p> <p>Class A = Articles. Has a StringListProperty which can be queried on it's list elements</p> <p>Class B = Tags. One entity per tag, also keeps a running count of the total number of articles using each tag.</p> <p>Data modifications to A are accompanied by maintenance work on B. Thinking that counts being pre-computed is a good approach in a read-heavy environment.</p>
<p>Many-to-many sounds reasonable. Perhaps you should try it first to see if it is actually expensive.</p> <p>Good thing about G.A.E. is that it will tell you when you are using too many cycles. Profiling for free!</p>
39,074
<p>I have received a content export of a MOSS 2007 site which I need to get replicated in my environment but I am having problems importing it using <code>stsadm</code>.</p> <p>The export was done using <code>stsadm</code> though a command similar to:</p> <blockquote> <p>stsadm -o export -url <a href="http://localhost" rel="nofollow noreferrer">http://localhost</a> -filename C:\Export</p> </blockquote> <p>I'm using the import command such as:</p> <blockquote> <p>stsadm -o import -url <a href="http://myServer" rel="nofollow noreferrer">http://myServer</a> -filename C:\Import</p> </blockquote> <p>Most things go fine until I get an error:</p> <blockquote> <p>Object Reference not set to an instance of an object. at Microsoft.SharePoint.Deployment.RolesImport..ctor(<em>and so on</em></p> </blockquote> <p>Essentially what appears to be the error is with the importing of the role groups from the other server. Because my system is a clean install of MOSS 2007 I don't have the user roles set up which they do, I was expecting the content import to handle that. But really, the roles are not important at all.</p> <p>Is it possible to do a content import but have the roles completely ignored?</p>
<p>No, the only option is to remove the roles in the Manifest.xml file of the content export. If you received the export as a single file, just rename it to .CAB and extract the Manifest.xml file for modification. The XML format is pretty extensive and it might take you some studying to figure out where the roles are. Microsoft has documented the XML schema here: <a href="http://msdn.microsoft.com/en-us/library/bb249989.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb249989.aspx</a></p>
<p>No, the only option is to remove the roles in the Manifest.xml file of the content export. If you received the export as a single file, just rename it to .CAB and extract the Manifest.xml file for modification. The XML format is pretty extensive and it might take you some studying to figure out where the roles are. Microsoft has documented the XML schema here: <a href="http://msdn.microsoft.com/en-us/library/bb249989.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb249989.aspx</a></p>
49,365
<p>I'd like to be able to send a Ruby app to some colleagues without requiring them to install a Ruby interpreter. A single exe would be preferable.</p> <p>I googled and found "RubyScript2Exe".</p> <p>What are your experiences with that? Are there other such tools or are there better approaches altogether than building an exe?</p>
<p>I've used it about 3 times and I haven't had any problems with it and I ran one of the apps on 10 servers and never had any issues. So, I think RubyScript2Exe is about as good as it gets for ruby.</p>
<p>Sorry to be late to the party, but I found this question in my search for trying to do this myself (starting to use SO more and more as a primary resource).</p> <p>Anyway, I have just had success with <a href="http://exerb.sourceforge.jp/index.en.html" rel="nofollow noreferrer">exerb</a>, although I'd add a couple of notes:</p> <ul> <li>The web page says exerb runs on any platform. That is true; however if you "compile" a program calls out to native code, then <code>exerb</code> will embed your system's native code (e.g. Linux <code>.so</code> files) into the .exe. In practice, that means you have to build any significant app on Windows.</li> <li>The web page also says <code>ruby -r exerb/mkrbc</code> but the actual command is <code>ruby -r exerb/mkexy</code>.</li> </ul>
45,397
<p>I dont know if I should use the httpcontext caching or the Enterprise Library Caching Application Block. Also, what is the best pattern for the caching Strategy when deleting or updating an entity that is part of a cached list?</p> <p>Should I remove all of a list from the cache or only remove the item from the cached list? If I update it will I remove the list from the cache or update the entity in it.</p>
<p>There are several approaches to implement caching,httpcontext being the easiest one, but it's not necessarily the worst. Take a look at <a href="http://www.danga.com/memcached/" rel="nofollow noreferrer">memcached</a> or <a href="http://blogs.msdn.com/velocity/" rel="nofollow noreferrer">MS Velocity</a>, both of which can be used as backends for the ASP.NET Cache. Especially memcached has a reputation of doing a really good job.</p> <p>As for caching policy: you have to decide what works best for you.I personally would remove the complete list from the cache upon update/delete rather than trying to find out whether the entity is in the list, since it takes a non-trivial amount of time and you need to take concurrency issues into account (locking the list, since somebody might do an update/delete of another entity). Sometimes it does make sense to update an entity in place (if you have a complete object with all data you need), sometimes it's a waste of time, because due to some state change the entity should move somewhere else (e.g. when you sort by LastChangedDate etc.)</p> <p>Don't forget to optimize your DB code too so that it does not take too much time to refresh the flushed list.</p>
<p>just use [OutputCache(Duration=10, VaryByParam="none")] on every action or even controller you want to cache.</p> <p>from <a href="http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs" rel="nofollow">http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs</a></p>
24,274
<p><strong>Has anyone found a way to run Selenium RC / Selenium Grid tests, written in C# in parallel?</strong></p> <p>I've currently got a sizable test suite written using Selenium RC's C# driver. Running the entire test suite takes a little over an hour to complete. I normally don't have to run the entire suite so it hasn't been a concern up to now, but it's something that I'd like to be able to do more regularly (ie, as part of an automated build)</p> <p>I've been spending some time recently poking around with the Selenium Grid project whose purpose essentially is to allow those tests to run in parallel. Unfortunately, it seems that the TestDriven.net plugin that I'm using runs the tests serially (ie, one after another). I'm assuming that NUnit would execute the tests in a similar fashion, although I haven't actually tested this out. </p> <p>I've noticed that the NUnit 2.5 betas are starting to talk about running tests in parallel with pNUnit, but I haven't really familiarized myself enough with the project to know for sure whether this would work. </p> <p>Another option I'm considering is separating my test suite into different libraries which would let me run a test from each library concurrently, but I'd like to avoid that if possible since I'm not convinced this is a valid reason for splitting up the test suite.</p>
<p>I am working on this very thing and have found <a href="http://www.gallio.org/" rel="noreferrer">Gallio</a> latest can drive mbUnit tests in parallel. You can drive them against a single <a href="http://selenium-grid.seleniumhq.org/" rel="noreferrer">Selenium Grid</a> hub, which can have several remote control servers listening. </p> <p>I'm using the <a href="http://ccnet.gallio.org/Distributables/" rel="noreferrer">latest nightly from Gallio</a> to get the <a href="http://www.gallio.org/api/html/T_MbUnit_Framework_ParallelizableAttribute.html" rel="noreferrer">ParallelizableAttribute</a> and <a href="http://www.gallio.org/api/html/T_MbUnit_Framework_DegreeOfParallelismAttribute.html" rel="noreferrer">DegreeOfParallelismAttribute</a>. </p> <p>Something things I've noticed is I cannot rely on <code>TestSet</code> and <code>TestTeardown</code> be isolated the parallel tests. You'll need the test to look something like this:</p> <pre><code>[Test] public void Foo(){ var s = new DefaultSelenium("http://grid", 4444, "*firefox", "http://server-under-test"); s.Start(); s.Open("mypage.aspx"); // Continue s.Stop(); } </code></pre> <p>Using the <code>[SetUp]</code> attribute to start the Selenium session was causing the tests to not get the remote session from <code>s.Start()</code>.</p>
<p>I don't know if no answer counts as an answer but I'd say you have researched everything and you really came up with the 2 possible solutions... </p> <ul> <li>Test Suite runs tests in parallel</li> <li>Split the test suite up</li> </ul> <p>I am at a loss for any thing else.</p>
11,777
<p>I normally work on single threaded applications and have generally never really bothered with dealing with threads. My understanding of how things work - which certainly, may be wrong - is that as long as we're always dealing with single threaded code (i.e. no forks or anything like that) it will always be executed in the same thread.</p> <p>Is this assumption correct? I have a fuzzy idea that UI libraries/frameworks may spawn off threads of their own to handle GUI stuff (which accounts for the fact that the Windows task manager tells me that my 'single threaded' application is actually running on 10 threads) but I'm guessing that this shouldn't affect me?</p> <p>How does this apply to COM? For instance, if I were to create an instance of a COM component in my code; and that COM component writes some information to a thread-based location (using <code>System.Threading.Thread.GetData</code> for instance) will my application be able to get hold of that information?</p> <p>So in summary:</p> <ol> <li><p>In single threaded code, can I be sure that whatever I store in a thread-based location can be retrievable from anywhere else in the code?</p></li> <li><p>If that single threaded code were to create an instance of a COM component which stores some information in a thread-based location, can that be similarly retrievable from anywhere else?</p></li> </ol>
<p>UI usually has the opposite constraint (sadly): it's single threaded and everything must happen on that thread.</p> <p>The easiest way to check if you are always in the same thread (for, say, a function) is to have an integer variable set at -1, and have a check function like (say you are in C#):</p> <pre><code>void AssertSingleThread() { if (m_ThreadId &lt; 0) m_ThreadId = Thread.CurrentThread.ManagedThreadId; Debug.Assert(m_ThreadId == Thread.CurrentThread.ManagedThreadId); } </code></pre> <p>That said:</p> <p>I don't understand the question #1, really. Why store in a thread-based location if your purpose is to have a global scope ?</p> <p>About the second question, most COM code runs on a single thread and, most often, on the thread where your UI message processing lives - this is because most COM code is designed to be compatible with VB6 which is single-thread.</p> <p>The reason your program has about 10 threads is because both Windows (if you use some of its features like completion ports, or some kind of timers) and the CLR (for example for the GC or, again, some types of timers) may create threads in your process space (technically any program with enough priviledges, can too).</p>
<p>Think about having the model of having a single dataStore class running in your mainThread that all threads can read and write their instance variables to. This will avoid a lot of problems that might arise accessing threads all over the shop.</p> <p>Simple idea, until you reach the fun part of threading. Concurrency and synchronization; simply, if you have two threads that want to read and write to the same variable inside dataStore at the same time, you have a problem.</p> <p>Java handles this by allowing you to declare a variable or method synchronized, allowing only one thread access at a time.</p> <p>I believe some .NET objects have Lock and Synchronized methods defined on them, but I know no more than this.</p>
36,428
<p>My huge 32-bit web services LLBLGen-based data access application is running alone on a dedicated 64-bit machine. Its physical memory consumption steadily grows up to approximately 2GB when the process releases almost all of the allocated space (up to 1,5GB) and continues to grow from that point again. There is no observable increase in Page Input values or other page file usage parameters so it looks like the memory is released rather than being swapped out to page file. I am thinking what kind of profile is this? There is nothing to actually prevent the process from grabbing all memory it can, on the other hand there are unacceptable http internal errors around the memory release - probably the clean-up blocks useful work. What would be a good strategy to make the cleanup less obtrusive, given the above is an acceptable behaviour in the first place.</p>
<p>It sounds like you have a memory leak, the process keeps leaking memory until it crushes with an out-of-memory condition and is then automatically restarted by the server.</p> <p>1.5GB is about the maximum amount of memory a 32 bit process can allocate before running out of address space.</p> <p>Somethings to look for:</p> <ul> <li>Do you do your own caching? when are items removed from the cache?</li> <li>Is there somewhere data is added to a collection every once in a while but never removed?</li> <li>Do you call Dispose on every object that implements IDisposable?</li> <li>Do you access any non-managed code at all (COM objects or using DllImport) or allocate non-managed memory (using the Marshal class for example)? anything that is allocated there is never freed by the garbage collector, you have to free it yourself.</li> <li>Do you use 3rd party libraries or any code from 3rd parties? it can have any of the problems in the list too.</li> </ul>
<p>The Garbage Collector doesn't automatically free memory when it releases objects, it holds on to that memory to help minimise the expense of future mallocs.</p> <p>When a low memory condition is triggered that memory will be returned to the OS and you will see more available memory when looking through task manager. This will normally happen about the 2GB mark, or 3GB if you use the <a href="http://technet.microsoft.com/en-us/library/bb124810.aspx" rel="nofollow noreferrer">relevant switch</a>.</p> <p><code>&lt;contentious&gt;</code></p> <p>By setting objects to null when they are dead you can encourage the GC to reuse the memory consumed by those objects, this limiting the growing consumption of memory.</p> <p>But which objects should you set to null? Big objects, large collections, frequently created objects.</p> <p><code>&lt;/contentious&gt;</code></p> <p><strong>EDIT</strong>: There is evidence to support the value of setting objects to null. See <a href="http://weblogs.asp.net/pwilson/archive/2004/02/14/73033.aspx" rel="nofollow noreferrer">this</a> for detail. Of course there is no <strong>need</strong> to set objects to null, the point is does it help memory management in any way?</p> <p><strong>EDIT</strong>: We need a recent benchmark if such a thing exists rather than continuing to opine.</p>
35,078
<p>We wish to provide people to be able to add some logic to their accounts(say, given a few arguments, how to compute a particular result). So, essentially, this would be tantamount to writing simple business rules with support for conditionals and expressions. However, the challenge is to provide them a simple online editor where they can create the logic (preferably) by completely visual means (drag/drop Expr-tree nodes maybe -- kinda like Y! pipes).</p> <p>Does anybody know of a scripting/macro/domain-specific language that lets people do this? The challenge is the visual editor, since we don't wish to invest in developing the UI to do the editing. The basic requirements would be:<br> 1. Embedded into another language, or run securely (no <code>reboot -n</code> or <code>&lt;JUNK-DANGEROUS-COMMAND&gt; &gt;&gt; ~/.bashrc</code>)<br> 2. Easily accessible to users without coding background (no need of any advanced features)<br> 3. Preferably have a simple GUI based editor to create the logic programs accessible to non-developers (kinda like spreadsheets)<br> 4. Some ability to generate compile-time warnings (invalid code) would be good (Type safety?)<br> 5. Ability to embed some data before execution which is available to the interpreter (Eg., <code>name</code>, <code>birthday</code>, <code>amount</code>) </p> <p>Anybody tried doing something like this and got any ideas? I looked at Lua, Io, Python, Ruby and a host of others, but the challenge essentially is that I don't think non-programmers will be able to understand the code all that much. Something that could be added via "meta-programming" to say a Ruby would be good as well, if an editor could be easily developed!</p>
<p>As a matter fact, Microsoft is developing <a href="http://www.microsoft.com/soa/products/oslo.aspx" rel="nofollow noreferrer">Oslo</a>, which is right up your alley. <a href="http://www.sellsbrothers.com/" rel="nofollow noreferrer">Chris Sells</a> has been writing a lot about it recently.</p> <p>It is designed to be a way to author DSLs and also to visually author these models with a graphical tool called Quadrant. Sounds very very similar to what you are looking for.</p> <p>Open source wise, Ruby I think can be close, as you can see if you look at _whytheluckystiff's Try Ruby or <a href="http://hacketyhack.net/" rel="nofollow noreferrer">Hackety</a>.</p>
<p>I don't think you'll find anything that isn't too generic, especially regarding the GUI editor. There's no generic tools as far as I know that will be able to automatically interface with your program and be able to query data from it and interpret the script into commands in your software -- if there is I'd like to have a copy. Not being flippant, but you <em>will</em> have to do some (probably alot) of work to get this working. It will probably result in you writing a custom DSL.</p>
36,935
<p>I'm looking for for a Jabber library for Delphi, I can see some COM based jabber components. But I'm looking for a real VCL library.</p> <p>Somebody knows one?</p>
<p>You could compile the code that underlies Exodus into a VCL. That code is called JOPL, and can be found at <a href="http://code.google.com/p/exodus/source/browse/#svn/trunk/jopl" rel="noreferrer">Google Code</a>.</p>
<p>Bricksoft have VCL component for MSN,YAHOO,AIM,ICQ and Jabber/GTalk.</p> <p>Pls visit our website <a href="http://www.imcomponents.com/" rel="nofollow noreferrer">http://www.imcomponents.com/</a> if you want to get more information.</p>
21,988
<p>Does anyone know a good C++ class to read (and possibly also write) INI files on Windows Mobile? Ideally this class sould work on Windows mobile 2003, 5 and 6 and be public domain but other alternatives may be interesting.</p>
<p>See this question <a href="https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file">How to read config file entries from an INI file</a>, and this followup <a href="https://stackoverflow.com/questions/146943/help-improve-this-ini-parsing-code">Help improve this INI parsing code</a>, in which I figured out how to do the parsing myself. I can't say what I came up with is the be-all and end-all but it could be a good start.</p> <p>Also, this article was mentioned <a href="http://www.codeproject.com/KB/files/SimpleIni.aspx" rel="nofollow noreferrer">Cross-platform INI configuration files</a>.</p>
<p>Try SimpleIni <a href="http://code.jellycan.com/simpleini/" rel="nofollow noreferrer">http://code.jellycan.com/simpleini/</a> as mentioned at CodeProject.</p> <p>It is C++, single header file, template library with an MIT licence (i.e. commercial use is OK). Include it into your source file and use it. It is cross-platform, supports UTF-8 and legacy encoded files, and can read and write the INI file largely preserving comments and structure, etc. Easiest to check out the page.</p> <p>It's been around for a while and is appears to be used by quite a number of people. I wrote it and continue to support it.</p>
35,417
<p>I have a bunch of records in several tables in a database that have a "process number" field, that's basically a number, but I have to store it as a string both because of some legacy data that has stuff like "89a" as a number and some numbering system that requires that process numbers be represented as number/year.</p> <p>The problem arises when I try to order the processes by number. I get stuff like:</p> <ul> <li>1</li> <li>10</li> <li>11</li> <li>12</li> </ul> <p>And the other problem is when I need to add a new process. The new process' number should be the biggest existing number incremented by one, and for that I would need a way to order the existing records by number.</p> <p>Any suggestions?</p>
<p><a href="http://blog.feedmarker.com/2006/02/01/how-to-do-natural-alpha-numeric-sort-in-mysql/" rel="nofollow noreferrer">Maybe this will help.</a></p> <p>Essentially:</p> <pre><code>SELECT process_order FROM your_table ORDER BY process_order + 0 ASC </code></pre>
<p>You need to cast your field as you're selecting. I'm basing this syntax on MySQL - but the idea's the same:</p> <pre><code>select * from table order by cast(field AS UNSIGNED); </code></pre> <p>Of course UNSIGNED could be SIGNED if required.</p>
25,840
<p>How to calculate minute difference between two date-times in PHP?</p>
<p>Here is the answer:</p> <pre><code>$to_time = strtotime("2008-12-13 10:42:00"); $from_time = strtotime("2008-12-13 10:21:00"); echo round(abs($to_time - $from_time) / 60,2). " minute"; </code></pre>
<p>try this</p> <pre><code>$now = \Carbon\Carbon::now()-&gt;toDateString(); // get current time $a = strtotime(&quot;2012-09-21 12:12:22&quot;); $b = strtotime($now); $minutes = ceil(($a - $b) / 3600); it will get ceiling value </code></pre>
47,674
<p>I have two databases with the same structure. The tables have an integer as a primary key as used in Rails.</p> <p>If I have a patients table, I will have one patient using primary key 123 in one database and another patient using the same primary key in the other database.</p> <p>What would you suggest for merging the data from both databases?</p>
<p>Set both your databases up with entries in config/database.yml, then generate a new migration.</p> <p>Use ActiveRecord::Base.establish_connection to switch between the two databases in the migration like this:</p> <pre><code>def self.up ActiveRecord::Base.establish_connection :development patients = Patient.find(:all) ActiveRecord::Base.establish_connection :production patients.each { |patient| Patient.create patient.attributes.except("id") } end </code></pre> <p>YMMV depending on the number of records and the associations between models.</p>
<p>BTW it probably makes more sense for this to be a rake or capistrano task rather than a migration.</p>
20,428
<p>I have been looking at the Model-View-ViewModel pattern that is suggested by several people out there (especially John Gossman, take a look at this <a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx" rel="nofollow noreferrer">post</a> and this <a href="http://pixel8.infragistics.com/#Episode:9071" rel="nofollow noreferrer">podcast</a>), but <strong>what other patterns (if any) have people used and liked ... and where do they add value?</strong></p> <p>I have also stumbled across:</p> <ul> <li>Model-View-ViewModel</li> <li><a href="http://blogs.southworks.net/jdominguez/2008/04/using-the-presentation-model-in-wpf/" rel="nofollow noreferrer">Presentation Model</a></li> <li><a href="http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx" rel="nofollow noreferrer">DataModel-View-ViewModel</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/cc707841.aspx" rel="nofollow noreferrer">Patterns in Prism</a> (now known as the Composite Application Guidance for WPF)</li> </ul> <p>I would love an active discussion on these above and those I may not have discovered yet.</p>
<p>Another pattern that we have used and loved is the <strong>Attached Behavior pattern</strong> ... using the extensibility mechanism of attached properties in WPF. There are quite a few posts out there on this useful pattern as well.</p> <ul> <li><a href="http://blogs.msdn.com/johngossman/archive/2008/05/16/attachedbehavior-pattern-sample.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/johngossman/archive/2008/05/16/attachedbehavior-pattern-sample.aspx</a></li> <li><a href="http://blogs.msdn.com/johngossman/archive/2008/05/07/the-attached-behavior-pattern.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/johngossman/archive/2008/05/07/the-attached-behavior-pattern.aspx</a></li> <li><a href="http://blogs.msdn.com/dancre/archive/2006/03/04/543854.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/dancre/archive/2006/03/04/543854.aspx</a></li> <li><a href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx</a></li> </ul>
<p>I have been using a variation of the Model-View-Presenter pattern. It has served our purposes pretty well developing various UIs. It is not perfect but it gets the job done well. One of the issues I've had is that I am never satisfied with multi-threaded scenarios. We've recently been making many of our presenters multi-threaded. Since these worker threads, in the end, update the UI, we have had to dispatch actions to the UI through the View's dispatcher. Code was becoming really verbose if every View property checked the dispatcher so because of time constraints, we ended up exposing the View's dispatcher to the Presenter. Not the greatest move if you ask me...</p> <p>We are using a modular UI framework similar to CAB and Prism, so a lot of those patterns apply to us as well.</p> <p>I am also a big fan of Commands in WPF. I haven't been able to play around with Prism's DelegateCommand and CompositeCommand yet, but they sound really nice.</p>
22,083
<p>Our web client needs a way to browse the local network and select location for file storage. This will then be returned to the webpage as a UNC name.</p> <p>On a native client this easily accomplished by using Shell32 functions.</p> <p>I've looked at ASP FileUpload, but that returns the file vs. a specific directory.</p> <p>EDIT: Another option would be to execute this on the clientside using javascript.</p>
<p>If by "web client", you mean a web browser - then you really can't. There's an <a href="http://msdn.microsoft.com/en-us/library/ms535263(VS.85).aspx" rel="nofollow noreferrer">HTML file input</a>, but it requires a file (which is no doubt what ASP FileUpload was using). There's <a href="http://msdn.microsoft.com/en-us/library/bb774065(VS.85).aspx" rel="nofollow noreferrer">Shell.Application.BrowseForFolder</a> and you could <a href="http://www.tek-tips.com/faqs.cfm?fid=5201" rel="nofollow noreferrer">create your own</a> using <a href="http://msdn.microsoft.com/en-us/library/z9ty6h50.aspx" rel="nofollow noreferrer">Scripting.FileSystemObject</a> - but those are Windows only, and would probably be locked down with security restrictions these days.</p> <p>If you're willing to take a dependency on Flash or Silverlight, you could probably build or buy something in them. However, I don't think Silverlight has a built in control for it <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.openfiledialog.filter(VS.95).aspx" rel="nofollow noreferrer">(OpenFileDialog</a> is the closest, but looks to also only allow selecting a folder).</p>
<p>You actually <em>can</em> use the Shell32 functions in C#, see <a href="http://www.pinvoke.net/" rel="nofollow noreferrer">P/Invoke</a>.</p>
30,305
<p>I was just wondering if there is any difference between the two different new object initializers or is it just syntactic sugar. </p> <p>So is:</p> <pre><code>Dim _StreamReader as New Streamreader(mystream) </code></pre> <p>and different to:</p> <pre><code>Dim _StreamReader as Streamreader = new streamreader(mystream) </code></pre> <p>Is there any difference under the hood? or are they both the same? Which one do you prefer to use?</p>
<p>In VB.NET, they're identical. The <code>As New</code> variant is canonical.</p> <p>In VB6, their semantics actually differed (apart form the obvious fact that VB6 didn't allow assignments in declarations): the <code>As New</code> variant would create an object that could never be <code>Nothing</code>. Rather, the runtime would ensure that the object was always properly initialized before each access to it.</p>
<p>I'm not a VB guy, but as far as I can tell they're equivalent. According to <a href="http://msdn.microsoft.com/en-us/library/7ee5a7s1.aspx" rel="nofollow noreferrer">MSDN's description of the Dim statement</a>:</p> <blockquote> <p>If you do not specify datatype, the variable takes the data type of initializer. If neither datatype nor initializer is present, by default, the data type is Object Data Type. If you specify both datatype and initializer, the data type of initializer must be convertible to datatype.</p> </blockquote> <p>I won't pass comment on preference, as I don't use VB (except when answering statements).</p>
37,600
<p>I'm playing around with the locale and I18N stuff in c++ and have been looking for real world examples. I've read through the Josuttis chapter on I18N in his <a href="http://www.josuttis.com/libbook/" rel="noreferrer">book</a> (2nd Edition for C++11 to be released April 2012), and found it useful but with no real world examples to draw from I've no idea if I'm following best practices are committing beginner mistakes. What resources can StackOverflow point me towards both on the web and in print for doing I18N stuff in C++?</p> <p>Also what libraries are available for C++ that makes i18n easier? What's not in the standard library that needs to be? At first glance, it seems that UTF8 support doesn't exist in the standard library.</p> <p>Edit:</p> <p>After doing some more reading, it seems that C and C++ are both Unicode "agnostic". It also seems that for dealing with data encoded in Unicode/UTF8/16/32 one needs to use a third party library. The crux of this is that the standard library itself only thinks about ISO 8859 and related character pages, which change based on what you're locale is set to. That means I probably want to use the ICU library for strings rather than using <code>std::string</code> or even <code>std::wstring</code>.</p>
<p>You've been pointed to <a href="http://www.gnu.org/software/gettext/" rel="nofollow noreferrer">GNU gettext</a>, which allows you to replace literal strings with localized versions at run time - one aspect of localization (which is what happens after you've done the internationalization, when someone actually uses your internationalized code in a specific locale). You've also been pointed to the <a href="http://www.boost.org/" rel="nofollow noreferrer">Boost</a> (in particular <a href="http://www.boost.org/doc/libs/1_61_0/libs/locale/doc/html/index.html" rel="nofollow noreferrer">Boost.Locale</a>) libraries; that is usually a good answer for anything related to C++.</p> <p>Another place you might look is the <a href="http://www.icu-project.org/" rel="nofollow noreferrer">ICU</a> (International Components for Unicode) project. And as a source of data, you might look at the <a href="http://unicode.org/cldr/" rel="nofollow noreferrer">CLDR</a> (Common Locale Data Repository) as a source of information about different locales; the Unicode web site also has lots of information about other aspects of different cultures because it deals with many languages.</p> <p>And as a final resource for now, a rather specialized one, there is the <a href="http://en.wikipedia.org/wiki/tz_database" rel="nofollow noreferrer">Olson Time Zone database</a>, which is updated multiple times each year to keep track of the way different countries change their rules on when to change between winter and summer (daylight saving and standard) time.</p>
<p>You do not need libraries to accomplish this task. See the MS guide for Satellite DLLs <a href="http://support.microsoft.com/kb/188659" rel="nofollow noreferrer">here</a>.</p> <p>If you specify to use Unicode in the project settings and use Unicode String functions (instead of char) then the standard use of Satellite DLLs to hold locale specific data (dialog boxes, Strings etc) will be enough. </p> <p>Windows itself will take care of finding the correct resource so long as the DLL is correctly named. The suffixs needed for the satellite DLLs are <a href="http://www.microsoft.com/globaldev/reference/winxp/langtla.mspx" rel="nofollow noreferrer">here </a>.</p>
23,750
<p>In any language really, im looking for a simple (very simple) way to control the position of a shortcut on the users desktop. I already make the assumption that Auto Arrange and Align to Grid are unchecked.</p> <p>Ex: The program creates the shortcut to the desktop than places it at position (450,302) on the desktop. </p> <p>I know how to create shortcuts, but i dont know how to control their placement on the desktop.</p>
<p>In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.</p> <p>I managed to resolve this using the following steps:</p> <ul> <li><p>Refresh the install using <code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root</code></p></li> <li><p>Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true" rel="nofollow noreferrer">Lockdown Policy Prevents This Request</a> errors that I was seeing. Instructions to <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596ff388-bc4c-472f-b029-aea2b0418bea.mspx?mfr=true" rel="nofollow noreferrer">enable the ASP.Net webservice extension</a> are on MSDN.</p></li> </ul>
<p>When you get the error, it means either:</p> <p>1 The DLL does not need to be registered</p> <p>or</p> <p>2 The DLL is corrupt</p>
12,420
<p>I'm used to passing around string like this in my C++ applications:</p> <pre><code>void foo(const std::string&amp; input) { std::cout &lt;&lt; input.size() &lt;&lt; std::endl; } void bar() { foo("stackoverflow"); } </code></pre> <p>Now I have a case where I want the string to be NULL:</p> <pre><code>void baz() { foo("stackoverflow"); foo(NULL); // very bad with foo implementation above } </code></pre> <p>I could change <code>foo</code> to:</p> <pre><code>void foo(const std::string* input) { // TODO: support NULL input std::cout &lt;&lt; input-&gt;size() &lt;&lt; std::endl; } </code></pre> <p>But to pass a string literal or copy a <code>char*</code> to that implementation of <code>foo</code> I need to write something like this:</p> <pre><code>void bar() { string input("hi"); // annoying temporary foo(&amp;input); foo(NULL); // will work as long as foo handles NULL properly } </code></pre> <p>I started thinking about inheriting from <code>std::string</code> and adding a <code>null</code> property, but I'm not so sure it's a good idea. Maybe it is better to simply use a <code>const char*</code> string for parameters that can be NULL, but what if I want to save a copy of the string (or NULL) without having to manage its memory myself? (See <a href="https://stackoverflow.com/questions/312570/what-are-some-of-the-drawbacks-to-using-c-style-strings">What are some of the drawbacks to using C-style strings?</a> etc.)</p> <p>Any clever solution around?</p>
<p>If you want the type to be null, then make it a pointer. Pass string pointers around instead of references, since this is precisely what pointers can do, and references cant. References always point to the same valid object. Pointers can be set to null, or be reseated to point to another object. Thus, if you need the things pointers can do, use pointers.</p> <p>Alternatively, use boost::optional, which allows a more type-safe way to specify "this variable may or may not contain a value".</p> <p>Or, of course, change the semantics so you either use empty strings instead of null, pass a separate bool parameter specifying whether the string is available or not, or refactor so you don't need this in the first place.</p>
<p>What if you just use:</p> <pre><code>void foo(const char *xinput) { if (xinput == NULL) { // do something exceptional with this return; } std::string input(xinput); // remainder of code as usual } </code></pre> <p>Yes, this does incur an extra allocation and copy, and calling the function is a bit more verbose because you need to use <code>.c_str()</code> in the usual case, but it does give you the semantics you want.</p>
44,422
<p>I have built an application in C# that I would like to be optimized for multiple cores. I have some threads, should I do more?</p> <p><strong>Updated for more detail</strong></p> <ul> <li>C# 2.0</li> <li>Run on Windows Vista and Windows Server 2003</li> </ul> <p><strong>Updated again</strong></p> <ul> <li>This code is running as a service</li> <li>I do not want to have the complete code... my goal here is to get your experience and how to start. Like I say, I have already use threads. What more can I do?</li> </ul>
<p>I'd generalize that writing a highly optimized multi-threaded process is a lot harder than just throwing some threads in the mix. </p> <p>I recommend starting with the following steps:</p> <ol> <li>Split up your workloads into discrete parallel executable units</li> <li>Measure and characterize workload types - Network intensive, I/O intensive, CPU intensive etc - these become the basis for your worker pooling strategies. e.g. you can have pretty large pools of workers for network intensive applications, but it doesn't make sense having more workers than hardware-threads for CPU intensive tasks.</li> <li>Think about queuing/array or ThreadWorkerPool to manage pools of threads. Former more finegrain controlled than latter.</li> <li>Learn to prefer async I/O patterns over sync patterns if you can - frees more CPU time to perform other tasks.</li> <li>Work to eliminate or atleast reduce serialization around contended resources such as disk. </li> <li>Minimize I/O, acquire and hold minimum level of locks for minimum period possible. (Reader/Writer locks are your friend)<br> 5.Comb through that code to ensure that resources are locked in consistent sequence to minimize deadly embrace.</li> <li>Test like crazy - race conditions and bugs in multithreaded applications are hellish to troubleshoot - often you only see the forensic aftermath of the massacre.</li> </ol> <p>Bear in mind that it is entirely possible that a multi-threaded version could perform worse than a single-threaded version of the same app. There is no excuse for good engineering measurement.</p>
<p>Understanding the parallelism (or potential for parallelism) in the problem(s) you are trying to solve, your application and its algorithms is much more important than any details of thread synchronization, libraries, etc.</p> <p>Start by reading <a href="https://rads.stackoverflow.com/amzn/click/com/0321228111" rel="nofollow noreferrer" rel="nofollow noreferrer">Patterns for Parallel Programming</a> (which focuses on 'finding concurrency' and higher-level design issues), and then move on to <a href="https://rads.stackoverflow.com/amzn/click/com/0123705916" rel="nofollow noreferrer" rel="nofollow noreferrer">The Art of Multiprocessor Programming</a> (practical details starting from a theoretical basis).</p>
15,056
<p>I'm investigating an annotation-based approach to validating Spring beans using <a href="https://springmodules.dev.java.net/" rel="nofollow noreferrer">spring modules</a>. In <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html" rel="nofollow noreferrer">this tutorial</a>, the following bean (getters and setters omitted) is used as an example:</p> <pre><code>public final class User { @NotBlank @Length(max = 80) private String name; @NotBlank @Email @Length(max = 80) private String email; @NotBlank @Length(max = 4000) private String text; } </code></pre> <p>The error message that is used if a particular validation rule is disobeyed should follow this format:</p> <pre><code>bean-class.bean-propery[validation-rule]=Validation Error message </code></pre> <p>Examples for the class shown above include:</p> <pre><code>User.email[not.blank]=Please enter your e-mail address. User.email[email]=Please enter a valid e-mail address. User.email[length]=Please enter no more than {2} characters. </code></pre> <p>The fact that the message keys contain the class name presents a couple of problems:</p> <ol> <li>If the class is renamed, the message keys also need to be changed</li> <li><p>If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.</p> <p>Person.email[not.blank]=Please enter your e-mail address.<br> Person.email[email]=Please enter a valid e-mail address.<br> Person.email[length]=Please enter no more than {2} characters.</p></li> </ol> <p>In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:</p> <pre><code>email=email address is invalid </code></pre> <p>This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. </p> <p>An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule</p> <pre><code>badEmail=Email address is invalid </code></pre> <p>This message should be used if I annotate the relevant property like this:</p> <pre><code>@Email(errorCode="badEmail") private String email; </code></pre> <p>However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?</p>
<p>I took a quick look at the <a href="https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/BeanValidator.html" rel="nofollow noreferrer">BeanValidator API</a>, and it looks like you might want to try the <em>errorCodeConverter</em> property.</p> <p>You would need to implement your own <a href="https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/converter/ErrorCodeConverter.html" rel="nofollow noreferrer">ErrorCodeConverter</a>, or use one of the provided implementations?</p> <pre><code>.... &lt;bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader" p:errorCodeConverter-ref="errorCodeConverter" /&gt; &lt;bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" /&gt; .... </code></pre> <p><em>Note: configurationLoader is another bean defined in the config XML used in the tutorial</em></p> <p>Example converter:</p> <pre><code>package contact; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springmodules.validation.bean.converter.ErrorCodeConverter; public class MyErrorCodeConverter implements ErrorCodeConverter { private Log log = LogFactory.getLog(MyErrorCodeConverter.class); @Override public String convertPropertyErrorCode(String errorCode, Class clazz, String property) { log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property)); return errorCode; // &lt;------ use the errorCode only } @Override public String convertGlobalErrorCode(String errorCode, Class clazz) { log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName())); return errorCode; } } </code></pre> <p>Now the properties should work:</p> <pre><code>MyEmailErrorCode=Bad email class Foo { @Email(errorCode="MyEmailErrorCode") String email } </code></pre>
<p>Add the following beans in your <code>applicationContext.xml</code> file.</p> <pre><code>&lt;bean id="configurationLoader" class="org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader" /&gt; &lt;!-- Use the error codes as is. Don't convert them to &lt;Bean class name&gt;.&lt;bean field being validated&gt;[errorCode]. --&gt; &lt;bean id="errorCodeConverter" class="org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter"/&gt; &lt;!-- shortCircuitFieldValidation = true ==&gt; If the first rule fails on a field, no need to check other rules for that field --&gt; &lt;bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader" p:shortCircuitFieldValidation="true" p:errorCodeConverter-ref="errorCodeConverter"/&gt; </code></pre>
18,017
<p>I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know).</p> <p>I've decided to removing the buffer overflows first. To make my bug-hunting easier, what tools can be used to check for buffer overruns?</p>
<p>On Linux I'd use Valgrind.</p>
<p>On Windows for memory leaks/buffer overruns and other runtime error detection you can use:</p> <ul> <li>Boundschecker from Compuware (<a href="http://www.compuware.com/products/devpartner/visualc.htm" rel="nofollow noreferrer">http://www.compuware.com/products/devpartner/visualc.htm</a>)</li> <li>IBM Rational Purify</li> </ul> <p>I think they worth their price if you have large projects that need cleanup.</p>
20,191
<p>I know you can use autoexnt to run a batch file on startup for Windows XP, but that only seems to work for 32-bit machines. I'm running Windows XP x64 on a box, and I need to have a script run on startup (without anyone's logging in). Any ides?</p> <p>Thanks for the help.</p>
<p>Can also use local computer policy to configure startup and shutdown scripts.</p> <p><a href="http://vlaurie.com/computers2/Articles/group_policy_editor.htm" rel="nofollow noreferrer">http://vlaurie.com/computers2/Articles/group_policy_editor.htm</a></p> <p>Has a good walkthrough of how to do it.</p>
<p>On startup meaning Login, or on startup meaning (before anyone logs in)?</p> <p>On login, you could just put a BAT in your Startup folder.</p>
12,946
<p>I can't seem to be able to disable a select box when the select tag is not nested inside a form tag. Some things I tried are (using Firefox 3): (via Jquery)</p> <pre><code>$("#mySelect").attr("disabled", true); $("#mySelect").attr("disabled", "disabled"); </code></pre> <p>(also)</p> <pre><code>document.getElementById('mySelect').disabled = true; document.getElementById('mySelect').disabled = true; </code></pre> <p>Here is the HTML:</p> <pre><code>&lt;select id="mySelect" onchange="updateChoice();"&gt; &lt;option value="1"&gt;First&lt;/option&gt; &lt;option value="2" selected=""&gt;Second&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Must I have this select box inside a form element?</p>
<p>Short answer: No, you don't need to have the select box within a form. </p> <p>Where is your JavaScript currently included with respect to the <code>body</code> tag in your HTML? Remember that if you have inline JavaScript included in the head if your page, then it will fire as the page is loaded. At this point, the select box will not have been parsed and, thus, your code cannot access it in order to disable it.</p> <p>I'm no fan of mixing JavaScript and markup together, but this demo should work for all intents and purposes.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;JavaScript Select Demo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;select id="mySelect" onchange="updateChoice();"&gt; &lt;option value="1"&gt;First&lt;/option&gt; &lt;option value="2" selected=""&gt;Second&lt;/option&gt; &lt;/select&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; document.getElementById('mySelect').disabled = true; &lt;/script&gt; &lt;/html&gt; </code></pre> <p>If, for whatever reason, you have to keep the script located in the page rather than an external file, you could setup an event handler to perform the same functionality after the page has loaded. Rather than keeping code at the bottom of the markup, you can include this in your head node:</p> <pre><code> &lt;head&gt; &lt;title&gt;JavaScript Select Demo&lt;/title&gt; &lt;script type="text/javascript"&gt; window.onload = function() { document.getElementById('mySelect').disabled = true; ; } &lt;/script&gt; &lt;/head&gt; </code></pre> <p>Lastly, rather than incorporate an <code>onchange</code> handler in the attributes of your markup, you could alternatively setup an event handler in your JavaScript to perform the same behavior. <a href="http://docs.jquery.com/Events/change" rel="nofollow noreferrer">jQuery makes this really easy</a>.</p>
<p>When using the jQuery library, make sure the code you write is always enclosed in the <code>$.ready</code> function: </p> <pre><code>$(function () { //Type in your code here }); </code></pre> <p>This makes sure that the <strong>code you write will be executed once the page has finished loading</strong></p>
44,959
<p>Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?</p> <p>I mean, something like Apache Commons' <code>PropertyUtilsBean.copyProperties()</code></p>
<p>If your class does not modify <code>__getitem__</code> or <code>__setitem__</code> for special attribute access all your attributes are stored in <code>__dict__</code> so you can do:</p> <pre><code> nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy </code></pre> <p>If you use python properties you should look at <code>inspect.getmembers()</code> and filter out the ones you want to copy.</p>
<p>At the risk of being modded down, is there <strike>a decent</strike> any use-case for this? </p> <p>Unless we know exactly what it's for, we can't sensibly call it as "broken" as it seems.</p> <p>Perhaps try this:</p> <pre><code>firstobject.an_attribute = secondobject.an_attribute firstobject.another_attribute = secondobject.another_attribute </code></pre> <p>That's the sane way of copying things between instances.</p>
30,214
<p>When I print large prints close to (but not exceeding) the maximum dimensions of the heated build platform on my Anet A8, the brim or skirt or the print itself is printed outside the heated bed, while there is some space left at the opposite sites. It appears as if the print is not in the center.</p> <ul> <li>Why is the print not centered on the bed?<br><em>It was centered in the slicer before generating the G-code.</em></li> <li>How can I center the print to make it fit on the heated build platform?</li> </ul>
<p>When centered in the slicer correctly, without offsets defined in the slicer, the printer is most probably incorrectly configured! Luckily you can do something about that! Basically, you will have to calibrate the printer for a new center.</p> <h2>Printer origin?</h2> <p>First of all, the firmware determines where your origin of the printer is. This implies that you need to properly set bed dimensions and offset values from the end stop switches in the firmware (usually not necessary out-of-the-box, but important when a newer or different firmware version is uploaded). These offsets determine where the origin of the bed plate is located. For Marlin firmware it is very common (for most printers) to have the origin specified at the front left corner (when facing the printer). From the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">configuration of Marlin</a> we find the origin is e.g. in the front-left corner. Note that this can be rotated 180 degrees in certain printers, so the aft-right. Also be aware that there are a few printers that have the origin in the center, e.g. Delta's and a few Cartesian printers. Marlin definition (edited snippet) of a common bed layout:</p> <pre> * +-- BACK ---+ * | | * L | (+) | R * E | | I * F | (-) N (+) | G * T | | H * | (-) | T * | | * O-- FRONT --+ * (0,0) * .(-Xh, -Yh) </pre> <h2>How do I find the physical origin of the printer?</h2> <p>This can be tested by instructing the head/nozzle to go to e.g. (0, 0, 15) using a <a href="/q/10573">terminal/console</a> or a simple G-code file with a move to that coordinate that you print from SD card (e.g. <code>G1 X0 Y0 Z15 F500</code>); <em>note a Z of 15 is chosen for safety!</em>. When this is performed, the nozzle should be at the (elevated, so X, Y) origin as defined by your firmware. Usually this is at the left front corner of your build plate (there may be clips there, so therefore the elevated value), but this may be different depending on the firmware settings or firmware brand.</p> <p>Next step is to configure the slicer as such that this coincides with the actual origin. Incorrect slicer settings can cause the slicer to assume the origin is at a different position than your actual position. In Ultimaker Cura, the &quot;Origin at center&quot; is notoriously known for this when the physical origin is not in the center, but in a corner. When the slicer is properly instructed, but the origin is still not at the corner of the build plate (<strong>beware!</strong> in some printers the origin is in the middle of the plate) you might have incorrect endstop to origin offsets.</p> <h2>Determine the offset first!</h2> <p>To quantify the offset of the center as it is known by the printer software (firmware) it is advised to print a large square that is a few percentage smaller than the maximum size of the bed. E.g. you can create a square hull at e.g. 90 % of the dimensions of the bed (parametric designs are very useful for this purpose, see e.g. <a href="https://www.thingiverse.com/thing:2280529/" rel="nofollow noreferrer">this design</a>). There are many things (<code>.stl</code> models) to be found on the internet. If it includes a cross, even better as some platforms have a mark in the center of the bed.</p> <p><em>Example of a bed center calibration model</em><br> <a href="https://i.stack.imgur.com/9eM3Wm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9eM3Wm.jpg" alt="bed center calibration model" /></a></p> <p>Once printed, measure the distance from every edge from the build platform to the printed square. If you fail to print the square, please check the level of the platform; <strong>this is also an excellent test for the level of your bed!</strong> The measurements should give you a notion of the offset of the bed. E.g. for the X-axis you measure a distance of 12 mm on the left and 8 mm on the right (when facing the printer) you can easily deduce that the center is (12 - 8)/2 = 2 mm to the right (positive X direction). This implies that the printer manufacturer has done a lousy job by delivering you a printer with an offset bed; better said incorrectly configured in their firmware. Note this is not uncommon!</p> <h2>How to fix this!</h2> <p>Once you quantified the offset, you want to be sure that your next print prints in the middle of the bed. How to proceed? Basically there are a couple of solutions you can use, each with its own advantages and disadvantages.</p> <ol> <li><p>A simple solution (i.e. if the printer support this) is to adjust the position of the endstops. Alternatively you can print alternate endstop holders to match the position change as measured from the calibration print.</p> </li> <li><p>Another simple and popular solution is applying an <strong>offset in the slicer</strong>. You could do that in the printer options some of the available slicers. If such options are not available, you could add <strong>G-code commands in the start code</strong> to create the offset (e.g. <code>G1</code> X-2 moves to the left and <code>G92 X0</code> resets the X origin). Note that this is a quick fix and should be applied wisely. The printer does not know where the actual center is! You merely changed if after the homing sequence. Exchanging <code>.gcode</code> with fellow enthusiasts with the same printer may have adverse effects.</p> </li> </ol> <p>A far better solution is to fix the center in the firmware so that the printer knows the <strong>actual</strong> center. This requires some extra effort by uploading firmware (files including configuration settings) to the printer or send G-code commands. The latter option will be discussed first.</p> <ol start="3"> <li>A prerequisite of this method is that it requires the <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">G-code command</a> <code>[M206](https://reprap.org/wiki/G-code#M206:_Offset_axes)</code> to be supported by your firmware; note that not all 3D printer firmware solutions are able to use this G-code command for axes offset definition. E.g. the stock Anet A8 runs a modified Repetier version that does not support <code>M206</code>, it would be time to upload a new firmware like e.g. <a href="https://github.com/MarlinFirmware/Marlin" rel="nofollow noreferrer">Marlin Firmware</a> making this particular printer safer as the stock firmware does not include thermal runaway protection! See question: &quot;<a href="/q/8466/">What is Thermal Runaway Protection?</a>&quot;. To send G-code commands to a printer you have the option to hook up your computer to the printer over USB and use a 3D printer program that support sending commands to the printer (this is called a terminal; i.e. an interface to the printer). Programs like <a href="http://www.pronterface.com/" rel="nofollow noreferrer">PronterFace</a>, <a href="https://www.repetier.com/" rel="nofollow noreferrer">Repetier-Host</a>, <a href="https://octoprint.org/" rel="nofollow noreferrer">OctoPrint</a>, and probably many more have such an interface. A simple alternative that works also is creating a text file (with <code>.gcode</code> extension) with the commands on separate lines and executing the &quot;print&quot;. The following codes need to be sent: <code>M206</code> e.g. <code>M206 X-2 Y2</code> (move center left and to the back, note to use integer values, float values are not allowed!) and store this new center with <code>M500</code>.</li> </ol> <p>The final, best solution is to set it fixed in the firmware. This requires an upload of a more recent configured version of an applicable firmware. See e.g. question: &quot;<a href="/q/5848">How to upload firmware to reprap printer?</a>&quot;. Note that there are different methods to upload a firmware to the board, it is best to search the internet for the applicable method for your board.</p> <ol start="4"> <li>To do that you will have to be comfortable with computer software and tools to build source files and upload binary code to the printer. This depends on the type of firmware you choose and therefore cannot be described for each firmware in detail. Various sources on the internet describe this process. Generally speaking, it requires you to set the bed and offset values/positions correctly. For Marlin Firmware this comes down to changing the settings in the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">configuration file</a>, this is similar in other firmware software solutions:</li> </ol> <pre> // The size of the print bed #define X_BED_SIZE 220 #define Y_BED_SIZE 220 // Travel limits (mm) after homing, corresponding to endstop positions. #define X_MIN_POS -35 ; used to be -33, so 2 mm shift to left now #define Y_MIN_POS -8 ; used to be -10, so 2 mm shift to the back #define Z_MIN_POS 0 #define X_MAX_POS X_BED_SIZE #define Y_MAX_POS Y_BED_SIZE #define Z_MAX_POS 240 </pre>
<p>As to <strong>why</strong> this happens, particularly with a budget printer the end-stop mountings may not be particularly precisely located, or the moving part may actuate the endstop slightly differently in each build. In my case, replacing the hot end (and thus the whole carriage) gave me an offset of some cm. With this upgrade, it was impossible to retain the stock calibration since the extruder dimensions are quite different.</p> <p>As to <strong>how to fix it</strong>, the easiest way for me was to modify the 'start g-code'. This fix only applies to the particular slicer, means that what I slice for my A8 won't be centred on the work maker-club Prusa, but doesn't need me to mess about with firmware or apply a per-model update.</p> <p>After the Z-home operation, I already have a pre-extrude step. Prior to this, I set the actual position of what I want my homed point to be, using <code>G92</code></p> <pre><code>M82 ; absolute extrusion mode G28 ; home all G92 X17 Y-12 ; re-define origin G92 E0.0 ; reset extruder distance position </code></pre>
959
<p>Last time <a href="https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery">I asked about the reverse process</a>, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.</p>
<p>If your form elements have their ID set to the fieldname:</p> <pre><code>$.each(myAssocArry, function(i,val) { $('#'+i).val(val); }); </code></pre>
<p>I have not seen jQuery handle passing a single (non-array) value into val() for a radio or checkbox input. You have to be sure to wrap the single value into an array.</p> <p>I have also typically not wanted to alter the values of button-ish inputs, so I filter those out.</p> <p>Here's a function that handles the array wrapping, button filtering, and also restricts the input selection to a given form element. The form parameter is optional. If left off/null/undefined, then all inputs on the page will be selected.</p> <pre><code>function populateForm(data, form) { $.each( data, function(name, value) { var input = $(":input[name='" + name + "']:not(:button,:reset,:submit,:image)", form ); input.val( ( !$.isArray( value ) &amp;&amp; ( input.is(':checkbox') || input.is(':radio') ) ) ? [ value ] : value ); } ); }; </code></pre>
20,788
<p><em>Out of interest and because it infuriates me, I was wondering if SOmebody here might happen to work for a bank or otherwise know the answer to this.</em></p> <p>I've used a few online banking sites (UK and N.America) and they universally enforce a password pattern of <code>/[\w\d]{6,8}/</code> Sometimes, maybe you get to use underscore, but never ever do you get to have <code>/.{6,20}/</code> that you get (more or less) with just about every !banking site you'll encounter. </p> <p>I have been told that this is to do with storage space, but the maths don't seem to support that. Assuming that banks keep shadow tables for your password record, let's generously say an average of 10 per account, then doubling the allowed length of the password and doubling the bit width of the character set based on an 8char 8bit existing format means an <em>extra</em> 11*2*8 = 176 bytes per account, so ~168Mb per 1M accounts. Let's say it's a gigantic bank supporting 100M accounts - that's still only 16Gb!</p> <p>It can't be that simple can it? Surely my numbers are off base.</p> <p>Or is the answer here that banks being banks they have no better reason for this than they're plodding dinosaurs.</p> <p>Does anyone know a technical reason why my password for www.random.com/forum is stronger than the one for my bank?</p>
<p>I actually work in a bank right now, and have worked in quite a few in the past.</p> <p>The primary reason that this happens is that in general the people who are ultimately responsible for making these decisions are not the people who end up implementing them. The "Business Unit" of a bank are the non-technical business experts who end up making these decisions. In many cases, technical objections will be overruled for political or business reasons. But this isn't exclusive to banking. It happens in any industry where technical considerations are often not the primary concern.</p>
<p>Here is a "bug" I got logged in Bugzilla regarding a site I'd built for a client recently (not a bank, thankfully!):</p> <blockquote> <p>"It seems that the user is forced to use a ! or _ in their password* which seems a bit odd to me. Can this ben updated so that it is a 6 - 8 digit password that can only use alphanumerics?"</p> </blockquote> <ul> <li><em>Actually, it was at least one non alpha-numeric character</em></li> </ul>
44,356
<p>I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.</p>
<p>This is what I've been using for development:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;cross-domain-policy&gt; &lt;allow-access-from domain="*" /&gt; &lt;/cross-domain-policy&gt; </code></pre> <p>This is a very liberal approach, but is fine for my application.</p> <p><strong>As others have pointed out below, beware the risks of this.</strong></p>
<p>In production site this seems suitable:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;cross-domain-policy&gt; &lt;allow-access-from domain="www.mysite.com" /&gt; &lt;allow-access-from domain="mysite.com" /&gt; &lt;/cross-domain-policy&gt; </code></pre>
26,209
<p>Let's say I have a class like this:</p> <pre><code>class ApplicationDefs{ public static final String configOption1 = "some option"; public static final String configOption2 = "some other option"; public static final String configOption3 = "yet another option"; } </code></pre> <p>Many of the other classes in my application are using these options. Now, I want to change one of the options alone and deploy just the compiled class. But if these fields are in-lined in the consumer classes this becomes impossible right?</p> <p>Is there any option to disable the in-lining of compile time constants?</p>
<p>You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.</p> <pre><code>public static final String configOption1 = &quot;some option&quot;.intern(); </code></pre> <p>This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren't creating anything extra.</p> <p>As an alternative you could always do</p> <pre><code>public static final String configOption1 = &quot;some option&quot;.toString(); </code></pre> <p>which might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.</p> <p><strong>Edit:</strong> Found another SO link that gives references to the JLS, for more information on this. <a href="https://stackoverflow.com/questions/1833581/when-to-use-intern">When to use intern() on String literals</a></p>
<p>There is nothing here that says these values should be inlined. You are just declaring some <code>public</code>, <code>static</code> members. Those other classes are using the values of these members. No inlining is asked. Even the <code>final</code> keyword </p> <p>But for <strong>performance reasons</strong>, some JVMs may <strong>inline</strong> these values in those other classes. This is an optimization. No optimization should change the behaviour of a program. So if you change the definition of these members, the JVM should <strong>un-inline</strong> the previous values.</p> <p>This is why there is no way to turn inlining off. Either the JVM does not inline and there is no problem or if it is inlined, the JVM guarantee the un-inlining.</p> <p>I am not sure what happens when you import statically this class. I think (not sure) the inlining is performed and may cause the trouble you mention. If that is the case, you could basically delete the static import and you are ok.</p>
49,480
<p>I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed).</p> <p>Is it possible?</p>
<p>I don't know about .Net, but in win32, the easy way is to call IsUserAnAdmin(). If you need more control, you can open the process token and check with CheckTokenMembership for each group you need to check</p> <p><strong>Edit:</strong> See <a href="http://www.pinvoke.net/default.aspx/advapi32/CheckTokenMembership.html" rel="nofollow noreferrer">pinvoke.net</a> for .NET sample code (Thanks chopeen)</p>
<p>You could loop the groups like i did in this answer:</p> <p><a href="https://stackoverflow.com/questions/45437/determining-members-of-local-groups-via-c#45458">Determining members of local groups via C#</a></p> <p>After reading some more, the easiest thing would be to use the <code>System.DirectoryServices.AccountManagement</code> namespace. Here is how it can be used:</p> <p><a href="http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx" rel="nofollow noreferrer">http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx</a></p> <p>Sample:</p> <pre><code>public static bool IsUserInGroup(string username, string groupname, ContextType type) { PrincipalContext context = new PrincipalContext(type); UserPrincipal user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, username); GroupPrincipal group = GroupPrincipal.FindByIdentity( context, groupname); return user.IsMemberOf(group); } </code></pre>
7,550
<p>I have 4 <code>&lt;select&gt;&lt;/select&gt;</code> elements in my form. Usually when submitting the form you would get this in the url, e.g.</p> <pre><code>index.html?day=01&amp;month=01&amp;year=1999&amp;reporter=Joe+Blogs </code></pre> <p>However in my interface users are switching between the date picker and the person picker. Is it possible to only send the values on the select that is active?</p> <p>[I started writing this to post to you guys but then I had a thought and checked out the disabled attribute of form elements - so in the spirit of stack over flow I have entered my own answer too]</p>
<p>Use the .attr("disabled","disabled") in jQuery.</p>
<p>I would rather prefer to pass the control to the server side for any sort of validation. </p>
45,360
<p>I want to play a movie file or any animation file till the time application not loaded completely.<br> Is there any simple way to do it?</p>
<p>Telling other people what they want to do is questionable. My client WANTS a movie to play and it's only a 3 second movie. It's called branding and if his users don't like it, they'll tell him.</p>
<p>The only way to play a movie is to use the MPMoviePlayer. This takes over the UI and is full screen -- none of your app will show through until the movie is closed.</p> <p>While it sounds cool to have a movie play while the app is loading, on the iPhone, it's really not practical. This is not something you want to do.</p>
44,511
<p>Will Subclipse 1.4.4 work safely with Subversion 1.3.2?</p> <p>I am confused because its <a href="http://subclipse.tigris.org/subclipse_1.4.x/changes.html" rel="nofollow noreferrer">changelog</a> says</p> <blockquote> <p>NOTE: As of Subclipse 1.3.0, the minimum Subversion JavaHL requirement is 1.5.0.</p> </blockquote>
<p>Subclipse requires Subversion 1.5.x on the client. A Subversion 1.5.x client can talk to any 1.x server, all the way back to 1.0.0.</p>
<p>Do you mean whether Subclipse 1.4.4 will work with a server that is 1.3.2? If so, probably yes since clients tend to be updated more often than the servers, and thus they try to be backwards compatible. 1.3.2 is starting to get old though, if the client is based on subversion 1.5.</p>
14,676
<p>Despite my most convincing cries to the contrary, I was recently forced to implement a horizontal drop-down navigation system, so I opted for the friendliest one I could find - <a href="http://www.htmldog.com/articles/suckerfish/dropdowns/" rel="nofollow noreferrer">Son of Suckerfish</a>.</p> <p>I tested in various browsers on my machine and all appeared to be fine. However, some (but not all!) IE7 users are experiencing an issue where sub menus do not close after they have been hovered over. The most annoying thing is that the affected users are using the exact version of IE7 that I am (7.0.5730.13), with the same privacy and security settings (I even had them send screenshots of the tabs in Internet Options) on the same OS (XP). I cannot verify if Vista is affected or not.</p> <p>Obviously trying to debug this issue is a nightmare since I cannot replicate it, so I am wondering if anyone here can and might know how to solve it. I have set up an example page here:</p> <blockquote> <p><a href="http://x01.co.uk/menu_test/" rel="nofollow noreferrer">http://x01.co.uk/menu_test/</a></p> </blockquote> <p>Additionally, there's an annoying flicker on rollover of the sub items which I have also tried to solve with no success, so any help with that would also be appreciated.</p>
<p>This is a problem that occurs in IE7 when another part of the page has focus (ie, you clicked somewhere and then mouse-over the menu). It seems to be an issue with the :hover pseudo-class.</p> <p>Adding a hasLayout trigger to the :hover style should fix the problem. </p> <pre><code>#nav li:hover { position: static; } </code></pre> <p>There are other solutions too. There's a great write-up about the problem here:</p> <p><a href="http://css-class.com/articles/explorer/sticky/index.htm" rel="nofollow noreferrer">Sticky Sons of Suckerfish</a></p>
<p>For testing why not download the Vista IE7 VPC image from MS themselves?</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF</a></p> <p>Not sure about the bug though. Remember having similar issues I think its because you need a JS. Will try and find out</p>
16,074
<p>I just installed Glassfish V2 on my local machine just to play around with it.</p> <p>I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.</p> <p>For instance,</p> <pre><code>http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC </code></pre> <p>How do I retrieve the "name" param in my Java code?</p>
<p>Like this:</p> <pre><code>@Path("/helloWorld") @Consumes({"application/xml", "application/json"}) @Produces({"application/xml", "application/json"}) @Singleton public class MyService { @GET public String getRequest(@QueryParam("name") String name) { return "Name was " + name; } } </code></pre>
<p>By putting:</p> <pre><code>@Context private UriInfo context; </code></pre> <p>in your HelloWorld class, can you access the</p> <pre><code>context.getQueryParameters() ; </code></pre> <p>method to get a map of parameters?</p> <p><a href="http://docs.sun.com/app/docs/doc/820-4867/ggrby?a=view" rel="nofollow noreferrer">http://docs.sun.com/app/docs/doc/820-4867/ggrby?a=view</a></p> <p>Seems to suggest you can :)</p>
12,543
<p>For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default.</p> <p>I've used this to good effect, I think, in my own code. But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here: </p> <ol> <li>avoid doing it, or </li> <li>promote it, with the hope that it will become an idiom.</li> </ol> <p>Example (within a larger method):</p> <pre><code>final Date nextTuesday; initNextTuesday: { GregorianCalendar cal = new GregorianCalendar(); ... // About 5-10 lines of setting the calendar fields nextTuesday = cal.getTime(); } </code></pre> <p>Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.</p> <p>Some people have commented that you don't actually need to name the block. While that's true, a raw block looks even more like a bug, as the intent is unclear. Furthermore, naming something encourages you to think about the intention of the block. The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.</p> <p>Many people have commented that it's best to go straight to small methods. I agree that this should be your first instinct. However, there may be several mitigating factors:</p> <ul> <li>To even consider a named block, the code should be short, one-off code that will never be called elsewhere.</li> <li>A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters. This is especially true when a class is in flux, and the inputs are likely to change from version to version.</li> <li>Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established. A named block is easier (psychologically, at least) to throw away.</li> <li>Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.</li> </ul> <p>Advantages of using the named scope:</p> <ol> <li>Can't accidentally reuse temporary variables</li> <li>Limited scope gives garbage collector and JIT compiler more information about programmer intent</li> <li>Block name provides a comment on a block of code, which I find more readable than open-ended comments</li> <li>Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.</li> </ol> <p>Disadvantages:</p> <p>Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name. (Just like Eclipse does.) And getting something to become idiomatic is an uphill battle.</p> <p>It can be used as an excuse for bad programming habits, such as:</p> <ul> <li>Making huge, monolithic methods where several small methods would be more legible.</li> <li>Layers of indentation too deep to read easily.</li> </ul> <p>Note: I've edited this question extensively, based on some thoughtful responses. Thanks!</p>
<p>I'd just go straight for refactoring into smaller methods. If a method is big enough that it needs breaking up like this, it really needs breaking up into multiple methods if <em>at all</em> possible.</p> <p>While limiting scope is nice, this isn't really what named blocks are for. It's unidiomatic, which is very rarely a good thing.</p>
<p>I have done this in some of my c#. I didn't know you could name the blocks though, I'll have to try that see if it works in c# too. </p> <p>I think the scope block can be a nice idea, because you can encapsulate code specific to something within a block of code, where you might not want to split it out into its own function.</p> <p>As for the disadvantage of nesting them, I see that as more of a fault of a programmer not of scope blocks themselves. </p>
25,173
<p>I need to unzip a compressed file on the fly in my program. It works when I try it on my own linux computer, but for some reason the school computers fail whenever I tell them to do it. To unzip I'm using the following command:</p> <pre><code> zcat /file/address/file.tar.gz </code></pre> <p>and get the error:</p> <pre><code> /file/address/file.tar.gz.Z: No such file or directory </code></pre> <p>I tried looking through the documentation but couldn't find a flag to turn off this odd behavior.</p>
<p>Your school's system still has the old "compress" style utilities rather than the newer GNU "gzip" based ones.</p> <p>You need to use <code>gzcat</code> rather than <code>zcat</code>, assuming that it's available.</p>
<p>gzip --decompress /file/address/file.tar.gz</p>
37,940
<p>When the following two lines of code are executed in a bash script, "ls" complains that the files don't exist:</p> <pre><code>dirs=/content/{dev01,dev02} ls -l $dirs </code></pre> <p>When I run the script with the -x option, it appears to be passing the variable within single quotes (which would prevent globbing):</p> <pre><code>+ dirs=/content/{dev01,dev01} + ls -l '/content/{dev01,dev01}' ls: /content/{dev01,dev01}: No such file or directory </code></pre> <p>If I execute the "ls" command from my interactive shell (sans quotes), it returns the two directories.</p> <p>I've been reading through the Bash Reference Manual (v 3.2) and can't see any reason for filename globbing to not take place (I'm not passing -f to the shell), or anything that I can set to ensure that globbing happens.</p>
<p>I think it is the order of expansions:</p> <blockquote> <p>The order of expansions is: <code>brace expansion</code>, tilde expansion, parameter, <code>variable</code> and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and <code>pathname expansion</code>.</p> </blockquote> <p>So if your variable is substituted, brace expansion doesn't take place anymore. This works for me:</p> <pre><code>eval ls $dirs </code></pre> <p>Be very careful with eval. It will execute the stuff verbatimly. So if dirs contains <code>f{m,k}t*; some_command</code>, some_command will be executed after the ls finished. It will execute the string you give to <code>eval</code> in the current shell. It will pass <code>/content/dev01 /content/dev02</code> to ls, whether they exist or not. Putting <code>*</code> after the stuff makes it a pathname-expansion, and it will omit non-existing paths:</p> <pre><code>dirs=/content/{dev01,dev02}* </code></pre> <p>I'm not 100% sure about this, but it makes sense to me.</p>
<pre><code>ls `echo $dirs` </code></pre> <p>works under cygwin. </p>
48,208
<p>Are there any libraries or resources available for parsing/reading an archived eventlogs?</p>
<p>There is this article <a href="http://www.codeproject.com/KB/string/EventLogParser.aspx?fid=334874&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2018071#xx2018071xx" rel="nofollow noreferrer">Parsing event log(*.evt) file.</a> Then there is the Microsoft <a href="http://msdn.microsoft.com/en-us/library/bb309026(VS.85).aspx" rel="nofollow noreferrer">Event Log file format documentation</a> (evt used on xp win 2003). So far the only information I can find for the new format is a pdf from some <a href="http://www.dfrws.org/2007/proceedings/p65-schuster.pdf" rel="nofollow noreferrer">forensic conference.</a> And <a href="http://blogs.technet.com/askperf/archive/2007/10/12/windows-vista-and-exported-event-log-files.aspx" rel="nofollow noreferrer">how to convert evt to evtx</a></p>
<p>Which IIS version do you use ? If you use IIS 6, You can use Microsoft Log Parser to see it. Download from <a href="http://support.microsoft.com/kb/840671" rel="nofollow noreferrer">IIS 6 Resource Kit</a></p>
47,193
<p>I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwords if I want to limit to say 70 pixels then the examples below show different character counts (9 and 15) both measuring the same:-</p> <p>Welcome M...<br> Hi Iain if I've ...</p> <p>If you look at Yahoo search results they are able to limit the length of title strings and add ellipsis on the end of long strings to indicate more. (try site:loot.com wireless+keyboard+and+mouse to see an example of Yahoo achieving this)</p> <p>Any Ideas?</p>
<p>Perhaps the CSS property <code>overflow: hidden;</code> can help you, in conjuntion with <code>width</code>.</p>
<p>Yahoo does this server-side, the truncation and elipsis ('...') is returned in the HTML. Presumably this is done on a character count, and if thats not an option for you then server-side is out.</p> <p>Other than <code>overflow: hidden</code> I'm not sure CSS can help you here. You could measure the width of the containing element using Javascript, and truncate the text based on that. This could be used in conjunctin with <code>overflow:hidden;</code> so the text elements don't just resize all of a sudden, but you may have to extract the text and add a temporary element onto the page somewhere to do the measurement. Depending on the number of elements to truncate this might not work very well.</p> <p>Another slightly hacky option is to measure the width of an element containing the letter '<code>W</code>', then do a character count and truncate if <code>(char_count * width_of_w) &gt; desired_width</code>.</p> <p>You can use <code>text-wrap: none;</code> to stop text wrapping onto new lines, although this is a CSS3 property and last I checked was only supported by IE (imagine my shock when I found that one out!).</p>
23,736
<p>I have a weird problem with my old 3D printer, it is a Prusa/Mendel type. When I print a 20&nbsp;mm cube, X and Y are correct, Z is resulting 16 to 17&nbsp;mm. I have checked the correctness of the movement on Z using the manual controls and there are no issues.</p> <p>I played a bit with the layer thickness, I have a 0.4&nbsp;mm nozzle, setting the layer height to 0.12&nbsp;mm (normally is on 0.16&nbsp;mm) but no changes in the result. I am printing PLA on a cold bed at 180&nbsp;&deg;C without any other particular defect.</p> <p>I would appreciate some direction on how to solve such problem.</p>
<p>You should check that the steps per mm for your Z-axis are set correctly. This depends on the pitch of the leadscrews/threaded rods driving the axis and parameters of your steppers (microstepping and raw steps/revolution). <a href="http://prusaprinters.org/calculator/" rel="nofollow noreferrer">This Calculator</a>.</p> <p>Make sure that your layer height is a multiple of a full step of the Z-stepper. The Z-stepper may be disabled intermittently, and when re-enabled it may "snap" to the nearest full step position. If your layer height requires microstepping, you may notice it getting rounded down or up due to this.</p> <p>For instance, if a full step were 0.08&nbsp;mm, then 0.16&nbsp;mm layers would require 2 full steps, printing fine. 0.12&nbsp;mm layers would require 1 full step and a half microstep. Due to rounding, some layers might be reduced to 0.08&nbsp;mm instead. This might account for the height discrepancy you're seeing (though 0.08&nbsp;mm is quite a high, unrealistic amount for a full-step).</p>
<p>A suitable test part for this problem, to check if the bad scaling is linear or the result of missing steps (as was identified in this case) would be a ramp, or sequence of steps. You can check the linearity using a straight edge, and would be able to perform repeated tests to identify of there was a specific Z location where steps were more likely to be lost (for example due to some tightness in the motion system).</p>
391
<p>Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it.</p> <p>So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO).</p> <p>The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the <strong>after_initialize</strong> hook. No problem... until I start adding some more mixins.</p> <p>The problem I have, is that I can have an <strong><code>after_initialize</code></strong> in any one of my mixins, so I need to include a <strong>super</strong> call at the start to make sure the other mixin <strong><code>after_initialize</code></strong> calls get called. Which is great, until I end up calling super and I get an error because there is no super to call.</p> <p>Here's a little example, in case I haven't been confusing enough:</p> <pre><code>class Iso &lt; ActiveRecord::Base include Shared::TracksSerialNumberExtension include Shared::OrderLines extend Shared::Filtered include Sendable::Model validates_presence_of :customer validates_associated :lines owned_by :customer order_lines :despatched # Mixin tracks_serial_numbers :items # Mixin sendable :customer # Mixin attr_accessor :address def initialize( params = nil ) super self.created_at ||= Time.now.to_date end end </code></pre> <p>So, if each one of the mixins have an after_initialize call, with a <strong>super</strong> call, how can I stop that last <strong>super</strong> call from raising the error? How can I test that the super method exists before I call it?</p>
<p>You can use this:</p> <pre><code>super if defined?(super) </code></pre> <p>Here is an example:</p> <pre><code>class A end class B &lt; A def t super if defined?(super) puts "Hi from B" end end B.new.t </code></pre>
<p>Rather than checking if the super method exists, you can just define it</p> <pre><code>class ActiveRecord::Base def after_initialize end end </code></pre> <p>This works in my testing, and shouldn't break any of your existing code, because all your other classes which define it will just be silently overriding this method anyway</p>
3,196
<p>My ASP.NET application allows users to upload and download large files. Both procedures involve reading and writing filestreams. What should I do to ensure the application doesn't hang or crash when it handles a large file? Should the file operations be handled on a worker thread for example?</p>
<p>Make sure you properly buffer the files so that they don't take inordinate amounts of memory in the system.</p> <p>e.g. excerpt from a download application, inside the while loop that reads the file:</p> <pre><code>// Read the data in buffer. length = iStream.Read(buffer, 0, bufferSize); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); </code></pre> <p>Where bufferSize is something reasonable, e.g. 100000 bytes, the trade-off is that it will be slower for smaller buffer sizes.</p> <p><a href="http://support.microsoft.com/kb/812406" rel="nofollow noreferrer">http://support.microsoft.com/kb/812406</a></p> <p>Edit: Also be sure that IIS is set to take a large enough <a href="http://dwnz.spaces.live.com/Blog/cns!BCC0973FC7B19D91!643.entry" rel="nofollow noreferrer">request length</a> (IIS7) and timeout.</p>
<p>Unless this is the primary purpose of your site consider partitioning these operations to a separate application, e.g. a sub-application or sub-domain. Besides reducing risk this would also simplify scaling out as your user base grows.</p>
34,808
<p>I'm using the d programing language to write a program, and I'm trying to use ddbg to debug it. When there is an exception, I want to have the program break whenever there is an exception thrown so that I can inspect the stack.</p> <p>Alternatively, is there another debugger that works with d? Is there another way to get a stack trace when there is an exception?</p>
<p>You want to break when there's any exception thrown or just uncaught exceptions? Because I think the latter is already the default behavior.</p> <p>You probably know this, but you get the stack trace by typing 'us' (unwind stack) at the prompt. Just trying to eliminate the obvious.</p> <p>Anyway, I've never had to use onex. Never even heard of it. Another thing you could try is forcing execution to stop by putting in asserts.</p>
<p>Haven't used ddbg yet, but according to the documentation at <a href="http://ddbg.mainia.de/doc.html" rel="nofollow noreferrer">http://ddbg.mainia.de/doc.html</a> there is the</p> <blockquote> <p>onex &lt;cmd; cmd; ...&gt; on exception execute list of commands</p> </blockquote> <p>command.</p>
6,965
<p>My company has been working on a Flex dashboard that displays realtime financial information. It will be deployed over a corporate WAN to perhaps a few dozen users. </p> <p>This is our first Flex project, and while development has been very pleasant, we're a little concerned about what production issues might come up (users not having the right Flash player installed, long download times,BlazeDS performance, etc). </p> <p>Our stack is RDBMS/Spring/BlazeDS (remoting and messaging)/Flex. </p> <p>Does anyone with experience deploying a commercial Flex app have any words of advice?</p>
<p>Your biggest problems are likely to be:</p> <ul> <li>your users not having the correct version of the flash player</li> <li>your users having locked-down desktops and either not being able to download the right version of the player or not being allowed to use the player at all</li> <li>download speeds of the swf if you have a big app</li> <li>intermittent loss of connection to your back-end due to either bugs in your code or unavailable network connection</li> <li>restrictive browser policies </li> </ul> <p>None of these are insurmountable, but you are likely to encounter all of them in the first few months.</p> <p>I am presuming that you have tested your app for performance under reasonable load and will have fixed those scalability issues already :-)</p> <p>HTH</p>
<p>our logs showed that flex apps would randomly drop connections to our servers. We ended up adding automatic retry logic to all of our REST calls.</p>
26,088
<p>I am working on a git repository with a master branch and another the topic branch. I have switched to topic branch and modified a file. Now, if I switched to the master branch, that same file is shown as modified.</p> <p>For example:</p> <p>git status in git-build branch:</p> <pre><code># On branch git-build # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Switch to master branch</p> <pre><code>[root@redbull builder_scripts (git-build)]# git co master M builder_scripts/cvsup_current Switched to branch &quot;master&quot; </code></pre> <p>git status in master branch</p> <pre><code>[root@redbull builder_scripts (master)]# git status # On branch master # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Why is that the file is shown as modified in the master branch even though it was modified in git-build branch?</p> <p>My understanding was that the branches are independent of each other and when I change from one branch to another the changes do not &quot;spill over&quot; from one branch to another. So I am obviously missing something here.</p> <p>Has anyone got a clue stick?</p>
<blockquote> <p>Why is that the file is shown as modified in master branch even though it was modified in git-build branch?</p> </blockquote> <p>The key to remember is that the file was <strong>not</strong> modified in the git-build branch. It was only modified in your working copy.</p> <p>Only when you commit are the changes put back into whichever branch you have checked out</p>
<p>In my experience this &quot;spillover&quot; problem arises because <code>git</code> does not protect &quot;untracked&quot; files from <code>git checkout</code> (only tracked but uncommitted files would be protected, i.e. user would be forced to <code>git commit</code> them before a <code>git checkout</code> is allowed to another branch).</p> <p>If you switch back to the original branch that created these files (and &quot;untracks&quot; them), these files become &quot;untracked&quot; again and can be <code>git add</code>'ed or <code>git rm</code>'ed.</p> <p>For me it looks like a bug: even &quot;untracked&quot; files should be protected from <code>git checkout</code>.</p>
30,564
<p>I have an installation program (just a regular C++ MFC program, not Windows Installer based) that needs to set some registry values based on the type of Internet connection: broadband, dialup, and/or wireless. Right now this information is being determined by asking a series of yes or no questions. The problem is that the person doing the installations is not the same person that owns and uses the computer, so they're not always sure what the answers to these questions should be. Is there a way to programatically determine any of this information? The code is written in C++ (and optionally MFC) for Windows XP and up. .NET-based solutions are not an option because I don't want to have to determine if the framework is installed before our installation program can run.</p> <p>To clarify, the issue is mainly that wireless and dialup connections are not "always-on", which creates a need for our product to behave a different way because our server is not always available. So a strictly speed-measuring solution wouldn't help, though there is a setting that's speed dependent so that the product doesn't try to send MB of information through a dialup connection as soon as it connects.</p>
<p>Use InternetGetConnectedState API to retrieve internet connection state.</p> <p>I tested it and it works fine.</p> <p>I found this document which can help:</p> <p><a href="http://www.pcausa.com/resources/InetActive.txt" rel="nofollow noreferrer">http://www.pcausa.com/resources/InetActive.txt</a></p>
<p>Best bet would be to grab the default active network connection, ensure it is an internet connection (ping google.com or similar) and then ask it what type of device it is. You should be able to determine from that what connection the user has.</p> <p>I'm fairly confident this is possible, but not sure how to go about it though.</p>
11,907
<p>I am looking for a solution or recommendation to a problem I am having. I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.</p> <p>The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel. If we use Excel or even export to CSV, we need to be able to import to move to .resx files. So, what is the best method for this?</p> <p>I am aware of this question, <a href="https://stackoverflow.com/questions/198772/convert-a-visual-studio-resource-file-to-a-text-file">Convert a Visual Studio resource file to a text file?</a> already and the use of Resx Editor but an easier solution would be preferred.</p>
<p>I'm not sure how comprehensive an answer you're looking for, but if you're really just using [string, string] pairs for your localization, and you're just looking for a quick way to load resource (.resx) files with the results of your translations, then the following will work as a fairly quick, low-tech solution.</p> <p>The thing to remember is that .resx files are just XML documents, so it should be possible to manually load your data into the resource from an external piece of code. The following example worked for me in VS2005 and VS2008:</p> <pre><code>namespace SampleResourceImport { class Program { static void Main(string[] args) { XmlDocument doc = new XmlDocument(); string filePath = @"[file path to your resx file]"; doc.Load(filePath); XmlElement root = doc.DocumentElement; XmlElement datum = null; XmlElement value = null; XmlAttribute datumName = null; XmlAttribute datumSpace = doc.CreateAttribute("xml:space"); datumSpace.Value = "preserve"; // The following mocks the actual retrieval of your localized text // from a CSV or ?? document... // CSV parsers are common enough that it shouldn't be too difficult // to find one if that's the direction you go. Dictionary&lt;string, string&gt; d = new Dictionary&lt;string, string&gt;(); d.Add("Label1", "First Name"); d.Add("Label2", "Last Name"); d.Add("Label3", "Date of Birth"); foreach (KeyValuePair&lt;string, string&gt; pair in d) { datum = doc.CreateElement("data"); datumName = doc.CreateAttribute("name"); datumName.Value = pair.Key; value = doc.CreateElement("value"); value.InnerText = pair.Value; datum.Attributes.Append(datumName); datum.Attributes.Append(datumSpace); datum.AppendChild(value); root.AppendChild(datum); } doc.Save(filePath); } } } </code></pre> <p>Obviously, the preceding method won't generate the code-behind for your resource, however opening the resource file in Visual Studio and toggling the accessibility modifier for the resource will (re)generate the static properties for you.</p> <p>If you're looking for a completely XML-based solution (vs. CSV or Excel interop), you could also instruct your translators to store their translated content in Excel, saved as XML, then use XPath to retrieve your localization info. The only caveat being the file sizes tend to become pretty bloated.</p> <p>Best of luck.</p>
<p>If it's in csv here's a quick Ruby script to generate the data elements.</p> <pre><code>require 'csv' require 'builder' file = ARGV[0] builder = Builder::XmlMarkup.new(:indent =&gt; 2) CSV.foreach(file) do |row| builder.data(:name =&gt; row[0], "xml:space" =&gt; :preserve) {|d| d.value(row[1]) } end File.open(file + ".xml", 'w') { |f| f.write(builder.target!) } </code></pre>
27,601
<p>Is it possible to have a CSS rule which basically "undoes" a prior rule?</p> <p>An example:</p> <pre><code>&lt;blockquote&gt; some text &lt;em&gt;more text&lt;/em&gt; other text &lt;/blockquote&gt; </code></pre> <p>and let's say there's this CSS:</p> <pre><code>blockquote { color: red; } </code></pre> <p>...but I want the <code>&lt;em&gt;</code> to remain the normal text color (which you may not necessarily know).</p> <p>Basically, would there be a way to do something like this?</p> <pre><code>blockquote em { color: inherit-from-blockquote's-parent } </code></pre> <hr> <p>Edit: The code I'm actually trying to get this to work on is actually a bit more complicated. Maybe this would explain it better:</p> <pre><code>This text should be *some unknown colour* &lt;ul&gt; &lt;li&gt;This text should be BLUE &lt;ul&gt; &lt;li&gt;Same as outside the UL&lt;/li&gt; &lt;li&gt;Same as outside the UL&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; ul { color: blue; } ul ul { color: ???; } </code></pre>
<p>With CSS alone, you can't refer to a parent's parent. </p> <p>The thing you can do is try a mix of specific CSS selectors and markup so that the desired effect appears. </p> <pre><code>&lt;td&gt; This is the enclosing element. &lt;ul&gt; &lt;li&gt;This is the first level UL, direct child of TD &lt;ul&gt; &lt;li&gt;This is the second level UL&lt;/li&gt; &lt;li&gt;Same as outside the UL&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/td&gt; </code></pre> <p>CSS:</p> <pre><code>td &gt; ul color: blue; /* this affects the "direct child" UL only */ } </code></pre> <p>You would limit the depth of style inheritance to one level, consequently the inner UL is unstyled in regard to color and gets its setup from the enclosing text.</p> <p>Read more on the <a href="http://meyerweb.com/eric/articles/webrev/200006b.html" rel="noreferrer">CSS Child Selector</a>, and be aware that older browsers may have their quirks with them.</p> <hr> <p><strong>EDIT</strong></p> <p>For Internet Explorer 6, the child selector can be faked to some extend. Be sure to fasten seat belts (conditional comments or the like) before using this:</p> <pre><code>td ul { color: expression(/TD/.test(this.parentNode.tagName)? "blue" : "black"); } </code></pre> <p>This assumes "black" as the outer color. If this color value is subject to change, your are out of luck, I'm afraid. Unless you can define an <code>expression()</code> that is able to get the color value from the context (e.g. checking some other properties of parent elements). Or you give up and use a JS framework, as someone else has already suggested.</p> <p>The wimpy solution without having to use JS would of course be:</p> <pre><code>td ul.first { color: blue; } </code></pre> <p>But I can see why you want to avoid that.</p>
<p>Ok, the additional text with example clarifies the question a lot. And I'm affraid that what you want is not possible.</p> <p>If you know the "unknown colour" you can of course repeat the color. But I think CSS needs some mechanism to add variables or references. </p> <p>So you have to stick to the cumbersome:</p> <pre><code>ul { color: blue; } li ul { color: sameenvironment; /* Sorry but you have to add the specific colour here */ } </code></pre>
34,985
<p>Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.</p> <p>I'm wondering about how user controls work in ASP.NET MVC. We have tons of <code>.ASCX</code> controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.</p> <p>What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.</p>
<p>To implement a user control you do the following call:</p> <pre><code>&lt;% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %&gt; </code></pre> <p>You may also see the older syntax which as of PR5 is not valid anymore</p> <pre><code>&lt;%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %&gt; </code></pre> <p>You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.</p>
<p>As Nick suggested, you will indeed be able to render your user controls, but obviously the page-cycle, pagestate and postback from traditional ASP Webforms won't work anymore, thus making your controls most likely useless.</p> <p>I think you'll have to rewrite most of your complex controls to port your website to MVC, while simple controls which, for instance, provide only formatting and have no postback status, should simply work. The code provided by Nick will simply work in this case.</p> <p>And about sharing between more projects: I think controls will be more like "reusable HTML-rendering components" that can be shared across a website, rather than "reusable code components" with logic (like WebForms controls). Your web logic will/should be in the pages controllers and not in the HTML controls. Therefore sharing controls across more projects won't be so useful as in the WebForms case.</p>
6,311
<p>i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.</p> <p>this is the code:</p> <pre><code>[TestMethod] public void TestMethod1() { // Grab the binary data. byte[] data = File.ReadAllBytes("Chick.jpg"); // Read in the data but do not close, before using the stream. Stream originalBinaryDataStream = new MemoryStream(data); Bitmap image = new Bitmap(originalBinaryDataStream); image.Save(@"c:\test.jpg"); originalBinaryDataStream.Dispose(); // Now lets use a nice dispose, etc... Bitmap2 image2; using (Stream originalBinaryDataStream2 = new MemoryStream(data)) { image2 = new Bitmap(originalBinaryDataStream2); } image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception. } </code></pre> <p>Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).</p> <p>I'm really confused :(</p>
<p>As it's a MemoryStream, you really don't <em>need</em> to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See <a href="https://stackoverflow.com/questions/234059">this question</a> for more on this.)</p> <p>However, you <em>should</em> be disposing the Bitmap - and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it "owns" the stream and you shouldn't close it. As <a href="http://msdn.microsoft.com/en-us/library/z7ha67kw.aspx" rel="noreferrer">the docs for that constructor</a> say:</p> <blockquote> <p>You must keep the stream open for the lifetime of the Bitmap.</p> </blockquote> <p>I can't find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.</p>
<p>One strange solution which made my code to work. Open the image in paint and save it as a new file with same format(.jpg). Now try with this new file and it works. It clearly explains you that the file might be corrupted in someway. This can help only if your code has every other bugs fixed</p>
43,633
<p>I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.</p> <pre><code>&lt;img src="pic.jpg" usemap="#picmap" /&gt; &lt;map id="picmap" name="picmap"&gt;&lt;area shape="rect" coords ="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /&gt; &lt;/map&gt; &lt;p id="desc"&gt;&lt;/p&gt; </code></pre> <p>Where in the header I defined these functions:</p> <pre><code> &lt;script type="text/javascript"&gt; function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; &lt;/script&gt; </code></pre> <p>It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). <strong>How can I make the image switching more seamless without reduction in picture quality?</strong> On second thought I realize that I could also just have both images displayed, at a small and a large scale, and <strong>on mouse over they would switch places; How would I do this?</strong> Would this reduce lag? </p>
<p>You don't need to create any page elements, it can all be preloaded using JavaScript:</p> <pre><code>tempImg = new Image() tempImg.src="pic2.jpg" </code></pre> <p>EDIT:</p> <p>If you have a lot of images, you can use the poor-man's multi-preloader:</p> <pre><code>preloads = "red.gif,green.gif,blue.gif".split(",") var tempImg = [] for(var x=0;x&lt;preloads.length;x++) { tempImg[x] = new Image() tempImg[x].src = preloads[x] } </code></pre>
<p>Use <code>display: none;</code>, then have the Javascript change it to <code>display: inline</code> when you want to display it. This has the added advantage of being able to put the image exactly where you want in the page's source, rather than having to add it with Javascript later.</p>
36,614
<p><strong>Is there a tool to generate WiX XML given a .reg file?</strong></p> <hr> <p>In 2.0, you were supposed to be able to run tallow to generate registry XML:</p> <pre><code>tallow -r my.reg </code></pre> <p>For what it's worth, the version of tallow I have is producing empty XML.</p> <p>In 3.0, tallow has been replaced with heat, but I can't figure out how to get it to produce output from a .reg file.</p> <p>Is there a way to do this in 3.0?</p>
<p>I couldn't find a tool, so I made one.</p> <p>The source code may not be elegant, but it seems to work:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Text.RegularExpressions; namespace Reg2Wix { class Program { static void PrintUsage() { Console.WriteLine("reg2wix &lt;input file&gt; &lt;output file&gt;"); } /// &lt;summary&gt; /// Parse the hive out of a registry key /// &lt;/summary&gt; /// &lt;param name="keyWithHive"&gt;&lt;/param&gt; /// &lt;param name="hive"&gt;&lt;/param&gt; /// &lt;param name="key"&gt;&lt;/param&gt; static void ParseKey(string keyWithHive, out string hive, out string key) { if (keyWithHive == null) { throw new ArgumentNullException("keyWithHive"); } if (keyWithHive.StartsWith("HKEY_LOCAL_MACHINE\\")) { hive = "HKLM"; key = keyWithHive.Substring(19); } else if (keyWithHive.StartsWith("HKEY_CLASSES_ROOT\\")) { hive = "HKCR"; key = keyWithHive.Substring(18); } else if (keyWithHive.StartsWith("HKEY_USERS\\")) { hive = "HKU"; key = keyWithHive.Substring(11); } else if (keyWithHive.StartsWith("HKEY_CURRENT_USER\\")) { hive = "HKCU"; key = keyWithHive.Substring(18); } else { throw new ArgumentException(); } } /// &lt;summary&gt; /// Write a WiX RegistryValue element for the specified key, name, and value /// &lt;/summary&gt; /// &lt;param name="writer"&gt;&lt;/param&gt; /// &lt;param name="key"&gt;&lt;/param&gt; /// &lt;param name="name"&gt;&lt;/param&gt; /// &lt;param name="value"&gt;&lt;/param&gt; static void WriteRegistryValue(XmlWriter writer, string key, string name, string value) { if (writer == null) { throw new ArgumentNullException("writer"); } if (key == null) { throw new ArgumentNullException("key"); } if (value == null) { throw new ArgumentNullException("value"); } string hive; string keyPart; ParseKey(key, out hive, out keyPart); writer.WriteStartElement("RegistryValue"); writer.WriteAttributeString("Root", hive); writer.WriteAttributeString("Key", keyPart); if (!String.IsNullOrEmpty(name)) { writer.WriteAttributeString("Name", name); } writer.WriteAttributeString("Value", value); writer.WriteAttributeString("Type", "string"); writer.WriteAttributeString("Action", "write"); writer.WriteEndElement(); } /// &lt;summary&gt; /// Convert a .reg file into an XML document /// &lt;/summary&gt; /// &lt;param name="inputReader"&gt;&lt;/param&gt; /// &lt;param name="xml"&gt;&lt;/param&gt; static void RegistryFileToWix(TextReader inputReader, XmlWriter xml) { Regex regexKey = new Regex("^\\[([^\\]]+)\\]$"); Regex regexValue = new Regex("^\"([^\"]+)\"=\"([^\"]*)\"$"); Regex regexDefaultValue = new Regex("@=\"([^\"]+)\"$"); string currentKey = null; string line; while ((line = inputReader.ReadLine()) != null) { line = line.Trim(); Match match = regexKey.Match(line); if (match.Success) { //key track of the current key currentKey = match.Groups[1].Value; } else { //if we have a current key if (currentKey != null) { //see if this is an acceptable name=value pair match = regexValue.Match(line); if (match.Success) { WriteRegistryValue(xml, currentKey, match.Groups[1].Value, match.Groups[2].Value); } else { //see if this is an acceptable default value (starts with @) match = regexDefaultValue.Match(line); if (match.Success) { WriteRegistryValue(xml, currentKey, (string)null, match.Groups[1].Value); } } } } } } /// &lt;summary&gt; /// Convert a .reg file into a .wsx file /// &lt;/summary&gt; /// &lt;param name="inputPath"&gt;&lt;/param&gt; /// &lt;param name="outputPath"&gt;&lt;/param&gt; static void RegistryFileToWix(string inputPath, string outputPath) { using (StreamReader reader = new StreamReader(inputPath)) { using (XmlTextWriter writer = new XmlTextWriter(outputPath, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.Indentation = 3; writer.IndentChar = ' '; writer.WriteStartDocument(); writer.WriteStartElement("Component"); RegistryFileToWix(reader, writer); writer.WriteEndElement(); writer.WriteEndDocument(); } } } static void Main(string[] args) { if (args.Length != 2) { PrintUsage(); return; } RegistryFileToWix(args[0], args[1]); } } } </code></pre>
<p>I've tried <strong>tallow.exe (version 2.0.5805)</strong> from the latest stable <strong>Wix 2</strong> release and it worked fine for me.</p> <pre><code>tallow -reg my.reg </code></pre> <p>This will generate the markup using Wix 2 <strong>"Registry"</strong> tag that was <strong>deprecated in Wix 3</strong>. Then you have to copy the output into a wix source file and execute <strong>WixCop</strong> utility to convert Wix 2 markup to Wix 3:</p> <pre><code>wixcop my.wxs -f </code></pre>
33,842
<p>According to MSDN </p> <pre><code>form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; </code></pre> <p>is enough to mirrow the form content for RTL languages.</p> <p>But controls placement gets mirrowed only for controls immediately on the form,<br> those inside a GroupBox or a Panel <strong>are not mirrowed</strong>, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt.</p> <p>This is a lot of manual work to place a TableLayoutPanel inside each GroupBox, and especially to rearrange the controls (one control per table cell, padding, margin, etc)</p> <p>Is there an easier way to make mirrowing work for all controls? </p> <p>Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms?</p> <hr> <p><strong>Edit</strong>: RightToLeft property for each control on the form by default is inherited,<br> so Panels and GroupBoxes always have the needed RightToLeft setting.<br> Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.</p>
<p>It does seen that you have quite a nasty problem on your hands. Have played with it for a while and come up with the following:</p> <p>Making use of a little recursion you can run though all the controls and do the manaul RTL conversion for those controls trapped in Pannels and GroupBoxes.</p> <p>This is a <em>quick</em> little mock of code that I slapped together. I would suggest you put this in your BaseForm (heres hoping you have one of these) and call on base form load.</p> <pre><code>private void SetRTL (bool setRTL) { ApplyRTL(setRTL, this); } private void ApplyRTL(bool yes, Control startControl) { if ((startControl is Panel ) || (startControl is GroupBox)) { foreach (Control control in startControl.Controls) { control.Location = CalculateRTL(control.Location, startControl.Size, control.Size); } } foreach (Control control in startControl.Controls) ApplyRTL(yes, control); } private Point CalculateRTL (Point currentPoint, Size parentSize, Size currentSize) { return new Point(parentSize.Width - currentSize.Width - currentPoint.X, currentPoint.Y); } </code></pre>
<p>If you have a class derived from Control that contains child controls (like a <code>ContainerControl</code>), you can add the following code to force all child controls to mirror when the parent form's <code>RightToLeftLayout</code> is set to true and when your control's <code>RightToLeft</code> is set to <code>RightToLeft.Yes</code>.</p> <pre><code>protected override CreateParams CreateParams { get { CreateParams createParams = base.CreateParams; Form parent = this.FindForm(); bool parentRightToLeftLayout = parent != null ? parent.RightToLeftLayout : false; if ((this.RightToLeft == RightToLeft.Yes) &amp;&amp; parentRightToLeftLayout) { createParams.ExStyle |= 0x500000; // WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT createParams.ExStyle &amp;= ~0x7000; // WS_EX_RIGHT | WS_EX_RTLREADING | WS_EX_LEFTSCROLLBAR } return createParams; } } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); RecreateHandle(); } </code></pre>
17,777
<p>I am writing a Java utility that helps me to generate loads of data for performance testing. It would be <em>really</em> cool to be able to specify a regex for Strings so that my generator spits out things that match this.</p> <p>Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there?</p>
<p><strong>Edit:</strong></p> <p>Complete list of suggested libraries on this question:</p> <ol> <li><a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">Xeger</a>* - Java</li> <li><a href="https://github.com/mifmif/Generex" rel="noreferrer">Generex</a>* - Java</li> <li><a href="https://github.com/curious-odd-man/RgxGen" rel="noreferrer">Rgxgen</a> - Java</li> <li><a href="https://github.com/GoranSiska/rxrdg" rel="noreferrer">rxrdg</a> - C#</li> </ol> <p>* - Depends on <code>dk.brics.automaton</code></p> <p><strong>Edit:</strong> As mentioned in the comments, there is a library available at Google Code to achieve this: <a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">https://code.google.com/archive/p/xeger/</a></p> <p>See also <a href="https://github.com/mifmif/Generex" rel="noreferrer">https://github.com/mifmif/Generex</a> as suggested by <a href="https://stackoverflow.com/a/24659605/1820">Mifmif</a></p> <p><strong>Original message:</strong></p> <p>Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps.</p> <p>If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.</p> <p>By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.</p>
<p>If you want to generate "critical" strings, you may want to consider:</p> <p>EGRET <a href="http://elarson.pythonanywhere.com/" rel="nofollow noreferrer">http://elarson.pythonanywhere.com/</a> that generates "evil" strings covering your regular expressions</p> <p>MUTREX <a href="http://cs.unibg.it/mutrex/" rel="nofollow noreferrer">http://cs.unibg.it/mutrex/</a> that generates fault-detecting strings by regex mutation</p> <p>Both are academic tools (I am one of the authors of the latter) and work reasonably well.</p>
4,211
<p>I am trying to use native windows API with Qt using mingw toolset. There are link problems with some functions. What happens? Is this a bug with mingw name mangling?</p> <pre><code>#ifdef Q_WS_WIN HWND hwnd = QWidget::winId(); HDC hdcEMF = CreateEnhMetaFile(NULL, NULL, NULL, NULL ) ; Rectangle(hdcEMF,100,100,200,200); HENHMETAFILE hemf = CloseEnhMetaFile(hdcEMF); OpenClipboard(hwnd); EmptyClipboard(); SetClipboardData(CF_ENHMETAFILE,hemf); CloseClipboard(); #else </code></pre> <p>The errors:</p> <p>undefined reference to `CreateEnhMetaFileW@16'</p> <p>undefined reference to `Rectangle@20'</p> <p>undefined reference to `CloseEnhMetaFile@4'</p>
<p>The functions <code>CreateEnhMetaFileW()</code> and <code>CloseEnhMetaFile()</code> are defined in the static library Gdi32.lib, so you have to make sure to link against that. Try adding <code>-lgdi32</code> to the end of your command line you're using to compile. If that doesn't work, you might have to specify the full path to Gdi32.lib by adding <code>-L/path/to/folder/containing/the/library -lgdi32</code> instead.</p>
<p>It's possible that the functions are included, but getting mangled due to the C++ assumption.</p> <p>Look into the extern C { } declaration. It's intended to declare functions that should not be name mangled to account for polymorphism / overloading. (IE two functions with the same name).</p>
33,571
<p>In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.</p> <p>My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?</p> <p>Psuedocode: (read, don't scrutinize the semantics of the code, I know it won't compile)</p> <pre><code>public DataSet GetData(int identifier) { dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString(); DataSet ds = dataAdapter.Fill(ds); if (ds.table1.Rows.Count == 0) throw new Exception("Data not found"); return ds; } </code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx" rel="nofollow noreferrer">MSDN guidelines</a> state:</p> <ul> <li><p>Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.</p></li> <li><p>Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.</p></li> <li><p>Do not create and throw new exceptions just to have your team's exception.</p></li> </ul> <p>There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException <a href="https://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809">as suggested by Johan Buret</a>.</p> <p>Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.</p>
<p>As far as ADO.net is concerned, a query that returns zero rows is not an error. If your application wishes to treat such a query as an error, you should create your own exception class by inheriting from Exception.</p> <pre><code>public class myException : Exception { public myException(string s) : base() { this.MyReasonMessage = s; } } public void GetData(int identifier) { dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString(); DataSet ds = dataAdapter.Fill(ds); if (ds.table1.Rows.Count == 0) throw new myException("Data not found"); } </code></pre>
14,796
<p>VMware ESX, ESXi, and VirtualCenter are supposed to be able to support HTTP PUT uploads since version 3.5. I know how to do downloads, that's easy. I've never done PUT before.</p> <p>Background information on the topic is here: <a href="http://communities.vmware.com/thread/117504" rel="nofollow noreferrer">http://communities.vmware.com/thread/117504</a></p>
<p>In the <a href="http://www.codeplex.com/vitoolkitextensions" rel="nofollow noreferrer">VI Toolkit Extensions</a> use Copy-TkeDatastoreFile. It will work with binaries.</p>
<p>You should have a look at the <code>Send-PoshCode</code> function in the <a href="http://PoshCode.org/" rel="nofollow noreferrer">PoshCode</a> cmdlets script module ... it uses a POST, not a PUT, but the technique is practically identical. I don't have PUT server I can think of to test against, but basically, set your $url and your $data, and do something like:</p> <pre><code>param($url,$data,$filename,[switch]$quiet) $request = [System.Net.WebRequest]::Create($url) $data = [Text.Encoding]::UTF8.GetBytes( $data ) ## Be careful to set your content type appropriately... ## This is what you're going to SEND THEM $request.ContentType = 'text/xml;charset="utf-8"' # "application/json"; # "application/x-www-form-urlencoded"; ## This is what you expect back $request.Accept = "text/xml" # "application/json"; $request.ContentLength = $data.Length $request.Method = "PUT" ## If you need Credentials ... # $request.Credentials = (Get-Credential).GetNetworkCredential() $put = new-object IO.StreamWriter $request.GetRequestStream() $put.Write($data,0,$data.Length) $put.Flush() $put.Close() ## This is the "simple" way ... # $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8 # write-output $reader.ReadToEnd() # $reader.Close() ## But there's code in PoshCode.psm1 for doing a progress bar, something like .... $res = $request.GetResponse(); if($res.StatusCode -eq 200) { [int]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } else { $output += $encoding.GetString($buffer,0,$count) } if(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } else { $output } } $res.Close(); </code></pre>
9,151
<p>I remember reading that one abstracts the low level calls into a data agnostic framework (eg. ExecuteCommand methods etc), and the other usually contains business specific methods (eg. UpdateCustomer).</p> <p>Is this correct? Which is which?</p>
<p>To me this is a personal design decision on how you want to handle your project design. At times data access and data service are one and the same. For .NET and LINQ that is the case.</p> <p>To me the data service layer is what actually does the call to the database. The data access layer receives the objects and creates them or modify them for the data service layer to make the call to the database.</p> <p>In my designs the Business Logic Layer manipulates the objects based on the business rules, then passes them to the data access layer which will format them to go into the database or the objects from the database, and the data service layer handles the actual database call.</p>
<p>The <strong>Data Service Layer</strong> concept done in the <a href="http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/index.jsp?topic=/com.ibm.commerce.developer.soa.doc/concepts/csddsl.htm" rel="nofollow">WebSphere Commerce</a> documentation is straightforward:</p> <blockquote> <p>The data service layer (DSL) provides an abstraction layer for data access that is independent of the physical schema. The purpose of the data service layer is to provide a consistent interface (called the data service facade) for accessing data, independent of the object-relational mapping framework</p> </blockquote> <p>Currently in internet the <strong>DSL</strong> concept is mainly associated with the <strong>SOAs</strong> (Service Oriented Architectures) but not only. <a href="http://www.codeproject.com/Articles/32237/N-Tier-development-with-ASP-NET-MVC-WCF-and-LINQ" rel="nofollow">Here</a> is mentioned in an example of N-tier applications.</p>
16,143
<p>I'm refactoring a number of classes in an application to use interfaces instead of base classes. Here's the interfaces I created so far:</p> <ul> <li>ICarryable implemented by all Item objects </li> <li>IActable implemented by all Actor objects</li> <li>IUseable implemented by some Item sub-classes</li> <li>IWieldable implemented by some Item sub-classes</li> </ul> <p>You can see the major base-classes are still Item and Actor. These have a common interface in that they both are located on a Map, so they have a Location property. The Map shouldn't care whether the object is an Actor or an Item, so I want to create an interface for it. Here's what the interface would look like</p> <pre><code>public interface IUnnameable { event EventHandler&lt;LocationChangedEventArgs&gt; LocationChanged; Location Location { get; set; } } </code></pre> <p>That's no problem, but I can't think of what to call this interface. IMappable comes to mind by seems a bit lame. Any ideas?</p>
<p>Sounds like an ILocateable. Something whose location you can discover and track.</p>
<p>IWhereYouAtable - Boost mobile</p> <p>ITwentyable - as in what's your 20 (short for 10-20 - CB slang)</p> <p>seriously though ILocateable is good.</p>
25,417
<p>I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.</p> <p>Bonus if I can output in the user's locale date format.</p>
<p>Seems the most foolproof way to start with a UTC date is to create a new <code>Date</code> object and use the <code>setUTC…</code> methods to set it to the date/time you want.</p> <p>Then the various <code>toLocale…String</code> methods will provide localized output.</p> <h3>Example:</h3> <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>// This would come from the server. // Also, this whole block could probably be made into an mktime function. // All very bare here for quick grasping. d = new Date(); d.setUTCFullYear(2004); d.setUTCMonth(1); d.setUTCDate(29); d.setUTCHours(2); d.setUTCMinutes(45); d.setUTCSeconds(26); console.log(d); // -&gt; Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) console.log(d.toLocaleString()); // -&gt; Sat Feb 28 23:45:26 2004 console.log(d.toLocaleDateString()); // -&gt; 02/28/2004 console.log(d.toLocaleTimeString()); // -&gt; 23:45:26</code></pre> </div> </div> </p> <h3>Some references:</h3> <ul> <li><a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleString" rel="noreferrer">toLocaleString</a></li> <li><a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleDateString" rel="noreferrer">toLocaleDateString</a></li> <li><a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleTimeString" rel="noreferrer">toLocaleTimeString</a></li> <li><a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTimezoneOffset" rel="noreferrer">getTimezoneOffset</a></li> </ul>
<p>Don't know how to do locale, but javascript is a client side technology.</p> <pre><code>usersLocalTime = new Date(); </code></pre> <p>will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.</p>
11,065
<p>I'm writing a photo gallery webapp for a friend's wedding and they want a photo gallery for guests to submit the digital photos they take on the day. </p> <p>After evaluating all the options, I've decided the easiest thing for users would be to let them use a familiar interface (their email) and just have them send in the pictures as attachments.</p> <p>I've created an mailbox but now I need to connect and retrieve these attachments for automated processing for adding to the gallery system. But how? Are there any tutorials or prefab classes you've seen for doing this?</p>
<p>What MTA are you using? If you use postfix + maildrop you can create a filtering rule that pipes certain messages through a PHP script that then handles the incoming mails. (google for maildrop and <code>xfilter</code>).</p>
<pre><code>&lt;?php //make sure that submit button name is 'Submit' if(isset($_POST['Submit'])){ $name = $_POST['visitorname']; $email = $_POST['visitoremail']; $message = $_POST['visitormessage']; $to="youremail@yourdomain.com"; $subject="From ".$name; $from = $email; // generate a random string to be used as the boundary marker $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x"; // now we'll build the message headers $headers = "From: $from\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; // next, we'll build the invisible portion of the message body // note that we insert two dashes in front of the MIME boundary // when we use it $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; foreach($_FILES as $userfile) { // store the file information to variables for easier access $tmp_name = $userfile['tmp_name']; $type = $userfile['type']; $name = $userfile['name']; $size = $userfile['size']; // if the upload succeded, the file will exist if (file_exists($tmp_name)) { // check to make sure that it is an uploaded file and not a system file if(is_uploaded_file($tmp_name)) { // open the file for a binary read $file = fopen($tmp_name,'rb'); // read the file content into a variable $data = fread($file,filesize($tmp_name)); // close the file fclose($file); // now we encode it and split it into acceptable length lines $data = chunk_split(base64_encode($data)); } // now we'll insert a boundary to indicate we're starting the attachment // we have to specify the content type, file name, and disposition as // an attachment, then add the file content. // NOTE: we don't set another boundary to indicate that the end of the // file has been reached here. we only want one boundary between each file // we'll add the final one after the loop finishes. $message .= "--{$mime_boundary}\n" . "Content-Type: {$type};\n" . " name=\"{$name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; } } $ok = @mail($to, $subject, $message , $headers); if ($ok) { if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg") &amp;&amp; ($_FILES["file"]["size"] &lt; 20000)) { if ($_FILES["file"]["error"] &gt; 0) { echo "Return Code: " . $_FILES["file"]["error"] . "&lt;br /&gt;"; } else { if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); } } } else { } echo "&lt;span class='red'&gt;E-mail has been sent successfully from $mail_name to $to&lt;/span&gt;"; } else{ echo "&lt;span class='red'&gt;Failed to send the E-mail from $from to $to&lt;/span&gt;"; } } ?&gt; </code></pre> <p>p/s:I used this code.hope its work and assist you.just copy and paste.make sure your textfield name is same as in this page.its work for all types of files.for further questions,just email me at shah@mc-oren.com.anyway,i also in learning process.=).thanks.</p>
14,026
<p>I want to add options to a dropdownbox on my aspx page from the c# code behind during load. I don't know how to get a reference to the control. I have some c# code that is triggered when the user changes the dropdownbox. In that I get a reference to the dropdown with:</p> <pre><code>DropDownBox ddb = (DropDownBox)info.Toolbar.ToolbarItems.Find("ID"); </code></pre> <p>But that won't work if I try it in </p> <pre><code>protected void Page_PreRender(object sender, EventArgs e) { </code></pre> <p>on my aspx.cs</p> <p>What am I missing? Thanks.</p>
<p>If you want the selected item of the dropdown to be automatically selected from viewstate on postbacks you will need to have all the items in the dropdown by the time Page_PreLoad fires. To do this you will want to put your code in Page_Init, at this point the controls are created but viewstate has not yet been injected into them.</p> <p>Take a look here <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">ASP.NET Page Life Cycle Overview</a> for info on the page lifecycle.</p> <p>I see that your dropdown is in a parent container, you may need to call info.EnsureChildControls() before you use Find() if it is not able to get a reference to your control.</p>
<p>PreRender is toward the end of the page lifecycle. Are you sure you want to be making changes there? Sounds like you should be changing items in the dropdown when it is initially bound or when its selection is changed. </p> <p><a href="http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg" rel="nofollow noreferrer">http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg</a></p>
46,205
<p>Is there a quick &amp; dirty way of obtaining a list of all the classes within a Visual Studio 2008 (c#) project? There are quite a lot of them and Im just lazy enough not to want to do it manually.</p>
<p>If you open the "Class View" dialogue (View -> Class View or Ctrl+W, C) you can get a list of all of the classes in your project which you can then select and copy to the clipboard. The copy will send the fully qualified (i.e. with complete namespace) names of all classes that you have selected.</p>
<p>I've had success using <strong><a href="http://www.doxygen.nl/" rel="nofollow noreferrer">doxygen</a></strong> to generate documentation from the XML comments in my projects - a byproduct of this is a nice, hyperlinked list of classes.</p>
11,661
<p>I have a table in the database that I'm retrieving using LINQ to SQL, and as a part of my processing I want to add to this list, then update the database with the new items + any changes I've made.</p> <p>What I thought I could do was this:</p> <pre><code>var list = (from item in db.Table select item).ToList(); [do processing where I modify items &amp; add to the list] list = list.Distinct(); db.SubmitChanges(); </code></pre> <p>What happens is that the modifications happed (ie. SQL updates) but any new items I add to the list don't get added.</p> <p>Obviously I'm doing this wrong, what is the correct way to modify &amp; add to a list of DB entities, then commit all the updates &amp; inserts?</p>
<p>The List is meaningless. It's just happens to hold objects that the DataContext knows about. We need to make sure that the DataContext knows about the new ones. The important thing is that they don't have to be complete when we alert the DataContext to them:</p> <pre><code>Item item; if (needNewOne) { item = new Item(); db.InsertOnSubmit(item); } else { item = list[i]; } /// build new or modify existing item /// : db.SubmitChanges(); </code></pre>
<p>You have to add the new items via InsertOnSubmit.</p>
22,525
<p>I'm getting seemingly random lines scattered across the top surface of my prints:</p> <p><img src="https://i.stack.imgur.com/UdXPx.jpg" alt="lines1"> <img src="https://i.stack.imgur.com/gf0OH.jpg" alt="lines2"></p> <p>Printer: Anycubic i3 mega<br> Slicer: Cura 3.2.1<br> Printer chosen in Cura: Prusa i3, <em>Gcode flavor</em> changed to <em>RepRap</em><br> Cura Profile: <em>Fine</em>, "Outer before inner walls" enabled</p> <p>What might be the reason?</p>
<p>Our local library has a genuine Prusa i3 Mk2.5 that recently had this problem. Because of the number of fingers engaging such a system, it was not immediately discovered that a different profile had been selected in which the Z-hop was turned off.</p> <p>Z-hop is a feature in which the nozzle lifts slightly (and is height-adjustable) as it moves from one portion of the print to another.</p> <p>According to my brief research, Cura supports z-hop in the settings. Either it has to be activated or perhaps slightly increased. The aforementioned Prusa works great with 0.5 mm lift.</p>
<p>It seems like the issue may only be that your nozzle has developed a bit of oozing. The g code likes to repeat the same patterns for at least a few layers every time it changes patterns and if it does the same pattern on the top 3-4 layers than by the time it reaches the last layer on the top that pattern will actually be the slightest bit raised above the rest of the layers because of the ooze building up along the same pattern for how many ever layers it followed the same pattern. Your nozzle is than rubbing on that raised pattern when it completes the last layer. This explains the randomness like OP said because the g code may not repeat the same pattern for 3 or more layers at the surface but without reading the gcode it would seemingly be random when and where they occurred. And truthfully if its a small oozing you could reprint this and it could be gone if you changed almost any setting in cura because the g code would be recalculated differently and new patterns would be chosen but so long as the new gcode did not have the same pattern repeat itself on the top 3 or so layers you would not have these raised patterns for the nozzle to rub on when finishing the top last layer. </p>
840
<p>I've never managed to move from unit-testing to integration-testing in any graceful or automated way when it comes to network code.</p> <p><strong>So my question is</strong>: Given a simple single-threaded client/server based network application, how would you go about integrating both client and server into your currently favorite testing suite (I currently use <a href="http://check.sourceforge.net/" rel="nofollow noreferrer">check</a>).</p> <p>I am of course willing to change unit-test suite to accomplish my goal.</p> <p><strong>Edit</strong>: While I appreciate the answers, I was more looking for some magical way of integrating integration-testing into my unit-test framework (if it's possible at all). Like if <em>fork</em>() or something could be applied without getting too many side effects.</p>
<p>Another approach is to mock up both ends with a dummy server and dummy client that just send the messages that you want to test and verify the responses are as expected. These mock servers cab be really, really dumb: they only need to read/write sockets and dump pre-set data back. You can spiff them up a bit by templating the responses from data in the requests if it's easy to parse.</p> <p>The win here is that you know exactly what the mocked item is going to do (including fake timeouts, send garbage, whatever you want).</p> <p>It would probably be very easy to use a Perl or Python socket library to build your mock servers and clients; if you use Perl, you should be able to use the very capable Test:: classes from CPAN to help do the actual "did this work" and reporting.</p>
<p>We structure our applications so that the core code is in a library and the executable is generated from a main.c (really main.cxx in our case) that is just a very thin wrapper that starts the server or client. This lets us set up test suites that can instantiate a complete server and client in proc and do tests where they talk to one another using their normal network protocol. It works quite well.</p> <p>If you can't structure things this way, you could start your usual server executable using fork/CreateProcess and then have the client code inside the test talk to the external server.</p>
43,916
<p>Is there anyway to use unicode strings (most probably in UTF-8, but could be any encoding) in PostScript?</p> <p>So far, i've been using this function to transforms fonts to Latin1 encoding:</p> <pre><code>/latinize { findfont dup length dict begin { 1 index /FID ne {def}{pop pop} ifelse }forall /Encoding ISOLatin1Encoding def currentdict end definefont pop }bind def /HelveLat /Helvetica latinize /HelveLatbold /Helvetica-Bold latinize </code></pre> <p>but i really don't like it.</p>
<p>Not really or in any simple &quot;out of the box&quot; way. See <a href="https://web.archive.org/web/20120322112530/http://en.wikibooks.org/wiki/PostScript_FAQ#Does_PostScript_support_unicode_for_CJK_fonts.3F" rel="nofollow noreferrer">this FAQ entry for details</a>.</p>
<p>This may or may not fit your bill, but the interpreter that I wrote (<a href="http://code.google.com/p/xpost/" rel="nofollow">xpost</a>) uses Cairo for all its graphics and font functions, including <code>show</code>. So whatever support Cairo has to offer, xpost doesn't get in the way. But before you get too excited, it's a one-man project, and doesn't quite offer full Level-1 Postscript yet. </p> <p>Edit: The newest version does not support this. <a href="http://code.google.com/p/xpost/downloads/detail?name=xpost2g.zip" rel="nofollow">Here</a> is the last version that did (<a href="http://code.google.com/p/xpost/downloads/detail?name=xpost2.pdf" rel="nofollow">listing</a>).</p> <hr> <p>Here's my C code for the show operator itself.</p> <pre><code>OPFN_ void show(state *st, object s) { char str[s.u.c.n+1]; memcpy(str, STR(s), s.u.c.n); str[s.u.c.n] = '\0'; //printf("showing (%s)\n", str); if (st-&gt;cr) { cairo_show_text(st-&gt;cr, str); cairo_surface_flush(st-&gt;surface); XFlush(st-&gt;dis); } } </code></pre> <p>And from the <a href="http://cairographics.org/manual/" rel="nofollow">Cairo docs</a>:</p> <blockquote> <p>cairo_show_text ()</p> <p>void cairo_show_text (cairo_t *cr,<br> const char *utf8);</p> <p>A drawing operator that generates the shape from a string of UTF-8 characters, rendered according to the current font_face, font_size (font_matrix), and font_options.</p> <p>This function first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph.</p> <p>After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for easy display of a single logical string with multiple calls to cairo_show_text().</p> <p>Note: The cairo_show_text() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See cairo_show_glyphs() for the "real" text display API in cairo. </p> <p><a href="http://www.cairographics.org/manual/cairo-text.html#cairo-show-text" rel="nofollow">http://www.cairographics.org/manual/cairo-text.html#cairo-show-text</a></p> </blockquote> <p>So it's UTF-8 in Postscript, near as I can figure! :)</p>
34,029
<p>I am using the jQuery tableSorter plugin on a page.</p> <p>Unfortunatley, the table that is being sorted is dynamically modified, and when I sort after adding an element, the element disappears, restoring the table to the state that it was in when the tableSorter was created.</p> <p>Is there any way that i can force tableSorter to rescan the page so that these new elements are sorted properly?</p>
<p>I believe you can trigger an update using something like:</p> <pre><code>$(table).trigger("update") </code></pre>
<p>The <code>$(table).trigger("update");</code> throws error </p> <pre><code> Uncaught TypeError: Cannot read property 'rows' of undefined </code></pre> <p>So, there is a jquery function <code>.ajaxStop()</code> where <code>tablesorter()</code> is called. Do not call tablesorter in <code>.ready()</code></p> <pre><code> jQuery(document).ajaxStop(function(){ jQuery("#table_name").tablesorter(); }) </code></pre> <p>which did the job</p>
30,718
<p>I use screen to persist my work session and connect to the same session from multiple machines. How can I setup SSH and screen such that the XDISPLAY variable <em>inside</em> my persistent screen session is always set to the machine I am currently connecting from?</p> <p>ie. I start the screen session at work and use gvim, which uses the X server running on my work machine. Later, I connect to the same session from home and also want to use gvim. But this time, I want gvim to use the X server on my home machine. I realize I could manually update XDISPLAY every time I connect from a different machine but I'd rather have an automated system.</p> <p>Bonus points if I can actually <em>move</em> gvim from my work machine to my home machine while it is running. I tried <a href="http://manpages.ubuntu.com/manpages/hardy/man1/xmove.html" rel="nofollow noreferrer">xmove</a> but could never get it to play nice.</p>
<p>The following is a manual solution, but there's no reason you couldn't use an alias or a script to have it done automagically when you remotely log in.</p> <p>Assuming that your local shell sets the DISPLAY variable appropriately, you could use <code>screen -X</code> to send the following commads to your remote screen before connecting.</p> <pre><code># set future remote shells started by screen to have the correct XDISPLAY % screen -X "setenv XDISPLAY $DISPLAY" #... # set up the keystroke F1 to update the XDISPLAY in current shells % screen -X "bindkey -k k1 stuff export XDISPLAY=$DISPLAY\015" #... </code></pre> <p>If you know that all your windows were left in a shell (not a running editor or some such), you could use <code>:at</code> to change the <code>XDISPLAY</code> rather than a key binding:</p> <pre><code># update the XDISPLAY in all current windows % screen -X "at % stuff export XDISPLAY=$DISPLAY\015" #... </code></pre> <p>Alternately, if you know some way of grabbing a parent process's environment variable value, then you could use that together with your shell's prompt hook to grab SCREEN's value of XDISPLAY (as set by setenv) and update it for the shell.</p>
<p>There is no "trivial" way to change environment variables in foreign processes.</p> <p>A straightforward solution might be to persist your <code>XDISPLAY</code> into a file on login and use a <code>PROMPT_COMMAND</code> to read this file before printing the next prompt.</p> <hr> <p>For moving X applications around look at something like <a href="http://en.wikipedia.org/wiki/X11vnc" rel="nofollow noreferrer"><code>X11vnc</code></a> or <a href="http://www.realvnc.com/products/free/4.1/man/Xvnc.html" rel="nofollow noreferrer"><code>Xvnc</code></a>.</p>
30,494
<p>i'm having a problem to create a text_field without a method association. Maybe i even don't need it :-)</p> <p>I have two radio_buttons associated to the same method:</p> <pre><code>&lt;%= radio_button :comment, :author, "anonymous" %&gt; Anonymous &lt;br&gt; &lt;%= radio_button :comment, :author, "real_name" %&gt; Name &lt;br&gt; </code></pre> <p>What i would like to do is to have an text_field which when the user click on the radio_button "real_name" i can verify the value in this new text_field. </p> <p>Basically my Controller would be something like:</p> <p>@comment = Comment.new(params[:comment])</p> <p>if @comment.author == "real_name" @comment.author = "value-from-the-new-textfield end</p> <p>There is any way to do it?</p> <p>Regards,</p> <p>Victor</p>
<p>If you want to generate a text_field without an associated object/method, use <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormTagHelper.html#M001701" rel="noreferrer"><code>text_field_tag</code></a></p>
<p><code>text_field_tag</code> is definitely the easiest way, but if you want to add a field that acts as part of a model, adding an <code>attr_accessor</code> attribute might be worth looking into as well.</p>
24,815
<p>I cannot get a two-way bind in WPF to work. </p> <p>I have a string property in my app's main window that is bound to a TextBox (I set the mode to "TwoWay"). </p> <p>The only time that the value of the TextBox will update is when the window initializes. </p> <p>When I type into the TextBox, the underlying string properties value does not change. </p> <p>When the string property's value is changed by an external source (an event on Click, for example, that just resets the TextBox's value), the change doesn't propagate up to the TextBox.</p> <p>What are the steps that I must implement to get two-way binding to work properly in even this almost trivial example?</p>
<p>Most probably you're trying to bind to a .net CLR property instead of a WPF dependencyProperty (which provides Change Notification in addition to some other things).<br> For normal CLR property, you'd need to implement INotifyPropertyChanged and force update on the textbox in the event handler for PropertyChanged. </p> <ul> <li>So make your object with the property implement this interface, raise the event in the property setter. (So now we have property change notification)</li> <li>Make sure the object is set as the DataContext property of the UI element/control</li> </ul> <p>This threw me off too when I started learning about WPF data binding.</p> <p><strong>Update:</strong> <em>Well OP, it would have been a waste of time if i was barking up the wrong tree.. anyways now since you had to dig a bit.. you'll remember it for a long time.</em> Here's the code snippet to round off this answer. Also found that updating the textbox happens automatically as soon as I tab-out.. You only need to manually subscribe to the event and update the UI if your datacontext object is not the one implementing INotifyPropertyChanged.</p> <p>MyWindow.xaml</p> <pre><code>&lt;Window x:Class="DataBinding.MyWindow" ... Title="MyWindow" Height="300" Width="300"&gt; &lt;StackPanel x:Name="TopLevelContainer"&gt; &lt;TextBox x:Name="txtValue" Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" /&gt; &lt;TextBlock TextWrapping="Wrap"&gt;We're twin blue boxes bound to the same property.&lt;/TextBlock&gt; &lt;TextBox x:Name="txtValue2" Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>MyWindow.xaml.cs</p> <pre><code>public partial class MyWindow : Window, INotifyPropertyChanged { public MyWindow() { InitializeComponent(); this.MyDotNetProperty = "Go ahead. Change my value."; TopLevelContainer.DataContext = this; } private string m_sValue; public string MyDotNetProperty { get { return m_sValue; } set { m_sValue = value; if (null != this.PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs("MyDotNetProperty")); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } </code></pre>
<p>Make sure that the binding specifies two way and when the property has a change, it is immediately transmitted to the holding property.</p> <pre><code> &lt;TextBox Text=&quot;{Binding TextBuffer, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}&quot;/&gt; </code></pre> <p>The above assures that the <code>TextBox</code> input control <code>Text</code> property binds to, then sends the changes back to the string property named <code>TextBuffer</code> in an immediate, <code>PropertyChanged</code>, and <code>TwoWay</code> fashion.</p>
41,389
<p>I'm in the process of designing a PHP-based content management system for personal use and eventually to be distributed. I know there are a lot of CMS's already out there, but I really haven't found one that meets my all of my needs and I also would like to have the learning experience. Security is a large focus, as are extensibility and ease of use. For those of you out there who have built your own CMS, what advice can you offer? What features are essential for a core? What are must have add-ons? What did you wish you knew before starting? What's the biggest potential roadblock/problem? Any and all advice is welcome.</p> <p>Edit: Any advice on marketing do's and don't's would also be appreciated.</p>
<p>In building a few iterations of CMSs, some of the key things turned out to be:</p> <ul> <li>Having a good rich text editor - end-users really don't want to do HTML. Consensus seems to be that FCKEditor is the best - there have been a couple of questions on this here recently</li> <li>Allowing people to add new pages and easily create a menu/tab structure or cross-link between pages</li> <li>Determining how to fit content into a template and/or allowing users to develop the templates themselves</li> <li>Figuring out how (and whether) to let people paste content from Microsoft Word - converting magic quotes, emdashes and the weirdish Wordish HTML</li> <li>Including a spellchecking feature (though Firefox has something built-in and iespell may do the job for IE)</li> </ul> <p>Some less critical but useful capabilities are: - Ability to dynamically create readable and SEO-friendly URLs (the StackOverflow way is not bad) - Ability to show earlier versions of content after it's modified - Ability to have a sandbox for content to let it be proofread or checked before release - Handling of multiple languages and non-English/non-ASCII characters</p>
<p>Just use Drupal.</p> <p>Out of the box it is very light and fast. You add modules for virtually everything, so that can be daunting but it is fantastic.</p> <p>Its secure (NASA and The White House use it), its modular, its open-source, it is well supported, has a reputation for clean APIs, and has hundreds of modules from SEO to Wysiwyg....</p>
10,231
<p>Spring IoC container gives you <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-arbitrary-method-replacement" rel="nofollow noreferrer">an option</a> of replacing a method of a bean. Can someone provide a real life example of using this feature to solve real life problem?</p> <p>I can see this used for adapting an old legacy code (w/o sources) to work with your app. But I think I would consider writing an adapter class using the legacy code directly instead of Spring method replacement approach.</p>
<p>As the documentation says, it's not "commonly useful" functionality.</p> <p>A case where it may be useful though is to alter the functionality of a third party method (you don't necessarily have the source) of a final class - i.e. one whose functionality can't be modified or extended through inheritance.</p> <p>I guess it would still amount to something of a hack though :)</p>
<p>Using spring IoC now I can change my Lucene Analyzers to whatever I want just changing a configuration file.</p> <pre><code>&lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;file.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="DocumentAnalyzer" class="${lucene.document_analyzer}"&gt; &lt;/bean&gt; &lt;bean id="QueryAnalyzer" class="${lucene.query_analyzer}"&gt; &lt;/bean&gt; &lt;bean id="IndexSearcher" class="org.apache.lucene.search.IndexSearcher" scope="prototype"&gt; &lt;constructor-arg&gt; &lt;value&gt;${lucene.repository_path}&lt;/value&gt; &lt;/constructor-arg&gt; &lt;/bean&gt; </code></pre> <p>and then in the code:</p> <pre><code>Analyzer analyzer = (Analyzer) BeanLoader.getFactory().getBean("DocumentAnalyzer"); </code></pre>
35,451
<p>The following is okay:</p> <pre><code>try { Console.WriteLine(&quot;Before&quot;); yield return 1; Console.WriteLine(&quot;After&quot;); } finally { Console.WriteLine(&quot;Done&quot;); } </code></pre> <p>The <code>finally</code> block runs when the whole thing has finished executing (<code>IEnumerator&lt;T&gt;</code> supports <code>IDisposable</code> to provide a way to ensure this even when the enumeration is abandoned before it finishes).</p> <p>But this is not okay:</p> <pre><code>try { Console.WriteLine(&quot;Before&quot;); yield return 1; // error CS1626: Cannot yield a value in the body of a try block with a catch clause Console.WriteLine(&quot;After&quot;); } catch (Exception e) { Console.WriteLine(e.Message); } </code></pre> <p>Suppose (for the sake of argument) that an exception is thrown by one or other of the <code>WriteLine</code> calls inside the try block. What's the problem with continuing the execution in <code>catch</code> block?</p> <p>Of course, the yield return part is (currently) unable to throw anything, but why should that stop us from having an enclosing <code>try</code>/<code>catch</code> to deal with exceptions thrown before or after a <code>yield return</code>?</p> <p><strong>Update:</strong> There's an <a href="https://web.archive.org/web/20080818052536/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx" rel="noreferrer">interesting comment from Eric Lippert here</a> - seems that they already have enough problems implementing the try/finally behaviour correctly!</p> <p>EDIT: The MSDN page on this error is: <a href="http://msdn.microsoft.com/en-us/library/cs1x15az.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cs1x15az.aspx</a>. It doesn't explain why, though.</p>
<p>I suspect this is a matter of practicality rather than feasibility. I suspect there are very, very few times where this restriction is <em>actually</em> an issue that can't be worked around - but the added complexity in the compiler would be very significant.</p> <p>There are a few things like this that I've already encountered:</p> <ul> <li>Attributes not being able to be generic</li> <li>Inability for X to derive from X.Y (a nested class in X)</li> <li>Iterator blocks using public fields in the generated classes</li> </ul> <p>In each of these cases it would be possible to gain a little bit more freedom, at the cost of extra complexity in the compiler. The team made the pragmatic choice, for which I applaud them - I'd rather have a slightly more restrictive language with a 99.9% accurate compiler (yes, there are bugs; I ran into one on SO just the other day) than a more flexible language which couldn't compile correctly.</p> <p>EDIT: Here's a pseudo-proof of how it why it's feasible.</p> <p>Consider that:</p> <ul> <li>You can make sure that the yield return part itself doesn't throw an exception (precalculate the value, and then you're just setting a field and returning "true")</li> <li>You're allowed try/catch which doesn't use yield return in an iterator block.</li> <li>All local variables in the iterator block are instance variables in the generated type, so you can freely move code to new methods</li> </ul> <p>Now transform:</p> <pre><code>try { Console.WriteLine("a"); yield return 10; Console.WriteLine("b"); } catch (Something e) { Console.WriteLine("Catch block"); } Console.WriteLine("Post"); </code></pre> <p>into (sort of pseudo-code):</p> <pre><code>case just_before_try_state: try { Console.WriteLine("a"); } catch (Something e) { CatchBlock(); goto case post; } __current = 10; return true; case just_after_yield_return: try { Console.WriteLine("b"); } catch (Something e) { CatchBlock(); } goto case post; case post; Console.WriteLine("Post"); void CatchBlock() { Console.WriteLine("Catch block"); } </code></pre> <p>The only duplication is in setting up try/catch blocks - but that's something the compiler can certainly do.</p> <p>I may well have missed something here - if so, please let me know!</p>
<p>I would speculate that because of the way the call stack gets wound/unwound when you yield return from an enumerator it becomes impossible for a try/catch block to actually "catch" the exception. (because the yield return block is not on the stack, even though he originated the iteration block)</p> <p>To get an ideea of what I'm talking about setup an iterator block and a foreach using that iterator. Check what the Call Stack looks like inside the foreach block and then check it inside the iterator try/finally block.</p>
45,071
<p>How does selenium work? Can you explain the internal working of it.</p>
<p>First there's a layer of javascript code that is used to automate the browser and simulate events, run and verify tests. Next, you run a proxy server - which you point your browser to - that injects this javascript code. Then, you can talk to this proxy server through another port using a set of commands which causes the proxy server to inject javascript code to be run on(or remote controlling) the running browser. Using this framework you can write automated test scripts in a style very much like writing macros for the browser.</p>
<p>Basically it works on following principal . It first Searches for element which you specify in your <strong>Locator</strong> by searching it in HTML document shown in driver launched browser . After finding element it gets location of Object.After getting that location ROBOT Class methods like MOUSECLICK MOUSE Move etc to perform actions on these locations.I hope this works :-) </p>
13,816
<p>Microsoft Linq to SQL, Entity Framework (EF), and nHibernate, etc are all proposing ORMS as the next generation of Data Mapping technologies, and are claiming to be lightweight, fast and easy. Like for example this article that just got published in VS magazine:</p> <p><a href="http://visualstudiomagazine.com/features/article.aspx?editorialsid=2583" rel="noreferrer">http://visualstudiomagazine.com/features/article.aspx?editorialsid=2583</a></p> <p>Who all are excited about implementing these technologies in their projects? Where is the innovation in these technologies that makes them so great over their predecessors?</p>
<p>I have written data access layers, persistence components, and even my own ORMs in hundreds of applications over the years (one of my "hobbies"); I have even implemented my own business transaction manager (discussed elsewhere on SO).</p> <p>ORM tools have been around for a long time on other platforms, such as Java, Python, etc. It appears that there is a new fad now that Microsoft-centric teams have discovered them. Overall, I think that is a good thing--a necessary step in the journey to explore and comprehend the concepts of architecture and design that seems to have been introduced along with the arrival of .NET.</p> <p>Bottom line: I would always prefer to do my own data access rather than fight some tool that is trying to "help" me. It is never acceptable to give up my control over my destiny, and data access is a critical part of my application's destiny. Some simple principles make data access very manageable.</p> <p>Use the basic concepts of modularity, abstraction, and encapsulation--so wrap your platform's basic data access API (e.g., ADO.NET) with your own layer that raises the abstraction level closer to your problem space. DO NOT code all your data access DIRECTLY against that API (also discussed elsewhere on SO).</p> <p>Severely apply the DRY (Don't Repeat Yourself) principle = refactor the daylights out of your data access code. Use code generation when appropriate as a means of refactoring, but seek to eliminate the need for code generation whenever you can. Generally, code generation reveals that something is missing from your environment--language deficiency, designed-in tool limitation, etc.</p> <p>Meanwhile, learn to use the available API well, particularly regarding performance and robustness, then incorporate those lessons into your own abstracted data access layer. For example, learn to make proper use of parameters in your SQL rather than embedding literal values into SQL strings.</p> <p>Finally, keep in mind that any application/system that becomes successful will grow to encounter performance problems. Fixing performance problems relies more on designing them out rather than just "tweaking" something in the implementation. That design work will affect the database and the application, which must change in sync. Therefore, seek to be able to make such changes easily (agile) rather than attempt to avoid ever changing the application itself. In part, that eventually means being able to deploy changes without downtime. It is not hard to do, if you don't "design" away from it.</p>
<p>I have been following Fluent-NHibernate very closely as it has some of the most potential I've ever seen in a project.</p>
47,422
<p>This is probably a really stupid newbie-sounding question to you developer type people, but I'm at a loss :( I've been trying to learn how to use Subversion for keeping the history of my code, but I'm finding it pretty confusing. I read the 'book' that comes with Subversion, but I didn't find it all that helpful. I'm using Windows, and I downloaded the TortoiseSVN GUI for it. </p> <p>All I really want to know how to do is to create a new project, put a file in it (any old file), and then update that file, just so I can see how it works. I created a 'repository' (in svn_repository/test), and if anyone could tell me how I'm supposed to go about creating a new file/putting a file in it, and then updating that file I'd be really happy :) Knowing my luck it'll be something as simple as "drag and drop the file into the directory". Apologies for asking such a stupid question! </p> <p>Also if anyone could tell me how to go about making it work with Zend Studio, that would be extra awesome-points. Thanks!</p>
<p>The recommended directory structure for a subversion repo contains three folders: "branches", "tags" and "trunk". So, create these folders somewhere convenient, in a new folder.</p> <p>Right click in the parent folder of these folders, go to TortoiseSVN and select Import. Enter the url to the repository you created here (ie_ <a href="https://JUNK:8443/svn/Test/" rel="nofollow noreferrer">https://JUNK:8443/svn/Test/</a> is one I just made, on my local machine). Hit the ok button and the folders will be imported.</p> <p>Now browse to where you want the repo to live on your local machine (I've gone to C:\workspace\test). Right-click and go to SVN Checkout.</p> <p>Now, you want to check out from the trunk of your repo, so change the repository URL to reflect this (<a href="https://JUNK:8443/svn/Test/trunk/" rel="nofollow noreferrer">https://JUNK:8443/svn/Test/trunk/</a>). Hit the ok button.</p> <p>Create a new file in this directory. Right click on it and go to TortoiseSVN, then Add. Hit ok, and the file is now marked as a new file for the repo. Right click in the parent folder of the file and you should see SVN Update and SVN Commit. SVN Update will refresh the local files with files from the repository. SVN Commit will send local files that have been changed back into the repository.</p> <p>Have fun :)</p>
<p>I found TortoiseSVN to be terribly confusing, especially in conjunction with the SVN Book. But then again, I'm not a very GUI oriented person.</p> <p>Work through the book using the command line SVN client, until you understand the basic concepts. Don't skip any chapters!</p> <p>Then you can evaluate GUIs, if you even need one by then.</p>
15,164
<p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p> <pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer()); </code></pre> <p>Where ContactServer is a predicate function object.<br> On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p> <p>What do you say?</p>
<p>I think I would go for it.</p> <p>The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.</p> <p>You might want to rename <code>ContactServer</code> to indicate that it is a predicate; <code>CanContactServer</code>? (But then people would complain about hidden side effects. Hmm...)</p>
<p>Isn't that what <code>find_if</code> is for?</p> <p>Note though, that it will find <em>all</em> the servers, if you iterate over the iterator - but you aren't going to do that (according to OP).</p>
4,724
<p>Problem (simplified to make things clearer):</p> <ul> 1. there is one statically-linked static.lib that has a function that increments: <pre><code> extern int CallCount = 0; int TheFunction() { void *p = &CallCount; printf("Function called"); return CallCount++; } </code></pre> 2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method: <pre><code> int Managed::CallLibFunc() { return TheFunction(); } </code></pre> 3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper: <pre><code> static void Main(string[] args) { Managed c1 = new Managed(); int val1 = c1.CallLibFunc(); // value is zero AppDomain ad = AppDomain.CreateDomain("NewDomain"); Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed; int val2 = c.CallLibFunc(); // value is one } </code></pre> </ul> <p>Question:</p> <p>Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p> <p>Thank you very much everyone!</p>
<p>My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.</p> <p><a href="http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/" rel="nofollow noreferrer">This link</a> shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.</p> <p><a href="http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/" rel="nofollow noreferrer">This link</a> is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround.</p>
<p>In short, maybe. AppDomains are purely a managed concept. When an AppDomain is instantiated it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)</p> <p>Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.</p> <p>You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride. For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.</p>
9,837
<p>Code below does not run correctly and throws <code>InvalidOperationExcepiton</code>.</p> <pre><code>public void Foo() { DataContext context = new DataContext(); LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ; context.LinqEntities.Attach(item, true); } </code></pre>
<p>By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.</p> <p>This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.</p> <p>Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.</p> <pre><code>LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; context.LinqEntities.Attach(item); item.Name = "John"; item.Surname = "Doe"; context.SubmitChanges(); </code></pre>
<p>When using an ORM you typically select an object before updating it. </p> <p>You can use <code>DataContext.ExecuteCommand(...)</code> to bypass the ORM if you do not want to do a select. </p>
6,126
<p>I have a two years of experience of programming in Visual C# and Visual C++. I would like to know some good online sources to start learning ASP.NET or anything else I should/need to learn before diving into ASP.NET. I found some online videos that are proving to be quite useful. Perhaps I would like to know about some open source projects where I can have a look at the ASP.NET code directly.</p>
<p>Sorry, but I'm going to have to suggest the immediately obvious first:</p> <p><a href="http://www.asp.net" rel="noreferrer">Official Microsoft ASP .Net Site</a></p> <p>There's a link at the top to both "Get Started" and "Learn", and I have found this site incredibly useful over the past year or so.</p>
<p>Just to add, another great resource is <a href="http://www.learnvisualstudio.net" rel="nofollow noreferrer">www.learnvisualstudio.net</a></p> <p>Its not free but it has a plethora of videos covering all aspects of asp.net from 1.1 to 3.5, AJAX, Webservices.</p> <p>Programmer to Programmer style videos with great examples and downloadable source code. </p> <p>Good luck :)</p>
33,668
<p>Grails scaffolding defaults to 10 rows per page. I would like to increase that number without generating the views and changing the 10 in every file. Where do I change the default?</p>
<p>You have to install scaffold templates with:</p> <p>grails install-templates</p> <p>Now, edit in src/templates/scaffolding Controller.groovy and increase the value params.max as you want</p>
<p>Add to the uri:</p> <pre><code>?max=&lt;num_rows_desired&gt; </code></pre> <p>For instance:</p> <pre><code>http://projecthost:8080/Library/Books/list?max=20 </code></pre>
8,234
<p>What does it mean if a task is declared with the automatic keyword in Verilog?</p> <pre><code>task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin // ... end endtask; </code></pre> <p>Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :)</p>
<p>It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task.</p> <p>You see - some of us do Verilog... (ugh)</p>
<p>In computing, a computer program or subroutine is called re-entrant if multiple invocations can safely run concurrently (Wikipedia). In simple words, the keyword automatic makes it safe, when multiple instances of a task run at a same time. :D</p>
5,559
<p>Is there a way to quickly list which sites are on which IP address in IIS 7? </p> <p>If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.</p>
<p>Take a look at <a href="http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe/#HowToUse" rel="noreferrer">APPCMD </a>.</p> <p>For example, to list all sites on the machine, use this command-line:</p> <pre><code> %systemroot%\system32\inetsrv\APPCMD list sites </code></pre>
<p>You can try this script:</p> <pre><code>MachineName = "localhost" IIsObjectPath = "IIS://" &amp; MachineName &amp; "/w3svc" WScript.Echo "Checking : " &amp; IISObjectPath Set IIsObject = GetObject(IIsObjectPath) for each obj in IISObject if (Obj.Class = "IIsWebServer") then BindingPath = IIsObjectPath &amp; "/" &amp; Obj.Name Set IIsObjectIP = GetObject(BindingPath) wScript.Echo BindingPath &amp; " - " &amp; IISObjectIP.ServerComment ValueList = IISObjectIP.Get("ServerBindings") ValueString = "" For ValueIndex = 0 To UBound(ValueList) value = ValueList(ValueIndex) Values = split(value, ":") IP = values(0) if (IP = "") then IP = "(All Unassigned)" end if TCP = values(1) if (TCP = "") then TCP = "80" end if HostHeader = values(2) if (HostHeader &lt;&gt; "") then wScript.Echo " IP = " &amp; IP &amp; " TCP/IP Port = " &amp; TCP &amp; ", HostHeader = " &amp; HostHeader else wScript.Echo " IP = " &amp; IP &amp; " TCP/IP Port = " &amp; TCP end if Next wScript.Echo "" set IISObjectIP = Nothing end if next set IISObject = Nothing </code></pre> <p>(source www.iisfaq.com)</p>
30,148
<p>I'm an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> developer who has used <code>Microsoft SQL Server</code> for all my database needs (both at work and for personal projects). </p> <p>I am considering trying out the <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="noreferrer">LAMP</a> stack for some of my personal projects. </p> <p>What are some of the main differences between <code>MySQL</code> and <code>SQL Server</code>? Is using <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedures</a> a common practice in <code>MySQL</code>? </p> <p>Any advice or resources you'd recommend to help me with the switch? </p> <p>To those who have experience with both, are there any missing features from <code>MySQL</code>?</p>
<p>One thing you have to watch out for is the fairly severe differences in the way SQL&nbsp;Server and MySQL implement the SQL syntax.</p> <p>Here's a nice <a href="http://troels.arvin.dk/db/rdbms/" rel="noreferrer">Comparison of Different SQL Implementations</a>.</p> <p>For example, take a look at the top-n section. In MySQL:</p> <pre><code>SELECT age FROM person ORDER BY age ASC LIMIT 1 OFFSET 2 </code></pre> <p>In SQL&nbsp;Server (T-SQL):</p> <pre><code>SELECT TOP 3 WITH TIES * FROM person ORDER BY age ASC </code></pre>
<p>Spending some time working with MySQL from the MSSQL to MySQL syntax POV I kept finding myself limited in what I could do.</p> <p>There are bizzare limits on updating a table while refrencing the same table during an update.</p> <p>Additionally UPDATE FROM does not work and last time I checked they don't support the Oracle MERGE INTO syntax either. This was a show stopper for me and I stopped thinking I would get anywhere with MySQL after that.</p>
3,182
<p>I want to search for a line in a file, using regex, inside a Perl script.</p> <p>Assuming it is in a system with grep installed, is it better to:</p> <ul> <li>call the external <code>grep</code> through an <code>open()</code> command</li> <li><code>open()</code> the file directly and use a <code>while</code> loop and an <code>if ($line =~ m/regex/)</code>?</li> </ul>
<p>In a modern Perl implementation, the regexp code should be just as fast as in grep, but if you're concerned about performance, why don't you simply try it out? From a code cleanliness and robustness standpoint, calling an external command line tool is definitely not good.</p>
<p>It depends.</p> <ul> <li>working inside Perl saves you the process startup time, and other related resource costs.</li> <li>grep is probably faster than doing the same job in Perl, but not hugely so.</li> </ul> <p>I'd say to do it in Perl unless performance forces you to optimize.</p>
47,683
<p>In the early days of SharePoint 2007 beta, I've come across the ability to customize the template used to emit the RSS feeds from lists. I can't find it again. Anybody know where it is?</p>
<p>OK, I think I have a solution:</p> <ul> <li>Generate the plugin via script/generate plugin</li> <li>change the Rakefile, and add</li> </ul> <p><code> require 'spec/rake/spectask'</p> <pre><code>desc 'Test the PLUGIN_NAME plugin.' Spec::Rake::SpecTask.new(:spec) do |t| t.libs &lt;&lt; 'lib' t.verbose = true end </code></pre> <p></code></p> <ul> <li>Create a spec directory, and begin adding specs in *_spec.rb files, as normal</li> </ul> <p>You can also modify the default task to run spec instead of test, too.</p>
<p>For an example of an existing plugin that uses rspec, check out the <a href="http://github.com/technoweenie/restful-authentication/tree/master" rel="nofollow noreferrer">restful_authentication plugin</a>. Maybe it will help.</p>
10,789
<p>Among the data my application sends to a third-party SOA server are complex XMLs. The server owner does provide the XML schemas (<code>.xsd</code>) and, since the server rejects invalid XMLs with a meaningless message, I need to validate them locally before sending.</p> <p>I could use a stand-alone XML schema validator but they are slow, mainly because of the time required to parse the schema files. So I wrote my own schema validator (in Java, if that matters) in the form of an <em>HTTP Server</em> which caches the already parsed schemas.</p> <p>The problem is: many things can go wrong in the course of the validation process. Other than unexpected exceptions and successful validation:</p> <ul> <li>the server may not find the schema file specified</li> <li>the file specified may not be a valid schema file</li> <li>the XML is invalid against the schema file</li> </ul> <p>Since it's an HTTP Server I'd like to provide the client with meaningful <em>status codes</em>. Should the server answer with a <em>400</em> error (<em>Bad request</em>) for all the above cases? Or they have nothing to do with HTTP and it should answer <em>200</em> with a message in the body? Any other suggestion?</p> <p><em>Update</em>: the main application is written in <em>Ruby</em>, which doesn't have a good xml schema validation library, so a separate validation server is not over-engineering.</p>
<p>It's a perfectly valid thinking to map error situations in the validation process to meaningful HTTP status codes. </p> <p>I suppose you send the XML file to your validation server as a POST content using the URI to determine a specific schema for validation.</p> <p>So here are some suggestions for error mappings:</p> <ul> <li>200: XML content is valid</li> <li>400: XML content was not well-formed, header were inconsistent, request did not match RFC 2616 syntax</li> <li>401: schema was not found in cache and server needs credentials to use for authentication against the 3rd party SOA backend in order to obtain the schema file</li> <li>404: Schema file not found</li> <li>409: the XML content was invalid against the specified schema</li> <li>412: Specified file was not a valid XMl schema</li> <li>500: any unexpected exception in your validation server (NullPointerExceptions et al.)</li> <li>502: the schema was not found in cache and the attempt to request it from the 3rd party SOA server failed.</li> <li>503: validation server is restarting</li> <li>504: see 502 with reason=timeout</li> </ul>
<p>That sounds like a neat idea, but the HTTP status codes don't really provide an "operation failed" case. I would return HTTP 200 with an <code>X-Validation-Result: true/false</code> header, using the body for any text or "reason" as necessary. Save the HTTP 4xx for HTTP-level errors, not application-level errors.</p> <p>It's kind of a shame and a double-standard, though. Many applications use HTTP authentication, and they're able to return HTTP 401 Not Authorized or 403 Forbidden from the application level. It would be convenient and sensible to have some sort of blanket HTTP 4xx Request Rejected that you could use.</p>
47,331
<p>When upgrading MySQL, I first create a backup of the database. Then I will uninstall the current version installed, and delete all the files that were left by the installer. Then I install the latest GA version, and restore the created back-up, using the MySQL Administrator.</p> <p>Is there a better way of doing an upgrade of the MySQL. Because I have to create again all the users that are allowed to connect to the database.</p> <p>The installation of the MySQL is used in a college enrollment system, a client server system I have developed using VB.Net and MySQL. I can only do the update at night because i know no one is connected to the database.</p>
<p>you can dump the <code>mysql.user</code> and <code>mysql.db</code> tables, which contains all the user info, and reimport that as well, to avoid having to recreate all that. i'd also suggest running repairs on the table after you re-import.</p> <p>alternatively, you could create a listing of grants:</p> <pre><code>select concat('show grants for ',quote(user),'@',quote(host),';') from mysql.user </code></pre> <p>this will output a list of sql statements that you can then run to get specific grant statements.</p> <p>ultimately though, you'll want to check out your specific version information regarding upgrades, to make sure you've considered any version specific compatibility issues.</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/upgrading-from-4-1.html" rel="nofollow noreferrer">here</a> is some information for a 4.1 - 5.x upgrade, for example.</p>
<p>Why is the mysql upgrade so braindead? The fact that you need to back up all your data, install MySQL to a different directory, reimport your data -- just to upgrade is ridiculous. There has to be an easier way.</p>
31,462
<p>I am new to programming, and am wondering if there is a correct way to order your control structure logic.</p> <p>It seems more natural to check for the most likely case first, but I have the feeling that some control structures won't work unless they check everything that's false to arrive at something that's true (logical deduction?)</p> <p>It would be hard to adapt to this 'negative' view, I prefer a more positive outlook, presuming everything is true :)</p>
<p>There is an excellent discussion of just this topic in McConnell's <em><a href="http://cc2e.com/" rel="nofollow noreferrer">Code Complete</a></em>. It's a book that I highly recommend. Anyway the relevant discussion is on pages 706-708 of the first edition or pg. 749-750 of second edition (thanks plinth). From that book:</p> <blockquote> <p>Arrange tests so that the one that's fastest and most likely to be true is performed first. It should be easy to drop through the normal case, and if there are inefficiencies, they should be in processing the exceptions.</p> </blockquote>
<p>Either / Or. I generally use the 'negative' approach though.</p> <p>if (!something) {</p> <p>}</p>
28,407
<p>neither</p> <pre><code>&lt;?php system('php file.php'); ?&gt; </code></pre> <p>nor</p> <pre><code>&lt;?php system('/usr/bin/php file.php'); ?&gt; </code></pre> <p>worked. Why?</p> <p>I tried with <code>-q</code>, with <code>!#/usr/bin/php</code> etc.</p>
<p>You are supposed to call it with -f, but it should work without it as well:</p> <pre><code>&lt;?php system('/usr/bin/php -f file.php'); ?&gt; </code></pre> <p>What do you mean by "it doesn't work"? </p> <p>Did you want the contents to be outputted as if they were from your script? Use <a href="http://php.net/include" rel="nofollow noreferrer">include</a> or <a href="http://php.net/require" rel="nofollow noreferrer">require</a>.</p> <p>Did you want the contents in a variable? Use the <a href="http://www.php.net/manual/en/language.operators.execution.php" rel="nofollow noreferrer">backtick operator</a>.</p> <p>You can see what you get back from the command by using the backtick operator instead of system.</p>
<p>You obviously don't understand how <em>system</em> function works. What you really need is probably <a href="http://www.php.net/popen" rel="nofollow noreferrer">popen</a>. Start the process with <em>popen</em> and then read its output with <em>fgets</em> for example.</p> <p>Alternatively, you can use the backtick operator as already suggested by others.</p>
23,949
<p>I have these 3 tables + data:</p> <p><strong>items</strong>: itemId, itemName <br />data: 1, my item one</p> <p><strong>categories</strong>: catId, catName <br />data: 1, my cat one. 2, my cat two</p> <p><strong>map</strong>: mapId, itemId, catId</p> <p>When you include item "my item one" in category "my cat one", you insert [1, 1, 1] into the map. When you add "my item one" to "my cat two", you insert [2, 1, 2] into the map. Now let's say we change our mind and only want the item in "my cat two". This means we need to know what categories the item is no longer in and delete the associations from the map. What's the most efficient sequence of steps to take to do so? (I'm looking for a solution that will scale beyond this trivial example.)</p>
<p>Assuming you've already got the category ID for "my cat two" and the item ID for "my item 1":</p> <pre><code>DELETE FROM MAP WHERE ItemID = @MyItem1Id AND CatID &lt;&gt; @MyCat2Id </code></pre> <p>If you have a set of categories you want to keep the item in, you could either:</p> <ol> <li>Delete everything from the map for that item and then re-add the set</li> <li>Use a query like the above but with "AND CatID NOT IN [ ... ]"</li> </ol>
<p>If you decide that an item should only be in the new category, the following should work:</p> <pre><code>DELETE M FROM Map M WHERE M.itemid = @item_id AND M.catid &lt;&gt; @new_cat_id </code></pre>
33,950
<p>I'm trying to do the following:</p> <ol> <li>User goes to web page, uploads XLS file</li> <li>use ADO .NET to open XLS file using JET engine connection to locally uploaded file on web server</li> </ol> <p>This all works fine locally (my machine as the client and the web server) - and in fact is working on the customer's web server with remote clients but is not working when trying to test internally using a remote client.</p> <p>The error I get is:</p> <pre><code>TIME: [10/1/2008 11:15:28 AM] SEVERITY: EXCEPTION PROGRAM: Microsoft JET Database Engine EXCEPTION: Unspecified error STACK TRACE: at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() </code></pre> <p>The code generating the error is:</p> <pre><code>OleDbConnection l_DbConnection; OleDbDataAdapter l_DbCommand; DataSet l_dataSet = new DataSet(); l_DbConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=\"" + l_importFileName + "\";Extended Properties=Excel 8.0;"); l_DbCommand = new OleDbDataAdapter("select * from [Sheet1$]", l_DbConnection); //try using provider to read file try { l_DbConnection.Open(); } </code></pre> <p>The call to "Open" is raising the exception above.</p> <p>The site is using impersonation and all calls are made as the user logged in on the client. What I've done so far to try and get this working:</p> <p>Followed the steps here <a href="http://support.microsoft.com/kb/251254/" rel="nofollow noreferrer">http://support.microsoft.com/kb/251254/</a> and assigned permissions to the TMP/TEMP environment variable directory to the user I am using to test (also assigned permissions to ASPNET and then to "Everyone" as a blanket "is this permissions related?" test).</p> <p>Ensured that the file is being uploaded and the XLS file itself has inherited the directory permissions that allow the user full access to the file. I also gave this dir permissions to "Everyone" just in case - that also didn't help.</p> <p>I haven't had to change any environment variables and have, therefore, not restarted after making these changes - but I shouldn't have to for Windows folder/file permissions to take effect.</p> <p>At this point I'm at a total loss</p>
<p>Ok, figured it out -</p> <p>turns out that even with IIS using impersonation and the TMP/TEMP environment variables being set to C:\WINDOWS\Temp the ASP.NET process is still running under the ASPNET account and each individual user needed permissions to the Documents and Settings\ASPNET\Local Settings\Temp folder</p> <p>The other way around this would probably be to create a new app pool and have that app pool run as a user with permissions to the right folder rather than ASPNET</p>
<p>Go to the directory \Documents and Settings\"machineName"\ASPNET\Local Settings\Temp and give the read, write rights to the user "EveryOne" Then it will work fine. Moreover you have to set "" in web.config file</p>
19,145