instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have some string s that is locale specific (eg, 0.01 or 0,01). I want to convert this string to a NSDecimalNumber. From the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html" rel="noreferrer">examples I've seen thus far on the interwebs</a>, this is accomplished by using an NSNumberFormatter a la:</p> <pre><code>NSString *s = @"0.07"; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [formatter setGeneratesDecimalNumbers:YES]; NSDecimalNumber *decimalNumber = [formatter numberFromString:s]; NSLog([decimalNumber stringValue]); // prints 0.07000000000000001 </code></pre> <p>I'm using 10.4 mode (in addition to being recommended per the documentation, it is also the only mode available on the iPhone) but indicating to the formatter that I want to generate decimal numbers. Note that I've simplified my example (I'm actually dealing with currency strings). However, I'm obviously doing something wrong for it to return a value that illustrates the imprecision of floating point numbers.</p> <p>What is the correct method to convert a locale specific number string to an NSDecimalNumber?</p> <p>Edit: Note that my example is for simplicity. The question I'm asking also should relate to when you need to take a locale specific currency string and convert it to an NSDecimalNumber. Additionally, this can be expanded to a locale specific percentage string and convert it to a NSDecimalNumber.</p>
<p>Based on Boaz Stuller's answer, I logged a bug to Apple for this issue. Until that is resolved, here are the workarounds I've decided upon as being the best approach to take. These workarounds simply rely upon rounding the decimal number to the appropriate precision, which is a simple approach that can supplement your existing code (rather than switching from formatters to scanners).</p> <p><strong>General Numbers</strong></p> <p>Essentially, I'm just rounding the number based on rules that make sense for my situation. So, YMMV depending on the precision you support.</p> <pre><code>NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [formatter setGeneratesDecimalNumbers:TRUE]; NSString *s = @"0.07"; // Create your desired rounding behavior that is appropriate for your situation NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; NSDecimalNumber *decimalNumber = [formatter numberFromString:s]; NSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior]; NSLog([decimalNumber stringValue]); // prints 0.07000000000000001 NSLog([roundedDecimalNumber stringValue]); // prints 0.07 </code></pre> <p><strong>Currencies</strong></p> <p>Handling currencies (which is the actual problem I'm trying to solve) is just a slight variation on handling general numbers. The key is that the scale of the rounding behavior is determined by the maximum fractional digits used by the locale's currency.</p> <pre><code>NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init]; [currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [currencyFormatter setGeneratesDecimalNumbers:TRUE]; [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; // Here is the key: use the maximum fractional digits of the currency as the scale int currencyScale = [currencyFormatter maximumFractionDigits]; NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:currencyScale raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; // image s is some locale specific currency string (eg, $0.07 or €0.07) NSDecimalNumber *decimalNumber = (NSDecimalNumber*)[currencyFormatter numberFromString:s]; NSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior]; NSLog([decimalNumber stringValue]); // prints 0.07000000000000001 NSLog([roundedDecimalNumber stringValue]); // prints 0.07 </code></pre>
<p>See also <a href="https://stackoverflow.com/questions/149033/best-way-to-store-currency-values-in-c">Best way to store currency values in C++</a></p> <p>The best way to handle currency is to use an integer value for the smallest unit of the currency, i.e. cents for dollars/euros, etc. You'll avoid any floating point related precision errors in your code.</p> <p>With that in mind, the best way to parse strings containing a currency value is to do it manually (with a configurable decimal point character). Split the string at the decimal point, and parse both the first and second part as integer values. Then use construct your combined value from those.</p>
40,985
<p>OK here's some background of the problem:</p> <p>Symptoms:</p> <ul> <li><p>All retracts on the extruder produce a screeching noise. The extruder extrudes normally all other times.</p> </li> <li><p>Any fast move on the Z-axis also produces a screeching noise and the Z-axis will move normally at all other times.</p> </li> <li><p>This appears to happen regardless of any printing state whether the heaters are on or not it will still occur it even happens during the ABL process.</p> </li> </ul> <p>Specifications of the printer:</p> <ul> <li>Mainboard: MKS Gen L V2</li> <li>Drivers: TMC2209 UART</li> <li>Stepper motors: Stepperonline 17HS15-1504S 1.8 deg 1.5A</li> <li>Pulleys: GT2 16T</li> <li>Leadscrew: 2 mm pitch T8</li> <li>Hotend: E3D V6</li> </ul> <p>OK so basically I performed an upgrade of my stepper drivers as well as the leadscrew and pulleys on my 3D printer which was originally a Tevo tornado and at the start of every print I would experience a loud screeching noise coming from the Z-axis and I originally identified it to be a single line in my G-code that would only trigger the screech if it was preceded by another line and by commenting out the first line I was able to start printing</p> <p>Lines in question:</p> <pre><code>G1 X3 Y1 Z15 F9000 ; Move safe Z height to shear strings G0 X1 Y1 Z0.2 F9000 ; Move in 1mm from edge and up [z] 0.2mm </code></pre> <p>However, while I was able to start printing, I soon found out that the extruder was doing the same thing with every retract it would create a loud screech and the filament wouldn't be retracted this caused heavy stringing as well as poor layer adhesion resulting in prints failing. I figured the problem was with the version of Marlin I was using so I attempted to use the latest bug fix. However, I was still experiencing the same problems. I attempted to see if the stepper current was the problem and after identifying that the stepper current was not the cause of the problem, I figured I needed to replace the stepper motors and after replacing the stepper motors the problem still remained. I figured the problem must be with Marlin so I attempted to use Klipper. However, I am still experiencing the same and now I can't even complete a mesh bed leveling as the movements that Klipper uses are triggering the loud screeching and causing the steppers to freeze up.</p> <p>I am unsure as to what could be causing this as I think I've checked everything that could be causing it so I'm not quite sure how to proceed I've also made a video that should show the problem in action. So I guess I'm wondering what's my next troubleshooting step?</p> <p><div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/v_vXF8f9GdQ?start=0"></iframe> </div></div></p> <p>EDIT: Updates</p> <p>I have tried changing the drivers back to TMC2208s there have been no changes on both Kilpper and Marlin.</p> <p>I tried switching to an MKS Gen L V2.1 in case it was a mainboard problem. sill experiencing problems</p> <p>Marlin Config</p> <p>Configuration.H <a href="https://paste-bin.xyz/41662" rel="nofollow noreferrer">https://paste-bin.xyz/41662</a></p> <p>Configuration_ADV.H <a href="https://paste-bin.xyz/41663" rel="nofollow noreferrer">https://paste-bin.xyz/41663</a></p> <p>Klipper Config <a href="https://paste-bin.xyz/41677" rel="nofollow noreferrer">https://paste-bin.xyz/41677</a></p> <p>Edit:</p> <p>The only other thing I think I can try is running the TMC2209s in standalone mode</p>
<p>If you have an empty spool of the same brand, you could weigh the empty spool and the one you're trying to &quot;measure&quot; to get an approximate weight of the remaining filament. Divide by the (presumably available from manufacturer) weight per meter to get a rough length in meters, if that's more useful to you than weight.</p>
<p>Besides using the window on a spool that estimates the amount of filament left, I've used large calipers to measure the diameter of an empty spool and the diameter of the filament left on the spool.</p>
2,110
<p>I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google &amp; two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for <strong>de</strong>-optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?</p>
<p>You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school.</p> <p>Common FORTRAN-isms I deal with, that hurt readability are:</p> <ul> <li>Common blocks</li> <li>Implicit variables</li> <li>Two or three DO loops with shared CONTINUE statements</li> <li>GOTO's in place of DO loops</li> <li>Arithmetic IF statements</li> <li>Computed GOTO's</li> <li>Equivalence REAL/INTEGER/other in some common block</li> </ul> <p>Strategies for solving these involve:</p> <ol> <li>Get <a href="http://www.polyhedron.com/spag0html" rel="noreferrer">Spag / plusFORT</a>, worth the money, it solves a lot of them automatically and Bug Free(tm)</li> <li>Move to Fortran 90 if at all possible, if not move to free-format Fortran 77</li> <li>Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it)</li> <li>Moving all COMMON blocks to MODULEs, low hanging fruit, worth it</li> <li>Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks</li> <li>Convert computed GOTOs to SELECT CASE blocks</li> <li><p>Convert all DO loops to the newer F90 syntax</p> <pre><code>myloop: do ii = 1, nloops ! do something enddo myloop </code></pre></li> <li><p>Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL</p></li> </ol> <p>If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.</p>
<p>Here's another one that has bit me from time to time. When you are working on FORTRAN code make sure you skip all six initial columns. Every once and a while, I'll only get the code indented five spaces and nothing works. At first glance everything seems okay and then I finally realize that all the lines are starting in column 6 instead of column 7.</p> <p>For anyone not familiar with FORTRAN, the first 5 columns are for line numbers (=labels), the 6th column is for a continuation character in case you have a line longer than 80 characters (just put something here and the compiler knows that this line is actually part of the one before it) and code always starts in column 7.</p>
5,160
<p>Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)?</p> <p>I would expect to be able to instantiate a an object of some sort, give it a template along the lines of</p> <pre><code>Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} </code></pre> <p>provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order').</p> <p>I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides </p> <p>For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as</p> <pre><code>Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} </code></pre> <p>and I can pass it an Object array, in my calling Java program</p> <pre><code>new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; </code></pre> <p>However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.</p>
<p>You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper.</p> <p>This blog post describes how to do it: <a href="http://illegalargumentexception.blogspot.com/2008/04/java-using-el-outside-j2ee.html" rel="noreferrer">Java: using EL outside J2EE</a>.</p>
<p>Freemarker would do exactly what you need. This is a template engine with a syntax very similar to JSP :</p> <p><a href="http://freemarker.org/" rel="nofollow noreferrer">http://freemarker.org/</a></p>
11,710
<p>The ASP page gets data uses that to draw a graph, I then need to save the image created to JPEG to be displayed on the browser and also used in PDF and other format. What is the best way to compress the image? I am currently porting a JPEG compression library to ASP but I think it will be too slow on this ARM device running Windows CE 6.0.</p> <p>So, the ASP page, running in Windows CE webservers, gets data, renders it into a bitmap image than then needs to be delivered to the browser accessing that ASP page. The same image is also used in PDF and one other proprietary format that can contain JPEG streams.</p> <p>Edit: What I am looking for is to way to create an array representing a bitmap and then compressing it to JPEG with ASP in Windows CE's IIS which has quite limited ASP implementation.</p>
<p>Take a look at the Imaging APIs (start your traversal at the <a href="http://msdn.microsoft.com/en-us/library/aa452202.aspx" rel="nofollow noreferrer">IImagingFactory interface</a>). If your device has a JPG compression codec installed (remember that CE is modular, so it may or may not be present) you can use it to create a stream (or file) from the image. From there you can do with it what you wish.</p>
<p>I'm confused... </p> <p>The images from ASP would be compressed on the server side--not client side. </p> <p>I'm sure your web server is not running on Windows CE, so I don't think your concern is warranted.</p> <p><strong>EDIT:</strong> Seems as though you can run a web server on Windows CE: <a href="http://www.microsoft.com/windows/embedded/products/windowsce/default.mspx" rel="nofollow noreferrer">http://www.microsoft.com/windows/embedded/products/windowsce/default.mspx</a>. I'll keep my thoughts to myself from now on. :-x</p>
6,141
<p>We recently bought a new rack and set of servers for it, we want to be able to redeploy these boxes as build servers, QA regression test servers, lab re-correlation servers, simulation servers, etc.</p> <p>We have played a bit with VMWare, VirtualPC, VirtualBox etc, creating a virtual build server, but we came across a lot of issues when we tried to copy it for others to use, having to reconfigure every new copy of the VM.</p> <p>We are using Windows XP x86/x64 and Windows Vista x86/x64, so I had to rename the machine, join the domain etc for every new copy.</p> <p>Ideally we just want to be able to add a new box, deploy a thin boot strap OS (Linux is fine here) to get the VM up an running, then use it.</p> <p>One other thing we have limited to no budget, so free is best.</p> <p>I would like to understand others experiences in doing the same thing.</p> <p>FYI, I am not in systems IT, this we are group of software engineers trying to set this up.</p> <p>Any links to good tutorials would be great.</p>
<p>The problem you're running into is the machine SID must be unique for each machine in a domain. Of course by copying an image you now break that unique constraint.</p> <p>I'd suggest that you read the documentation for <a href="http://technet.microsoft.com/en-us/library/bb457073.aspx" rel="nofollow noreferrer">Sysprep</a> in the reskit and <a href="http://technet.microsoft.com/en-us/library/cc721929.aspx" rel="nofollow noreferrer">Vista System Image Manager</a> - your friends for XP/Win2k3 and Vista/Win2k8 respectively.</p> <p>These tools enable to "reseal" your configured instance of the OS such that the next time it boots - it can prompt for information such as network configuration, machine names, admin user ID's, run scripts etc.</p> <p>Also be aware that the licencing restrictions for Windows desktop clients are generally per image - not per server.</p> <p>Using these tools with HyperV we created complete preconfigured instances of Win2k3 &amp; Win2k8 that boot to finish installing Sharepoint - going further we used the diffing disks to overlay Visual Studio so our devs could use the production images for their work. It has radically changed our development process.</p> <p>At this point our entire public website is run on HyperV with of 5 boxes running 15 images for a mix of soft and hard redundancy - they take several hundred million page views per week.</p>
<p>Another option for dealing with the SID probelm is <a href="http://technet.microsoft.com/en-us/sysinternals/bb897418.aspx" rel="nofollow noreferrer" title="NewSID">NewSID</a>. This is a simpler tool than sysprep, in that all it does is rename the machine and reassign the SID; if you don't need all the other features of sysprep this is a much easier tool to use.</p>
13,298
<p>This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this?</p>
<p>What you are looking for is a pseudo-element that doesn't exist. There is <code>:first-letter</code> and <code>:first-line</code>, but no <code>:first-word</code>.</p> <p>You can of course do this with JavaScript. Here's some code I found that does this: <a href="http://www.dynamicsitesolutions.com/javascript/first-word-selector/" rel="noreferrer">http://www.dynamicsitesolutions.com/javascript/first-word-selector/</a></p>
<p>Insert Span Tag in your paragraph text. For Example- <code>&lt;p&gt;&lt;span&gt;Hello&lt;/span&gt;My Name Is Dot&lt;/p</code> and then style the first letter.</p>
7,943
<p>How are assertions done in c++? Example code is appreciated.</p>
<p>Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version.</p> <p>Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:</p> <pre><code>#include &lt;assert.h&gt; void function(int* pointer_arg) { assert(pointer_arg != NULL); ... } </code></pre> <p>An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:</p> <pre><code>assert(a++ == 5); </code></pre> <p>Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:</p> <pre><code>assert((a == 5) &amp;&amp; "a has the wrong value!!"); </code></pre>
<p>Here is a <a href="http://en.wikipedia.org/wiki/Assert" rel="nofollow noreferrer">definition</a> of what an assertion is and <a href="http://www.cplusplus.com/reference/clibrary/cassert/assert.html" rel="nofollow noreferrer">here</a> is some sample code. In a nutshell an assertion is a way for a developer to test his (or her) assumptions about the state of the code at any given point. For example, if you were doing the following code:</p> <pre><code>mypointer-&gt;myfunct(); </code></pre> <p>You probably want to assert that mypointer is not NULL because that's your assumption--that mypointer will never be NULL before the call. </p>
31,563
<p>Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?</p> <p>The methods that I have identified thus far are:</p> <ul> <li><code>save()</code></li> <li><code>update()</code></li> <li><code>saveOrUpdate()</code></li> <li><code>saveOrUpdateCopy()</code></li> <li><code>merge()</code></li> <li><code>persist()</code></li> </ul>
<p>Here's my understanding of the methods. Mainly these are based on the <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html" rel="noreferrer">API</a> though as I don't use all of these in practice.</p> <p><strong>saveOrUpdate</strong> Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called.</p> <p><strong>save</strong> Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.</p> <p><strong>update</strong> Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown.</p> <p><strong>saveOrUpdateCopy</strong> This is deprecated and should no longer be used. Instead there is...</p> <p><strong>merge</strong> Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html" rel="noreferrer">take a look here</a>. With save &amp; update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving.</p> <p><strong>persist</strong> As mentioned above, this is used on transient objects. It does not return the generated ID.</p>
<p>None of the answers above are complete. Although Leo Theobald answer looks nearest answer.</p> <p>The basic point is how hibernate is dealing with states of entities and how it handles them when there is a state change. Everything must be seen with respect to flushes and commits as well, which everyone seems to have ignored completely.</p> <p>NEVER USE THE SAVE METHOD of HIBERNATE. FORGET THAT IT EVEN EXISTS IN HIBERNATE!</p> <p><strong>Persist</strong></p> <p>As everyone explained, Persist basically transitions an entity from "Transient" state to "Managed" State. At this point, a slush or a commit can create an insert statement. But the entity will still remains in "Managed" state. That doesn't change with flush.</p> <p>At this point, if you "Persist" again there will be no change. And there wont be any more saves if we try to persist a persisted entity.</p> <p>The fun begins when we try to evict the entity.</p> <p>An evict is a special function of Hibernate which will transition the entity from "Managed" to "Detached". We cannot call a persist on a detached entity. If we do that, then Hibernate raises an exception and entire transaction gets rolled back on commit.</p> <p><strong>Merge vs Update</strong></p> <p>These are 2 interesting functions doing different stuff when dealt in different ways. Both of them are trying to transition the entity from "Detached" state to "Managed" state. But doing it differently.</p> <p>Understand a fact that Detached means kind of an "offline" state. and managed means "Online" state.</p> <p>Observe the code below:</p> <pre><code>Session ses1 = sessionFactory.openSession(); Transaction tx1 = ses1.beginTransaction(); HibEntity entity = getHibEntity(); ses1.persist(entity); ses1.evict(entity); ses1.merge(entity); ses1.delete(entity); tx1.commit(); </code></pre> <p>When you do this? What do you think will happen? If you said this will raise exception, then you are correct. This will raise exception because, merge has worked on entity object, which is detached state. But it doesn't alter the state of object.</p> <p>Behind the scene, merge will raise a select query and basically returns a copy of entity which is in attached state. Observe the code below:</p> <pre><code>Session ses1 = sessionFactory.openSession(); Transaction tx1 = ses1.beginTransaction(); HibEntity entity = getHibEntity(); ses1.persist(entity); ses1.evict(entity); HibEntity copied = (HibEntity)ses1.merge(entity); ses1.delete(copied); tx1.commit(); </code></pre> <p>The above sample works because merge has brought a new entity into the context which is in persisted state. </p> <p>When applied with Update the same works fine because update doesn't actually bring a copy of entity like merge.</p> <pre><code>Session ses1 = sessionFactory.openSession(); Transaction tx1 = ses1.beginTransaction(); HibEntity entity = getHibEntity(); ses1.persist(entity); ses1.evict(entity); ses1.update(entity); ses1.delete(entity); tx1.commit(); </code></pre> <p>At the same time in debug trace we can see that Update hasn't raised SQL query of select like merge.</p> <p><strong>delete</strong></p> <p>In the above example I used delete without talking about delete. Delete will basically transition the entity from managed state to "removed" state. And when flushed or commited will issue a delete command to store.</p> <p>However it is possible to bring the entity back to "managed" state from "removed" state using the persist method.</p> <p>Hope the above explanation clarified any doubts.</p>
19,488
<p>I have a little c# console program that outputs some text using Console.WriteLine. I then pipe this output into a textfile like:</p> <p><code>c:myprogram &gt; textfile.txt</code></p> <p>However, the file is always an ansi text file, even when I start cmd with the /u switch. cmd /? says about the /u switch:</p> <blockquote> <p>/U Causes the output of internal commands to a pipe or file to be Unicode</p> </blockquote> <p>And it indeed makes a difference, when I do an </p> <p><code>c:echo "foo" &gt; text.txt</code></p> <p>the text.txt is unicode (without BOM)</p> <p>I wonder why piping the output of my console program into a new file does not create an unicode file likewise and how i could change that? </p> <p>I just use Windows Power Shell (which produces a unicode file with correct BOM), but I'd still like to know how to do it with cmd. </p> <p>Thanks!</p>
<p>The /U switch, as the documentation says, affects whether <em>internal</em> commands generate Unicode output. Your program is not one of cmd.exe's internal commands, so the /U option does not affect it.</p> <p>To create a Unicode text file, you need to make sure your program is generating Unicode text.</p> <p>Even that may not be enough, though. I came across <a href="http://blogs.msdn.com/junfeng/archive/2004/02/25/79621.aspx" rel="nofollow noreferrer">this blog from Junfeng Zhang</a> describing how to write Unicode text in a console program. It checks the file type of the standard output handle. For character files (a console or LPT port), it calls WriteFileW. For all other types of handles (including disk files and pipes), it converts the output string to the console's current code page. I'm afraid I don't know how that translates into .Net terms, though.</p>
<p>I had a look how mscorlib implements Console.WriteLine, and it seems to decide on which text output encoding to use based on a call to <a href="http://msdn.microsoft.com/en-us/library/ms683169(VS.85).aspx" rel="nofollow noreferrer">GetConsoleOutPutCP</a>. So I'm guessing (but have not yet confimed) that the codepage returned is a differnt one for a PS console than for a cmd console so that my program indeed only outputs ansi when running from cmd. </p>
36,242
<p>I made a torus that was 1 on the x and y axes, and 3 on the z axis in Blender. It is supposed to be a bead for a beaded necklace. It was exported to Cura as an .stl, then printed on a Lulzbot Mini. It worked fine in plastic, but when we tried it with bronze filament the nozzle clogged and it didn't start printing.<br> Is there something I need to add to the model that will provide instructions for the printer? The person who operates the printer says that most, but not all, of the models he prints in bronze have a border around them when they print, and this one didn't. I don't know if that makes a difference.</p>
<p>We print a lot of stuff in a variety of materials, and I think it is likely what you are experiencing is a problem caused by some combination of the following: Object size overall, object detail size, wall thickness, or span width/thickness.</p> <p>Blender gives pretty clean stls, but the last-mile needed to get output is primarily a materials engineering problem.... (and saying thias, I am assuming you got a valid stl that the printer was able to read and rip...)</p> <p>A first thought: Try loading your stl into one of the services that price online. Shapeways does, and Cubify does or did... and you can download the driver software for the Form2 even if you don't own the printer.</p> <p>Bring your stl into these apps and look for error messages. The Shapeways ordering app does a nice job of showing issues, particularly ones like wall thickness and manifold faces/vertices (another possibility I did not mention above) very quickly.</p> <p>I'd offer to look at your stl if it is something you can share... and/or you can ask your output guy for a sample stl he has printed with some success before. Bring that stl file into Blender beside your model and compare.</p> <p>I do not recognize a "border" around stls, but all of the printers have preferences for the support sprues that support the model as it is built.... possible that he means these?</p> <p>In any case, shout if I can help. We have used a lot of materials, but some of them take tweaking -- most often with detail size (how small of a detail you can recreate on the rpinted surface) and step size (how small the steps are inbetween printed layers in additive rinting systems.</p> <p>Or... just chuck it onto a CNC with a big ole' block of bronze and machine it down! That's pretty old school, but it works, too... just by removing material rather than adding. </p> <p>Here's a torus at Shapeways I uploaded....</p> <p><a href="https://i.stack.imgur.com/7gMY6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7gMY6.jpg" alt="enter image description here"></a></p>
<p>We print a lot of stuff in a variety of materials, and I think it is likely what you are experiencing is a problem caused by some combination of the following: Object size overall, object detail size, wall thickness, or span width/thickness.</p> <p>Blender gives pretty clean stls, but the last-mile needed to get output is primarily a materials engineering problem.... (and saying thias, I am assuming you got a valid stl that the printer was able to read and rip...)</p> <p>A first thought: Try loading your stl into one of the services that price online. Shapeways does, and Cubify does or did... and you can download the driver software for the Form2 even if you don't own the printer.</p> <p>Bring your stl into these apps and look for error messages. The Shapeways ordering app does a nice job of showing issues, particularly ones like wall thickness and manifold faces/vertices (another possibility I did not mention above) very quickly.</p> <p>I'd offer to look at your stl if it is something you can share... and/or you can ask your output guy for a sample stl he has printed with some success before. Bring that stl file into Blender beside your model and compare.</p> <p>I do not recognize a "border" around stls, but all of the printers have preferences for the support sprues that support the model as it is built.... possible that he means these?</p> <p>In any case, shout if I can help. We have used a lot of materials, but some of them take tweaking -- most often with detail size (how small of a detail you can recreate on the rpinted surface) and step size (how small the steps are inbetween printed layers in additive rinting systems.</p> <p>Or... just chuck it onto a CNC with a big ole' block of bronze and machine it down! That's pretty old school, but it works, too... just by removing material rather than adding. </p> <p>Here's a torus at Shapeways I uploaded....</p> <p><a href="https://i.stack.imgur.com/7gMY6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7gMY6.jpg" alt="enter image description here"></a></p>
260
<p>Curious to get people's thoughts. I conduct frequent interviews, and have had enough in my career to reflect on them, and I've noticed a broad array of questions. I made this c++ specific, but it's worth noting that I have had people ask me algorithmic complexity questions over the phone, and I don't even mean what is the complexity of a hash lookup vs. a binary tree, I mean more like analytical problems, such as "imagine there are 4 bumble bees, each buzzing bla bla bla."</p> <p>Now personally I prefer to keep phone screens a little more concrete, and leave the abstract questions for the white board. So when conducting c++ phone interviews, what kind of topics do you cover, especially for Sr. developers?</p> <p>I know there is another thread similar to this, but frankly it seems to completely have missed the point that this is about phone screens, not interviews that are face to face. Plus this is more c++ specific.</p>
<p>I'd ask about resource/memory management, because it's an important subject in C++, and it doesn't require concrete code. Just sketch a simple hypothetical scenario, and ask how they'd ensure some vital resource gets freed even in the face of errors/exceptions. Say they're developing a network app, how do they ensure that we close our sockets properly? Of course the proper answer would be to wrap it in a RAII object, but don't ask them that directly (it's easy to google "RAII", while the above question "how would you ensure resources get released properly" actually shows you whether or not they know the appropriate techniques. If they answer "wrap everything in try/catch", they might have a problem. And this ties in nicely with questions about the differences between heap and stack.</p> <p>You might be able to come up with some simple question about exception safety too, which doesn't require any real code. In general, I'd say a discussion of all the various C++ idioms might be a good idea, because many of them don't require much actual code, but are still vital language-specific concepts.</p> <p>See if they know about smart pointers (again preferably by giving them a situation where smart pointers are called for, and see how they would solve the problem), and maybe templates/metaprogrammin (in the latter case, probably just find out if they're aware that it's possible ,rather than requiring them to code actual metaprograms on the phone)</p> <p>You might also want to ask about some common areas of undefined behavior (what are the values of a and b after executing <code>a = b++ + b++?</code>?), or allocate an array of 10 elements, and add 10 or 11 to the array pointer, and ask what the result is in each case (+=10 is legal, gives you a past-the-end pointer, +=11 is undefined). Or give them a scenario where they need to copy a lot of objects, and ask how they'd do that (plain for-loop copying each element at a time, memcpy or std::copy are obvious answers. Note the caveats with memcpy, that it's not safe for non-POD objects)</p> <p>Or ask about their coding style in general. How do they feel about iterators? Do they prefer plain old for-loops? Do they know how to use std::for_each or std::transform?</p> <p><em>Edit:</em> Seems the <code>a = b++ + b++</code> (the answer is undefined behavior, btw) suggestion in particular generated a lot of comments. Perhaps people read too much into it. As the OP said he preferred to ask <em>concrete</em> (not abstract, and easy to explain/answer/discuss over the phone) questions, that'd reveal a bit about the interviewee's C++ skills, and this is a simple (and yes, perhaps nitpicky) example of that. The reasoning behind it is that 1) it has an intuitive meaning, which is wrong, and 2) you have to have a certain level of experience with C++ before you realize this. And of course 3), it's short and easy to ask over the phone. It doesn't require anyone to write code down. No, it won't reveal whether the candidate is a "great programmer", but as I understood the question, that wasn't the goal either. If someone gets it wrong, it doesn't mean much at all, but if they get it right, you can be fairly sure that they know a bit of C++. But if you read my answer again, you'll see that it was just a quick example of a category of questions I thought should be represented. C++ is full of undefined behavior, even in code that looks completely harmless and intuitive. Asking the candidate to recognize <em>some</em> instance of this may be useful, whether it's the "modify the same variable twice in the same expression" example above, or something different.</p>
<ul> <li>Design Patterns</li> <li>Basics of C/C++</li> <li>Virtual Functions</li> <li>Poly morphism</li> <li>Concepts from Scott Mayer's series</li> <li>About templates. (Not in particular order)</li> </ul> <p>Last but not the least. I will give some sample problem I tell them to design the classes. Just the interfaces.</p>
47,758
<p>Are there any "Alert" (or Notification) frameworks in Java out there.</p> <p>In my web application I would like our users to be able to configure which (of the available alerts) they would like to receive and in which (e.g via email) form.</p> <p>As a simple example, a user chooses to be alerted only via email when his/her order has been shipped.</p>
<p>Nothing comes by default in Java/J2EE. However, it does NOT take much to implement. Your order processor and other processors can have listeners /observers on the processORder method. These can process the email/other notifications.</p> <p>You can even have a jms message coming out of the OrderProcessor with some info about the particular notification and you send an email/otherAlert to the user after consuming the JMS message.</p>
<p>We can use JMS for sending notifications to users. JMS producers puts the alerts in queue and producers will process the message and send to notifications to user via. email / sms and/or store in database to show the messages in user dashboards.</p>
37,221
<p>I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that seems related to the issue I am having:</p> <pre> <code> HttpApplication app = (HttpApplication)sender; // sender from context.BeginRequest event HttpRequest crntReq = app.Request; // set a reference to request object for easier access HttpWebRequest proxyReq = (HttpWebRequest)HttpWebRequest.Create(crntReq.Url.AbsoluteUri); // parse headers from current httpcontext.request.headers and add each name->value to the // new request object foreach (string header in crntReq.Headers) { proxyReq.Headers.Add(header, crntReq.Headers[header]); // throws exception :( } </code> </pre> <p><br /></p> <p>When my code hits the foreach loop, it throws an exception for the Headers.Add function. I'm assuming the collection has access restrictions, for security purposes. It appears that some of the header values are accessible with properties for the HttpWebRequest object itself. However in this case I'd rather get rid of the abstraction and set the properties manually. The exception that I'm receiving is:<br /><i>{"This header must be modified using the appropriate property.\r\nParameter name: name"}</i></p> <p><hr> Thanks in advance for your help,</p> <p>CJAM</p>
<p>Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent</p> <p>You will need to update these properties directly and avoid setting them via the Headers property.</p>
<p>So I am understanding your response as "It's not possible to set the collection explicitly." I was hoping there was a way to add names and values to the NameValueDictionary, but I guess I'll need to just determine which fields I need to set and use the properties to access specific name/value objects. I guess I could use inheritance and roll my own version of the HttpWebRequest object, but I'm sure the folks at Microsoft had a reason behind encapsulating the collection, so I'll probably just leave things the way they are.</p> <p>Thanks for your help on this.</p>
21,291
<p>There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class.</p> <p>Here is the error that you get:</p> <blockquote> <p>Cannot copy [filename]: Insufficient system resources exist to complete the requested service.</p> </blockquote> <p>The is a <a href="http://support.microsoft.com/default.aspx/kb/259837" rel="noreferrer">knowledge base article</a> on the subject, but it pertains to NT4 and 2000.</p> <p>There is also a suggestion to <a href="http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx" rel="noreferrer">use ESEUTIL</a> from an Exchange installation, but I haven't had any luck getting that to work.</p> <p>Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested.</p> <p><strong>[Edit]</strong> I provided working C# code to accompany the accepted answer.</p>
<p>The best option is to just open the original file for reading, the destination file for writing and then loop copying it block by block. In pseudocode :</p> <pre><code>f1 = open(filename1); f2 = open(filename2, "w"); while( !f1.eof() ) { buffer = f1.read(buffersize); err = f2.write(buffer, buffersize); if err != NO_ERROR_CODE break; } f1.close(); f2.close(); </code></pre> <p><strong>[Edit by Asker]</strong> Ok, this is how it looks in C# (it's slow but it seems to work Ok, and it gives progress):</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LoopCopy { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine( "Usage: LoopCopy.exe SourceFile DestFile"); return; } string srcName = args[0]; string destName = args[1]; FileInfo sourceFile = new FileInfo(srcName); if (!sourceFile.Exists) { Console.WriteLine("Source file {0} does not exist", srcName); return; } long fileLen = sourceFile.Length; FileInfo destFile = new FileInfo(destName); if (destFile.Exists) { Console.WriteLine("Destination file {0} already exists", destName); return; } int buflen = 1024; byte[] buf = new byte[buflen]; long totalBytesRead = 0; double pctDone = 0; string msg = ""; int numReads = 0; Console.Write("Progress: "); using (FileStream sourceStream = new FileStream(srcName, FileMode.Open)) { using (FileStream destStream = new FileStream(destName, FileMode.CreateNew)) { while (true) { numReads++; int bytesRead = sourceStream.Read(buf, 0, buflen); if (bytesRead == 0) break; destStream.Write(buf, 0, bytesRead); totalBytesRead += bytesRead; if (numReads % 10 == 0) { for (int i = 0; i &lt; msg.Length; i++) { Console.Write("\b \b"); } pctDone = (double) ((double)totalBytesRead / (double)fileLen); msg = string.Format("{0}%", (int)(pctDone * 100)); Console.Write(msg); } if (bytesRead &lt; buflen) break; } } } for (int i = 0; i &lt; msg.Length; i++) { Console.Write("\b \b"); } Console.WriteLine("100%"); Console.WriteLine("Done"); } } } </code></pre>
<p>If you want to write code, one way you can optimize is sending the file in chunks (like using <a href="http://www.codeproject.com/KB/XML/MTOMWebServices.aspx" rel="nofollow noreferrer">MTOM</a>). I used this approach for sending down huge files from a DataCenter down to our office for printing..</p> <p>Also, check the TeraCopy utility mentioned <a href="http://lifehacker.com/software/lifehacker-top-10/top-10-free-windows-file-wranglers-330037.php" rel="nofollow noreferrer">here</a>..</p>
11,766
<p>I'm trying to remember how the math is worked out to compute the remainder of an XOR algorithm in Cyclical Redundancy Checks to verify the remainder bits of a network message.</p> <p>I shouldn't have tossed that text book.</p> <p>This is easily done in code, but how is it worked out by hand?</p> <p>I know it looks something like a standard division algorithm, but I can't remember where to go from there to get the remainder. </p> <pre><code> ___________ 1010 | 101101000 </code></pre> <p><strong>Note:</strong> I did google it, but wasn't able to find a place where they mapped the steps in figuring the remainder.</p>
<pre><code>1010 | 101101000 1010 0001 this result is 1011 XOR 1010 = 0001 1010 1010 0000 thus no remainder. </code></pre> <p>Thus 101101000 is perfect and no error has occurred in transmission/reception</p>
<p>Let's assume that we want to divide 101110000 to 1001.</p> <pre><code>101110000 1001 --------- XOR the 1011 and 1001 0010 </code></pre> <p>Now we will <strong>remove the zeros at the beginning of our XOR result</strong> which is 0010 and <strong>slide numbers from the top</strong>.</p> <pre><code>101110000 1001 --------- 1010 </code></pre> <p>Continue the XOR 1001 with the result.</p> <pre><code>101110000 1001 --------- 1010 1001 --------- 0011 --------- Remove zeros at the beginning 1100 1001 --------- 0101 --------- Remove zeros at the beginning 1010 1001 --------- 0011 </code></pre> <p>Answer is 0011.</p>
44,876
<p>I want that list, because if something horrible happens, and I'll have to reinstall Visual Studio - I'll need this list, so that I can recreate the same development environment. This also makes it hard to search for updates - I can not see the versions of currently installed plug-ins.</p> <p>So, is there a single place in Visual Studio, that would show me a complete list of plug-ins and their versions?</p>
<p>The reason that exceptions on non-test threads (i.e. other spawned threads) do not cause tests to fail is that NUnit is configured by default to use <a href="http://msdn.microsoft.com/en-us/library/ms228965.aspx" rel="nofollow noreferrer">legacyUnhandledExceptionPolicy</a> which is a .Net process level setting which can be applied via app.config, i.e.:</p> <pre><code>&lt;legacyUnhandledExceptionPolicy enabled=&quot;1&quot;/&gt; </code></pre> <p>Enabling this setting (i.e. setting it to &quot;1&quot;) causes exceptions which do not occur on the main thread to be <em>ignored</em>.</p> <p>I wrote an article which goes into more detail in reference to this issue with the ReSharper test runner, but it applies equally to the NUnit test runner: <a href="https://web.archive.org/web/20101006004301/http://gojisoft.com/blog/2010/05/14/resharper-test-runner-hidden-thread-exceptions/" rel="nofollow noreferrer">https://web.archive.org/web/20101006004301/http://gojisoft.com/blog/2010/05/14/resharper-test-runner-hidden-thread-exceptions/</a>)</p> <blockquote> <h2>ReSharper test runner – hidden thread exceptions</h2> <p>By Tim Lloyd, May 14, 2010 4:31 pm</p> <p>We use the ReSharper test runner here at GojiSoft to run NUnit tests from within Visual Studio. It’s a great test runner, but doesn’t play nicely with multi-threaded components where exceptions may occur on non-test threads. Unhandled exceptions on non-test threads are hidden and tests which should fail, instead pass.</p> <p>...</p> <p>The problem lies in the fact that the ReSharper test runner is configured to behave in the same way as .Net 1.0 and 1.1 apps where unhandled exceptions on non-main threads were swallowed. The situation improves from .Net 2.0 where all unhandled exceptions flatten the process. However, Microsoft had to allow existing .Net 1.0 and 1.1 apps the option of behaving as before on new .Net frameworks. They introduced the app.config setting: legacyUnhandledExceptionPolicy.</p> <p>The ReSharper test runner is configured by default to use the .Net 1.0 and 1.1 policy, so if there is an unhandled non-test thread exception it does not bubble up and cause the test to fail – the test passes, and we get a false positive instead.</p> <p>If unhandled exceptions on non-test threads should fail tests, the app.config for the ReSharper test runner has to be updated.</p> <p>...</p> <ol start="3"> <li><p>Turn the legacy unhandled exception policy off by editing legacyUnhandledExceptionPolicy: <code>&lt;legacyUnhandledExceptionPolicy enabled=&quot;0&quot; /&gt;</code></p> </li> <li><p>Now multi-threaded tests fail as expected when they raise exceptions on non-test threads:</p> </li> </ol> <p>Buyer beware…</p> <p>There is a caveat to this. Exceptions on non-test threads will now flattened the test runner and test suite execution will be halted when they happen. This is in contrast to normal test runs where failed tests are marked as failed, and the test runner continues. ...</p> </blockquote>
<p>I solved the problem by creating an addin for nunit, which "installs" an ITestDecorator.</p>
45,937
<p>I want to call a function from a .NET DLL (coded in C#) from an Inno Setup script.</p> <p>I have:</p> <ol> <li>marked the <em>Register for COM interop</em> option in the project properties,</li> <li>changed the <em>ComVisible</em> setting in the <em>AssemblyInfo.cs</em> file,</li> <li>added these lines to the ISS script:</li> </ol> <blockquote> <p>[Files]</p> <p>Source: c:\temp\1\MyDLL.dll; Flags: dontcopy</p> <p>[Code]</p> <p>function MyFunction(): string;</p> <p>external 'MyFunction@files:MyDLL.dll stdcall setuponly';</p> </blockquote> <p>but I still get the following error:</p> <blockquote> <p>Runtime Error (at -1:0):</p> <p>Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll.</p> </blockquote> <p>What am I doing wrong?</p>
<p>Oops, my bad, it's been too long since I've read pascal! So, if you need to get the value then there are a couple of possibilities:</p> <ol> <li>Write the functionality in C/C++ and export the function, that's definitely supported.</li> <li>Use a Managed C++ dll to shim to your .NET dll, and expose the call as a C interface point (this should work, but it's getting messy)</li> <li>Use an .exe to store the result of your code in a .INI file or the registry or in a temp file and read the result in the setup code section (this is now properly nasty)</li> </ol> <p>When I last worked with InnoSetup it didn't support your scenario directly (calling .NET code from setup).</p>
<p>A .NET dll can be best called from any other programming language by exposing it as a COM object. Take a look at this example: <a href="http://support.microsoft.com/kb/828736" rel="nofollow noreferrer">http://support.microsoft.com/kb/828736</a>. This shows how to call a ".NET dll" from "unmanaged C++". You can replace the "unamanged C++" by any other programming language, that can be used as a COM client.</p>
6,741
<p>Let's say I have some code like this </p> <pre><code>if(isset($_GET['foo'])) //do something if(isset($_GET['bar'])) //do something else </code></pre> <p>If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&amp;bar=xyz, rather than example.com/?bar=xyz. </p> <p>I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.</p>
<p>Here's one way....</p> <pre><code>//get passed params //(you might do some sanitizing at this point) $params=$_GET; //morph the params with new values $params['bar']='xyz'; //build new query string $query=''; $sep='?'; foreach($params as $name=&gt;$value) { $query.=$sep.$name.'='.urlencode($value); $sep='&amp;'; } </code></pre>
<p>Just set the link that changes bar to xyz to also have foo=abc if foo is already set.</p> <pre><code>$link = ($_GET['foo'] == 'abc') ? 'foo=abc&amp;bar=xyz' : 'bar=xyz'; ?&gt; &lt;a href="whatever.php?&lt;?= $link ?&gt;"&gt;Click Me&lt;/a&gt; </code></pre>
47,154
<p>I have an Access DB that I would like to extract the source code from so I can put it into Source control. </p> <p>I have tried to extract the data using the Primary Interop Assemblies(PIA), but I am getting issues as it is not picking up all of the modules and forms. </p> <p>There are 140 Forms and Modules in the code(Don't ask, it's a legacy system I have inherited) but the PIA code is only picking up 91 of them. </p> <p>Here is the code I am using. </p> <pre><code>using System; using Microsoft.Office.Interop.Access; namespace GetAccesSourceFiles { class Program { static void Main(string[] args) { ApplicationClass appClass = new ApplicationClass(); try { appClass.OpenCurrentDatabase("C:\\svn\\projects\\db.mdb",false,""); Console.WriteLine(appClass.Version); Console.WriteLine(appClass.Modules.Count.ToString()); Console.WriteLine(appClass.Modules.Parent.ToString()); int NumOfLines = 0; for (int i = 0; i &lt; appClass.Modules.Count; i++) { Console.WriteLine(appClass.Modules[i].Name + " : " + appClass.Modules[i].CountOfLines); NumOfLines += appClass.Modules[i].CountOfLines; } Console.WriteLine("Number of Lines : " + NumOfLines); Console.ReadKey(); } catch(Exception ex) { Console.WriteLine(ex.Message + "\r\n" +ex.StackTrace); } finally { appClass.CloseCurrentDatabase(); appClass.Quit(AcQuitOption.acQuitSaveNone); } } } } </code></pre> <p>Any suggestions on what that code might be missing? or on a product/tool out there that will do this for me?</p> <p>Edit: I should also mention that this needs to script to disk, integration with VSS is not an option as our source system is SVN. Thanks.</p>
<p>There is a better way. You can use Visual Sourcesafe (and possibly other SCCs) to version control code and objects in place: see this <a href="http://msdn.microsoft.com/en-us/library/ms181088(VS.80).aspx" rel="nofollow noreferrer">MSDN article</a></p>
<p>You might also want to take a look at his Q&amp;A:</p> <p><a href="https://stackoverflow.com/questions/247292/working-with-multiple-programmers-on-ms-access">Working with multiple programmers on MS Access</a></p>
24,075
<p>I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time.</p> <p>This is what I have that works so far:</p> <pre><code>$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id"); </code></pre> <p>Is there a way to refactor this? Is there an easier way to figure this out?</p>
<p>Assign the same class to each div then:</p> <pre><code>$("div.myClass:visible").attr("id"); </code></pre>
<p>When applicable, it's better to use contextual selectors rather than add spurious classes. For instance, if the <code>&lt;div&gt;</code> elements are the only children of an element with <code>id="foo"</code>, then using <code>$("#foo &gt; div:visible").attr("id")</code> would better reflect the purpose of the code.</p>
8,673
<p>I've inherited a BizTalk 2006 application that uses several SOAP ports to request data from a 3rd party web service. The web service is secured by "basic" authentication - username / password. After making a few enhancements to the application I deployed to an integration test server which has access to the 3rd party web service. The BizTalk app was unable to retrieve the data and I soon realised that I had forgotten to set the username / password on the SOAP send ports. I wanted the make deployment of the BizTalk app as automated as possible because I may not be present when it is deployed to the live server. I opened up the binding file, located the 1st of the problem SOAP send ports and looked for the <strong>* that BizTalk uses to replace the password - except that it doesn't! It seems that the password for SOAP ports is set to NULL rather than *</strong>, see here for more details: <a href="http://msdn.microsoft.com/en-us/library/aa547319.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa547319.aspx</a></p> <p>I proceeded to update the binding but when I came to test, after importing my amended binding file, I found that I had the same problem as before. I've double checked and can confirm that the correct password is now present in the binding file but, although BizTalk doesn't complain during the import, when I run the app I get the following exception:</p> <p><em>Details:"ArgumentNullException: String reference not set to an instance of a String. Parameter name: s ".</em></p> <p>If I then manually amend the password through the BizTalk admin console everything work fine. </p> <p>Has anyone else had a similar problem with the bindings for a SOAP port - does anyone have a solution?</p>
<p>I've been bit by something like this in the past. The password is either put in as '****'. This is ok. I wouldn't want all of my secrets exported with the binding file. What does get you is when you export the bindings and you leave the password NULL. The Variable Type (vt) attribute on the XML element for the password is set to vt="1" which is the same as NULL. It won't matter what you put in for the password. It may even cause the error you described. I would suggest you include a copy of the binding XML for review.</p>
<p>I've never seen this problem before - I'm doing exactly what you are trying to do and it works perfectly.</p> <p>I've included the &lt;TransportTypeData&gt; element from one of my BizTalk bindings that works. Hopefully having something to compare against helps.</p> <pre><code>&lt;TransportTypeData&gt; &amp;lt;CustomProps&amp;gt; &amp;lt;AuthenticationScheme vt="8"&amp;gt;Basic&amp;lt;/AuthenticationScheme&amp;gt; &amp;lt;AssemblyName vt="8"&amp;gt;WebService.ProxyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xyz&amp;lt;/AssemblyName&amp;gt; &amp;lt;Username vt="8"&amp;gt;soapUser&amp;lt;/Username&amp;gt; &amp;lt;UseProxy vt="11"&amp;gt;0&amp;lt;/UseProxy&amp;gt; &amp;lt;UseSoap12 vt="11"&amp;gt;0&amp;lt;/UseSoap12&amp;gt;&amp;lt;UsingOrchestration vt="11"&amp;gt;0&amp;lt;/UsingOrchestration&amp;gt; &amp;lt;UseSSO vt="11"&amp;gt;0&amp;lt;/UseSSO&amp;gt; &amp;lt;Password vt="8"&amp;gt;MYPASSWORD&amp;lt;/Password&amp;gt; &amp;lt;ProxyPort vt="3"&amp;gt;80&amp;lt;/ProxyPort&amp;gt;&amp;lt;AssemblyPath vt="8"&amp;gt;C:\ProxyClass\bin\Debug\ProxyClass.dll&amp;lt;/AssemblyPath&amp;gt; &amp;lt;TypeName vt="8"&amp;gt;ProxyClass.Webservice.servicesService&amp;lt;/TypeName&amp;gt; &amp;lt;MethodName vt="8"&amp;gt;PickupRequest&amp;lt;/MethodName&amp;gt; &amp;lt;UseHandlerSetting vt="11"&amp;gt;-1&amp;lt;/UseHandlerSetting&amp;gt; &amp;lt;/CustomProps&amp;gt; &lt;/TransportTypeData&gt; </code></pre>
42,219
<p>I've already written a generator that does the trick, but I'd like to know the best possible way to implement the off-side rule.</p> <p>Shortly: <a href="http://en.wikipedia.org/wiki/Off-side_rule" rel="noreferrer">Off-side rule</a> means in this context that indentation is getting recognized as a syntactic element.</p> <p>Here is the offside rule in pseudocode for making tokenizers that capture indentation in usable form, I don't want to limit answers by language:</p> <pre><code>token NEWLINE matches r"\n\ *" increase line count pick up and store the indentation level remember to also record the current level of parenthesis procedure layout tokens level = stack of indentation levels push 0 to level last_newline = none per each token if it is NEWLINE put it to last_newline and get next token if last_newline contains something extract new_level and parenthesis_count from last_newline - if newline was inside parentheses, do nothing - if new_level &gt; level.top push new_level to level emit last_newline as INDENT token and clear last_newline - if new_level == level.top emit last_newline and clear last_newline - otherwise while new_level &lt; level.top pop from level if new_level &gt; level.top freak out, indentation is broken. emit last_newline as DEDENT token clear last_newline emit token while level.top != 0 emit token as DEDENT token pop from level comments are ignored before they are getting into the layouter layouter lies between a lexer and a parser </code></pre> <p>This layouter doesn't generate more than one NEWLINE at time, and doesn't generate NEWLINE when there's indentation coming up. Therefore parsing rules remain quite simple. It's pretty good I think but inform if there's better way of accomplishing it.</p> <p>While using this for a while, I've noticed that after DEDENTs it may be nice to emit newline anyway, this way you can separate the expressions with NEWLINE while keeping the INDENT DEDENT as a trailer for expression.</p>
<p>I've written tokenizers and parsers for a couple of little indentation-centric domain-specific languages in the past couple of years, and what you have there looks pretty reasonable to me, for whatever that's worth. If I'm not mistaken, your method is quite similar to what Python does, for example, which seems like it ought to carry some weight.</p> <p>Converting NEWLINE NEWLINE INDENT to just INDENT before it hits the parser definitely seems like the right way to do things -- it's a pain (IME) to always be peeking ahead for that in the parser! I've actually done that step as a separate layer in what ended up being a three step process: the first combined what your lexer and layouter do minus all the NEWLINE lookahead stuff (which made it very simple), the second (also very simple) layer folded consecutive NEWLINEs and converted NEWLINE INDENT to just INDENT (or, actually, COLON NEWLINE INDENT to INDENT, since in this case all indented blocks were always preceded by colons), then the parser was the third stage on top of that. But it also makes a lot of sense to me to do things the way you've described them, especially if you want to separate the lexer from the layouter, which presumably you'd want to do if you were using a code-generation tool to make your lexer, for instance, as is common practice.</p> <p>I did have one application that needed to be a bit more flexible about indentation rules, essentially leaving the parser to enforce them when needed -- the following needed to be valid in certain contexts, for instance:</p> <pre><code>this line introduces an indented block of literal text: this line of the block is indented four spaces but this line is only indented two spaces </code></pre> <p>which doesn't work terribly well with INDENT/DEDENT tokens, since you end up needing to generate one INDENT for each column of indentation and an equal number of DEDENTs on the way back, unless you look way ahead to figure out where the indent levels are going to end up being, which it doesn't seem like you'd want a tokenizer to do. In that case I tried a few different things and ended up just storing a counter in each NEWLINE token that gave the change in indentation (positive or negative) for the following logical line. (Each token also stored all trailing whitespace, in case it needed preserving; for NEWLINE, the stored whitespace included the EOL itself, any intervening blank lines, and the indentation on the following logical line.) No separate INDENT or DEDENT tokens at all. Getting the parser to deal with that was a bit more work than just nesting INDENTs and DEDENTs, and might well have been hell with a complicated grammar that needed a fancy parser generator, but it wasn't nearly as bad as I'd feared, either. Again, no need for the parser to look ahead from NEWLINE to see if there's an INDENT coming up in this scheme.</p> <p>Still, I think you'd agree that allowing and preserving all manner of crazy-looking whitespace in the tokenizer/layouter and letting the parser decide what's a literal and what's code is a bit of an unusual requirement! You certainly wouldn't want your parser to be saddled with that indentation counter if you just wanted to be able to parse Python code, for example. The way you're doing things is almost certainly the right approach for your application and many others besides. Though if anyone else has thoughts on how best to do this sort of thing, I'd obviously love to hear them....</p>
<p>Tokenizer in ruby for fun:</p> <pre><code>def tokenize(input) result, prev_indent, curr_indent, line = [""], 0, 0, "" line_started = false input.each_char do |char| case char when ' ' if line_started # Content already started, add it. line &lt;&lt; char else # No content yet, just count. curr_indent += 1 end when "\n" result.last &lt;&lt; line + "\n" curr_indent, line = 0, "" line_started = false else # Check if we are at the first non-space character. unless line_started # Insert indent and dedent tokens if indentation changed. if prev_indent &gt; curr_indent # 2 spaces dedentation ((prev_indent - curr_indent) / 2).times do result &lt;&lt; :DEDENT end result &lt;&lt; "" elsif prev_indent &lt; curr_indent result &lt;&lt; :INDENT result &lt;&lt; "" end prev_indent = curr_indent end # Mark line as started and add char to line. line_started = true; line &lt;&lt; char end end result end </code></pre> <p>Does only work for two-space-indentation. Result is something like <code>["Hello there from level 0\n", :INDENT, "This\nis level\ntwo\n", :DEDENT, "This is level0 again\n"]</code>.</p>
28,795
<p>I'm trying to fix a non-responsive USB device that's masquerading as a virtual COM port. Manual replugging works, but there may be up to 12 of these units. Is there an API command to do the programmatic equivalent of the unplug/replug cycle?</p>
<p>What about using Devcon.exe to "remove" and then "rescan"?</p> <p>DR</p>
<p>Programmatically <a href="https://stackoverflow.com/questions/85649/safe-remove-usb-drive-using-win32-api">unmounting a USB drive</a> can be done, however, I don't know if remounting can be done via code.</p>
16,756
<p>Is there a command within the bash shell of fedora that will give me the currently assigned IP address?</p>
<p><a href="http://linux.die.net/man/8/ifconfig" rel="nofollow noreferrer">ifconfig</a> is what you're looking for</p>
<p>Try the following command:</p> <pre><code>ipconfig getifaddr eth0 </code></pre>
21,882
<p>I am wanting to access a website from a different port than 80 or 8080. Is this possible? I just want to view the website but through a different port. I do not have a router. I know this can be done because I have a browser that accessing websites through different ports, Called XB Browser by Xero Bank.</p> <hr> <p>Thanks for the answers. So, if I setup a proxy on one computer, I could have it go from my computer, to another computer that then returns the website to me. Would this bypass logging software?</p>
<p>If your question is about IIS(or other server) configuration - yes, it's possible. All you need is to create ports mapping under your Default Site or Virtual Directory and assign specific ports to the site you need. For example it is sometimes very useful for web services, when default port is assigned to some UI front-end and you want to assign service to the same address but with different port.</p>
<p>when viewing a website it gets assigned a random port, it will always come from port 80 (usually always, unless the server admin has changed the port) there's no way for someone to change that port unless you have control of the server.</p>
10,473
<p>Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:</p> <pre><code>cat * | wc -l </code></pre> <p>However, if there are sub-directories, this doesn't work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?</p>
<p>First you do not need to use <code>cat</code> to count lines. This is an <a href="http://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat" rel="noreferrer">antipattern called Useless Use of Cat</a> (UUoC). To count lines in files in the current directory, use <a href="https://en.wikipedia.org/wiki/Wc_(Unix)" rel="noreferrer"><code>wc</code></a>:</p> <pre><code>wc -l * </code></pre> <p>Then the <code>find</code> command recurses the sub-directories:</p> <pre><code>find . -name "*.c" -exec wc -l {} \; </code></pre> <ul> <li><p><code>.</code> is the name of the top directory to start searching from</p></li> <li><p><code>-name "*.c"</code> is the pattern of the file you're interested in </p></li> <li><p><code>-exec</code> gives a command to be executed</p></li> <li><p><code>{}</code> is the result of the find command to be passed to the command (here <code>wc-l</code>)</p></li> <li><p><code>\;</code> indicates the end of the command </p></li> </ul> <p>This command produces a list of all files found with their line count, if you want to have the sum for <strong>all</strong> the files found, you can use find to list the files (with the <code>-print</code> option) and than use xargs to pass this list as argument to wc-l.</p> <pre><code>find . -name "*.c" -print | xargs wc -l </code></pre> <p>EDIT to address Robert Gamble comment (thanks): if you have spaces or newlines (!) in file names, then you have to use <code>-print0</code> option instead of <code>-print</code> and <code>xargs -null</code> so that the list of file names are exchanged with null-terminated strings. </p> <pre><code>find . -name "*.c" -print0 | xargs -0 wc -l </code></pre> <p>The Unix philosophy is to have tools that do one thing only, and do it well.</p>
<p>Here's a Bash script that counts the lines of code in a project. It traverses a source tree recursively, and it excludes blank lines and single line comments that use "//".</p> <pre><code># $excluded is a regex for paths to exclude from line counting excluded="spec\|node_modules\|README\|lib\|docs\|csv\|XLS\|json\|png" countLines(){ # $total is the total lines of code counted total=0 # -mindepth exclues the current directory (".") for file in `find . -mindepth 1 -name "*.*" |grep -v "$excluded"`; do # First sed: only count lines of code that are not commented with // # Second sed: don't count blank lines # $numLines is the lines of code numLines=`cat $file | sed '/\/\//d' | sed '/^\s*$/d' | wc -l` total=$(($total + $numLines)) echo " " $numLines $file done echo " " $total in total } echo Source code files: countLines echo Unit tests: cd spec countLines </code></pre> <p>Here's what the output looks like for <a href="https://github.com/curran/phd/tree/f1ab3319a27c2bd3283df3402e568ce69be670de/prototype" rel="nofollow">my project</a>:</p> <pre><code>Source code files: 2 ./buildDocs.sh 24 ./countLines.sh 15 ./css/dashboard.css 53 ./data/un_population/provenance/preprocess.js 19 ./index.html 5 ./server/server.js 2 ./server/startServer.sh 24 ./SpecRunner.html 34 ./src/computeLayout.js 60 ./src/configDiff.js 18 ./src/dashboardMirror.js 37 ./src/dashboardScaffold.js 14 ./src/data.js 68 ./src/dummyVis.js 27 ./src/layout.js 28 ./src/links.js 5 ./src/main.js 52 ./src/processActions.js 86 ./src/timeline.js 73 ./src/udc.js 18 ./src/wire.js 664 in total Unit tests: 230 ./ComputeLayoutSpec.js 134 ./ConfigDiffSpec.js 134 ./ProcessActionsSpec.js 84 ./UDCSpec.js 149 ./WireSpec.js 731 in total </code></pre> <p>Enjoy! --<a href="https://github.com/curran/portfolio" rel="nofollow">Curran</a></p>
40,880
<p>What property in Netbeans to I need to change to set the name of my java swing app in the OS X menubar and dock? I found info.plist, but changing @PROJECTNAMEASIDENTIFIEER@ in multiple keys here had no effect.</p> <p>Thanks, hating netbeans.</p>
<p>The answer depends on how you run your application. If you run it from the command line, use '-Xdock:name=appname' in the JVM arguments. See the section "More tinkering with the menu bar" in the article linked to by Dan Dyer.</p> <p>If you are making a bundled, double-clickable application, however, you just need to set the standard CFBundle-related keys in your application's Info.plist (see the <a href="http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/PListKeys.html" rel="nofollow noreferrer">documentation on Info.plist keys</a> for more details).</p>
<p>This is not NetBeans-specific, but <a href="http://java.sun.com/developer/technicalArticles/JavaLP/JavaToMac/" rel="nofollow noreferrer">this article</a> has some useful tips about tweaking your Swing apps so that they fit in on OS X.</p>
15,778
<p>I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task.</p> <p>Has anyone gotten this to work?</p> <p>Caveat: The stored procedure uses two temp tables (and cleans them up, of course)</p>
<p>Enter some valid values for the stored procedure parameters so it runs and returns some data (or even no data, you just need the columns). Then you should be able to do the mapping/etc.. Then do a disconnected edit and change to the actual parameter values (I assume you are getting them from a global variable).</p> <pre><code>DECLARE @param1 DataType1 DECLARE @param2 DataType2 SET @param1 = global variable SET @param2 = global variable (I forget exact syntax) --EXEC procedure @param1, @param2 EXEC dbo.proc value1, value2 </code></pre> <p>Basically you run it like this so the procedure returns results. Do the mapping, then in disconnected edit comment out the second <code>EXEC</code> and uncomment the first <code>EXEC</code> and it should work.</p> <p>Basically you just need to make the procedure run and spit out results. Even if you get no rows back, it will still map the columns correctly. I don't have access to our production system (or even database) to create dts packages. So I create them in a dummy database and replace the stored procedure with something that returns the same columns that the production app would run, but no rows of data. Then after the mapping is done I move it to the production box with the real procedure and it works. This works great if you keep track of the database via scripts. You can just run the script to build an empty shell procedure and when done run the script to put back the true procedure.</p>
<p>You would need to actually load them into a table, then you can use a SQL task to move it from that table into the perm location if you must make a translation.</p> <p>however, I have found that if working with a stored procedure to source the data, it is almost just as fast and easy to move it to its destination at the same time!</p>
11,320
<p>I can't seem to find Developer Express' version of the <code>LinkButton</code>. (The Windows Forms linkbutton, not the <code>ASP.NET</code> linkbutton.) <code>HyperLinkEdit</code> doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox.</p> <p>Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1.</p>
<p>The control is called the HyperLinkEdit. You have to adjust the properties to get it to behave like the System.Windows.Forms control like so:</p> <pre><code> control.BorderStyle = BorderStyles.NoBorder; control.Properties.Appearance.BackColor = Color.Transparent; control.Properties.AppearanceFocused.BackColor = Color.Transparent; control.Properties.ReadOnly = true; </code></pre>
<p>You should probably just use the standard ASP.Net LinkButton, unless it's really missing something you need.</p>
2,571
<p>I have a project that has the following line in the additional includes section:</p> <p>"$(SOMEPATH_SHORTNAME)\include"</p> <p>Can someone tell me where I can find $(SOMEPATH) defined? I can't find it by simply searching in Visual Studio</p>
<p>If it's not an environment variable, the place to look is the macros. In the property sheets, click the (...) button beside the "Addition Include Directories" line, and expand the "Macros>>" button in the dialog that pops up. </p>
<ul> <li>Right-click My Computer, and then click Properties.</li> <li>Click the Advanced tab.</li> <li>Click Environment variables.</li> <li>Click one the following options, for either a user or a system variable:</li> <li>Click New to add a new variable name and value.</li> <li>Click an existing variable, and then click Edit to change its name or value.</li> </ul>
35,621
<p><strong>Problem Statement:</strong> I would like to create an offline database to lookup prices/info on the n most useful books to sell in the United States (where n is probably 3 million or so). </p> <p><strong>Question:</strong> So, my question is (and I am open to other approaches here as well), I am trying to figure out how to use Amazon AWS to download a list of the n higest salesrank books being sold as well as some information about the book (i.e. title, prices, etc...).</p> <p><strong>What I have done so far:</strong> First, something like this exists already (asellertool.com), however, I thought this would be an interesting project to work on and quite frankly, we aren't serious enough to need to pay the $30/month subscription.</p> <p>Now, AWS is great (and easy) if you have a few items you want to look up, but I can't seem to figure out how enumerate on sales rank. Originally, I was hoping to enumerate all of the book items Amazon had by ISBN. But that wasn't available either. Then I thought I could find a list of all ISBN numbers out there, but that was a dead end too. Finally I thought I could create my own list of ISBN numbers, but as I did some back of the envelope calculations, I thought better of it as my solutions would take roughly a year to go through a third of the 10 digit space at 100/second (and it was overkill anyway).</p> <p>So, I am back on Sales Ranking, which is currently seems like a dead end as well. So, if you have any thoughts, I would appreciate it.</p>
<p>Amazon has a data feed service you can use which contains GZipped xml files of all their products based on top level categories. It's updated once a day and totals about 20GB/110GB of compressed/uncompressed data. Since you only need books it's more in the area of 4GB/31GB. The only thing is I'm not sure who's able to use this and what's involved with getting an account. They don't list anything about this on their website as far as I know so you will most likely have to contact someone there to find out more about it. We use this at work for stuff we do with them and it's some of the craziest xml processing I've had to do.</p>
<p>I was wondering which one of Amazon AWS services you want to use? Or you don't know?</p> <p>And why you need offline database? Why not make requests on everything you need and make some temporary cache?</p>
39,951
<p>I am using Team Foundation Server (TFS) for Visual Studio 2005.</p> <p>Whenever i wish to compare two file's versions TFS displays a window with the differences.</p> <p><strong>The problem is that it is always split vertically.</strong></p> <p>In fact, almost every time, <strong>i would prefer to have it split horizontally.</strong> I've already looked at TFS options and googled but i found nothing. I'm appalled to think that such option is not available!</p> <p>Is there any way to configure TFS to split it horizontally?</p>
<p>I've found the built in differencing tool in TFS woefully lacking so I set up WinMerge (<a href="http://www.winmerge.org/" rel="noreferrer">http://www.winmerge.org/</a>) in my environment in Tools -> Options -> Source COntrol -> Visual Studio Team Foundation.</p> <p>A nice blog post exists below:</p> <p><a href="http://www.vitalygorn.com/blog/post/2007/12/Better-DiffMerge-tool-for-TFS.aspx" rel="noreferrer">http://www.vitalygorn.com/blog/post/2007/12/Better-DiffMerge-tool-for-TFS.aspx</a></p>
<p>I have Visual Studio 2012 and I get to choose between side - by - side options and inline mode. With inline mode, the before and after appear one below the other so that I have the full window for editing.</p> <p><a href="https://stackoverflow.com/questions/18316799/visual-studio-2012-code-review-difference-window">Related post on StackOverflow</a></p>
22,806
<p>I am in a process of designing a custom SharePoint application. On a previous project, all the data was kept in SharePoint lists and that's the way I've been trying now. But, I'm getting to the point where the data model grows and I feel a need to normalize it and split one logical entity into several physical lists. I'm wondering if I should switch from the SP lists to a classic database. On one hand, I am happy with the SharePoint out-of-box New Item, Edit Item, All Items forms; on the other hand I'm worried that the performance will suffer once I have to query joined data (if it stays in <code>SPList</code>s).<br> If you have any insight or experience with this problem, please share. Thanks.</p>
<p>It depends on your requirements, but from my experience here are the cases when you should use database instead of lists:</p> <p>1) When you have a many-to-many relationship in your database model</p> <p>2) When you have two or more entities linked together (e.g. Customer > Invoice > Invoice Product). </p> <p>SharePoint is great but in the above scenarios you will have problems with SharePoint UI limitations.</p> <p>3) If you plan to have any custom reports or charts you should stick to your own database. </p> <p>When you are using database entities the best approach is to develop your own web parts since BDC is expensive and very limited for most cases. You can also check 3rd party web parts (e.g. Bamboo Web Parts)</p> <hr> <p>Here are the reasons to use SharePoint lists over database:</p> <ul> <li>Permissions</li> <li>Ease of usage for the end user</li> <li>Edit in datasheet / Excel / Access</li> <li>Workflows</li> <li>Search</li> </ul>
<p>In addition to Maxim's answer, I would also advise that you take searching into consideration. OTB Search is really nice if this data is going to be something you will need to dig into.</p>
31,246
<p>I have a Server 2003 box with about 6 sites that each have about 15-20 host headers.</p> <p>Is there a tool out there that will copy all the host header records and automatically move them to the new server so I don't have to manually enter each host header again in the new server?</p> <p>Thanks.</p>
<p>If you save the configuration via the IIS Manager (right-click All Tasks -> Save Configuration to a file) this will export all the host header information along with everything else about the website. Then on the new server you can import this configuration to recreate the website.</p>
<p>You can try the Web Deployment Tool, which can sync settings between IIS servers: <a href="http://www.iis.net/downloads/default.aspx?tabid=34&amp;g=6&amp;i=1602" rel="nofollow noreferrer">http://www.iis.net/downloads/default.aspx?tabid=34&amp;g=6&amp;i=1602</a></p> <p>You should also be able to export the settings from one IIS box and import them on the other.</p>
29,741
<p>I've been experiencing the good and the bad sides of messaging systems in <strong>real production environments</strong>, and I must admit that a well organized table or schema of tables simply beats every time any other form of messaging queue, because:</p> <ol> <li>Data are permanently stored on a table. I've seen so many java (jms) applications that lose or vanish messages on their way for uncaught exceptions or other bugs.</li> <li>Queues tend to fill up. Db storage is virtually infinite, instead.</li> <li>Tables are easily accessible, while you have to use esotic instruments to read from a queue.</li> </ol> <p>What's your opinion on each approach?</p>
<p>The phrase <em>beats every time</em> totally depends on what your requirements were to begin with. Certainly its not going to beat every time for everyone.</p> <p>If you are building a single system which is already using a database, you don't have very high performance throughput requirements and you don't have to communicate with any other teams or systems then you're probably right.</p> <p>For simple, low thoughput, mostly single threaded stuff, database are a totally fine alternative to message queues.</p> <p>Where a message queue shines is when</p> <ul> <li>you want a high performance, highly concurrent and scalable load balancer so you can process tens of thousands of messages per second concurrently across many servers/processes (using a database table you'd be lucky to process a few hundred a second and processing with multiple threads is pretty hard as one process will tend to lock the message queue table)</li> <li>you need to communicate between different systems using different databases (so don't have to hand out write access to your systems database to other folks in different teams etc)</li> </ul> <p>For simple systems with a single database, team and fairly modest performance requirements - sure use a database. Use the right tool for the job etc.</p> <p>However where message queues shine is in large organisations where there are lots of systems that need to communicate with each other (and so you don't want a business database to be a central point of failure or place of version hell) or when you have high performance requirements.</p> <p>In terms of performance a message queue will always beat a database table - as message queues are specifically designed for the job and don't rely on pessimistic table locks (which are required for a database implementation of a queue - to do the load balancing) and <a href="http://activemq.apache.org/what-is-the-prefetch-limit-for.html" rel="noreferrer">good message queues will perform eager loading of messages to queues to avoid the network overhead of a database</a>.</p> <p>Similarly - you'd never use a database to do load balancing of HTTP requests across your web servers - as it'd be too slow - if you have high performance requirements for your load balancer you'd not use a database either.</p>
<p>Queues provide reliable messaging. The store-and-forward, disconnected nature of queueing make it much more scalable than databases, not to mention more robust.</p> <p>And queues shouldn't really be used for permanent storage of information - it is best to think of them as temporary inboxes, unlike databases.</p>
31,916
<p>I'm looking at the code for a phase accumulator, and I must be a simpleton because I don't get it. The code is simple enough:</p> <pre> Every Clock Tick do: accum = accum + NCO_param; return accum; </pre> <p>accum is a 32-bit register. Obviously, at some point it will roll-over.</p> <p>My question really is: How does this relate to the phase?</p>
<p><a href="http://en.wikipedia.org/wiki/Direct_digital_synthesis" rel="nofollow noreferrer">This article</a> may help. </p> <p>In the running step, the counter (properly called the phase accumulator) is instructed to advance by a certain increment on each pulse from the frequency reference. The output of the phase accumulator (the phase) is used to select each item in the data table in turn. Finally, the DAC converts this sequence of data to an analogue waveform.</p> <blockquote> <p>In the running step, the counter (properly called the phase accumulator) is instructed to advance by a certain increment on each pulse from the frequency reference. The output of the phase accumulator (the phase) is used to select each item in the data table in turn. Finally, the DAC converts this sequence of data to an analogue waveform. To generate a periodic waveform, the circuit is set up so that one pass through the table takes a time equal to the period of the waveform. For example, if the reference frequency is 1 MHz, and the table contains 1000 entries, then a complete pass through the table with a phase increment of 1 will take 1000 / 1 MHz = 1 ms, so the frequency of the output waveform will be 1/(1 ms) = 1 kHz.</p> <p>This system can generate a higher output frequency simply by increasing the phase increment so that the counter runs through the table more quickly. In the example above, the phase increment is equal to 1, so the next possible frequency is obtained by setting the increment to 2, resulting in a doubling of output frequency. To obtain a finer control of frequency than this, the standard phase increment can be set to, say, 10. This then allows slightly higher or lower output frequencies. For example, increasing the increment to 11 would increase the output frequency by 10%, and reducing it to 9 would decrease the output frequency by the same proportion. The more precision required over the frequency, the more bits are needed in the counter.</p> </blockquote>
<p>The formula is this: </p> <p>Example using oscillors that have a period of waveform(x) period = x(0-1) rather than x(0-2Pi)</p> <p>One variable per audio stream called acc/accumulator,</p> <p>Every sample, accumulate it by accadd:</p> <pre><code> var accadd = 1.0/( sampleRate / p2freq( note ) ) ; acc+= accadd; acc = acc%1.0;// not sure to do this as accurately using if statement. can reset acc every noteOn </code></pre> <p>If you are using classical Sin with 2pi period, use 2pi instead of 1.0</p> <p>Like that the waveform will run from 0-1 at p2freq(note) periods per second.</p>
26,195
<p>I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports <code>for each</code> syntax on stl lists et al to facilitate iteration. For example:</p> <pre><code>list&lt;Object&gt; myList; for each (Object o in myList) { o.foo(); } </code></pre> <p>I was very happy to discover it, but I'm concerned about portability for the dreaded day when someone decides I need to be able to compile my code in say, gcc or some other compiler. Is this syntax widely supported and can I use it without worrying about portability issues?</p>
<p>For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop.</p> <p>QuantumPete</p> <p>[edit] This seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref: <a href="http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx</a> [/edit]</p>
<p>My vote goes for Luc, </p> <p>Stick to the standard STL algorithms and you will be better off by far. STL algorithms can make your life very easy, efficient and safe. Take a look at the off the shelve algorithms like find_if, count, count_if, sort, transform, etc... </p> <p>Point 5 onwards... <a href="http://www.sgi.com/tech/stl/table_of_contents.html" rel="nofollow noreferrer">http://www.sgi.com/tech/stl/table_of_contents.html</a></p> <p>Boost is cool, but if you are going to use it just for the FOR_EACH macro it is too much cumbersome regarding the development/build environment setup. </p> <p>use boost when standard c++ / stl cannot solve the problem in an 'easy' way. </p>
24,014
<p>What do you use as a test client for your stateful web services? Is it possible to use SoapUI? Are there best practices in this area?</p>
<p>You can do what's called a "Property Transfer" in SoapUI. For example, all our web services have to first call an authentication web service and obtain an authentication token.</p> <p>I've set this up in SoapUI so that the returned auth token from the auth service is passed on to subsequent requests. It seems to work pretty well, but unless I'm missing a trick I wouldn't like to set it up for a lot of web services (i.e. you have to have an entry for each call you want to transfer data to / from).</p>
<p>I don't know whether it's practical to do this with SoapUI, but I've done things like this with both iTKO LISA and Parasoft SOATest. It wasn't for testing stateful web services, but simply executing multiple testing steps, storing results that are used in following steps. Both LISA and SOATest have the ability to define steps in the GUI that can store pieces of responses that are used in later requests.</p>
36,989
<p>VC++ makes functions which are implemented within the class declaration inline functions.</p> <p>If I declare a class <code>Foo</code> as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?</p> <pre><code>class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } </code></pre>
<p>Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the &quot;inline&quot; keyword.</p> <p>In both cases it's a hint to the compiler. An &quot;inline&quot; function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.</p>
<p>To the same extent that we can make any other function inline, yes.</p>
4,154
<p><a href="http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html" rel="noreferrer">Resharper</a> certainly thinks so, and out of the box it will nag you to convert</p> <pre><code>Dooberry dooberry = new Dooberry(); </code></pre> <p>to</p> <pre><code>var dooberry = new Dooberry(); </code></pre> <p>Is that really considered the best style?</p>
<p>It's of course a matter of style, but I agree with Dare: <a href="http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx" rel="noreferrer">C# 3.0 Implicit Type Declarations: To var or not to var?</a>. I think using var instead of an explicit type makes your code less readable.In the following code:</p> <pre><code>var result = GetUserID(); </code></pre> <p>What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.</p> <p>Jeff wrote a post on this, saying <a href="http://blog.codinghorror.com/department-of-declaration-redundancy-department/" rel="noreferrer">he favors var</a>. But that guy's crazy!</p> <p>I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.</p>
<p>"Best style" is subjective and varies depending on context.</p> <p>Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.</p> <p>Other times, using the full class name is more helpful as it documents the code better than 'var' does.</p> <p>I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".</p> <p>Cheers!</p>
3,774
<p>When would you use a bigtabe/simpledb database vs a Relational database?</p>
<p>Relational databases give you a lot more layout and query flexibility, and are easier to use, but you also end up with more pain if you later need to partition your data if it won't fit on a single database server/cluster. BigTable and similar things scale essentially infinitely, but do so by not offering a bunch of relational database features and making the design problem a lot harder.</p> <p>Given probably 0.1% of places end up needing the BigTable level of scalability, you're almost always better off going with a relational database. If your data model is simple enough that either one would work, I'd be inclined to <em>still</em> pick a relational database.</p>
<p>Size, redundancy and performance are all key words that pop up in my head.</p> <p>It's fairly easy to create a little database that does its job but when you need to do significant scaling and redundancy, while keeping it performing at the speed of light, it's cheaper for lots of people to ship the job off to Amazon who've been doing it for a lot longer than most of us.</p>
17,371
<p>How can I access the apache basic-auth username in a PHP script?</p>
<p>Simply access this variable:</p> <pre><code>$_SERVER['PHP_AUTH_USER'] </code></pre>
<p>At my clients hoster <code>$_SERVER['PHP_AUTH_USER']</code> and <code>$_SERVER[&quot;HTTP_AUTHORIZATION&quot;]</code> were empty but <code>$_SERVER[&quot;REMOTE_USER&quot;]</code> was set!</p> <pre class="lang-php prettyprint-override"><code>if ($_SERVER[&quot;REMOTE_USER&quot;] == &quot;admin&quot;) echo &quot;Welcome, admin!&quot;; else echo &quot;Access denied&quot;; </code></pre>
40,915
<p>Can anyone recommend a library for chart generation (bar charts, pie charts etc.) which runs on both Java and .Net?</p>
<p><a href="http://www.advsofteng.com/" rel="noreferrer">ChartDirector</a> is fantastic and supports more than just Java and .NET.</p>
<p>Flash Charts.<br> <a href="http://www.fusioncharts.com/free/Gallery.asp" rel="nofollow noreferrer">http://www.fusioncharts.com/free/Gallery.asp</a></p>
4,677
<p>I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the <strong>id</strong>). What is the simplest way to accomplish this?</p> <p>I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.</p> <p>Perhaps something like this:</p> <pre class="lang-ruby prettyprint-override"><code> new_record = Record.copy(:id) </code></pre>
<p>To get a copy, use the <a href="https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup" rel="noreferrer">dup</a> (or clone for &lt; rails 3.1+) method:</p> <pre><code>#rails &gt;= 3.1 new_record = old_record.dup # rails &lt; 3.1 new_record = old_record.clone </code></pre> <p>Then you can change whichever fields you want.</p> <p><a href="http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001363" rel="noreferrer">ActiveRecord overrides the built-in Object#clone</a> to give you a new (not saved to the DB) record with an unassigned ID.<br /> Note that it does not copy associations, so you'll have to do this manually if you need to.</p> <p><a href="https://gist.github.com/994614" rel="noreferrer">Rails 3.1 clone is a shallow copy, use dup instead...</a></p>
<p>You can also check the <a href="https://github.com/esbanarango/acts_as_inheritable" rel="nofollow">acts_as_inheritable</a> gem.</p> <p>"Acts As Inheritable is a Ruby Gem specifically written for Rails/ActiveRecord models. It is meant to be used with the <a href="https://github.com/esbanarango/acts_as_inheritable#self-referential-association" rel="nofollow">Self-Referential Association</a>, or with a model having a parent that share the inheritable attributes. This will let you inherit any attribute or relation from the parent model."</p> <p>By adding <code>acts_as_inheritable</code> to your models you will have access to these methods:</p> <p><strong>inherit_attributes</strong></p> <pre class="lang-ruby prettyprint-override"><code>class Person &lt; ActiveRecord::Base acts_as_inheritable attributes: %w(favorite_color last_name soccer_team) # Associations belongs_to :parent, class_name: 'Person' has_many :children, class_name: 'Person', foreign_key: :parent_id end parent = Person.create(last_name: 'Arango', soccer_team: 'Verdolaga', favorite_color:'Green') son = Person.create(parent: parent) son.inherit_attributes son.last_name # =&gt; Arango son.soccer_team # =&gt; Verdolaga son.favorite_color # =&gt; Green </code></pre> <p><strong>inherit_relations</strong></p> <pre class="lang-ruby prettyprint-override"><code>class Person &lt; ActiveRecord::Base acts_as_inheritable associations: %w(pet) # Associations has_one :pet end parent = Person.create(last_name: 'Arango') parent_pet = Pet.create(person: parent, name: 'Mango', breed:'Golden Retriver') parent_pet.inspect #=&gt; #&lt;Pet id: 1, person_id: 1, name: "Mango", breed: "Golden Retriver"&gt; son = Person.create(parent: parent) son.inherit_relations son.pet.inspect # =&gt; #&lt;Pet id: 2, person_id: 2, name: "Mango", breed: "Golden Retriver"&gt; </code></pre> <p>Hope this can help you.</p>
8,482
<p>Is <em>CompileAssemblyFromDom</em> faster than <em>CompileAssemblyFromSource</em>?</p> <p>It <em>should</em> be as it presumably bypasses the compiler front-end.</p>
<p>CompileAssemblyFromDom compiles to a .cs file which is then run through the normal C# compiler.</p> <p>Example:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CSharp; using System.CodeDom; using System.IO; using System.CodeDom.Compiler; using System.Reflection; namespace CodeDomQuestion { class Program { private static void Main(string[] args) { Program p = new Program(); p.dotest(&quot;C:\\fs.exe&quot;); } public void dotest(string outputname) { CSharpCodeProvider cscProvider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.MainClass = null; cp.GenerateExecutable = true; cp.OutputAssembly = outputname; CodeNamespace ns = new CodeNamespace(&quot;StackOverflowd&quot;); CodeTypeDeclaration type = new CodeTypeDeclaration(); type.IsClass = true; type.Name = &quot;MainClass&quot;; type.TypeAttributes = TypeAttributes.Public; ns.Types.Add(type); CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Static; cmm.Name = &quot;Main&quot;; cmm.Statements.Add(new CodeSnippetExpression(&quot;System.Console.WriteLine('f'zxcvv)&quot;)); type.Members.Add(cmm); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(ns); CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu); foreach (CompilerError err in results.Errors) Console.WriteLine(err.ErrorText + &quot; - &quot; + err.FileName + &quot;:&quot; + err.Line); Console.WriteLine(); } } } </code></pre> <p>which shows errors in a (now nonexistent) temp file:</p> <blockquote> <p>) expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17</p> <p>; expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17</p> <p>Invalid expression term ')' - c:\Documents and Settings\jacob\Local Settings\Tem p\x59n9yb-.0.cs:17</p> </blockquote> <p>So I guess the answer is &quot;no&quot;</p>
<p>I've tried finding the ultimate compiler call earlier and I gave up. There's quite a number of layers of interfaces and virtual classes for my patience.</p> <p>I don't think the source reader part of the compiler ends up with a DOM tree, but intuitively I would agree with you. The work necessary to transform the DOM to IL should be much less than reading C# source code.</p>
2,659
<p>I'll admit that I don't know the inner workings of the unix operating system, so I was hoping someone could shed some light on this topic.</p> <p>Why is the Unix file system better than the windows file system?</p> <p>Would grep work just as well on Windows, or is there something fundamentally different that makes it more powerful on a Unix box?</p> <p>e.g. I have heard that in a Unix system, the number of files in a given directory will not slow file access, while on Windows direct file access will degrade as the # of files increase in the given folder, true?</p> <p>Updates: Brad, no such thing as the <a href="http://en.wikipedia.org/wiki/Unix_File_System" rel="noreferrer">unix file system</a>?</p>
<p>One of the fundamental differences in filesystem semantics between Unix and Windows is the idea of inodes.</p> <p>On Windows, a file name is directly attached to the file data. This means that the OS prevents somebody from deleting a file that is currently open. On some versions of Windows you can rename a file that is currently open, and on some versions you can't.</p> <p>On Unix, a file name is a pointer to an inode, which is the place the file data is actually stored. This has a couple of implications:</p> <ul> <li>You can have two different filenames that refer to the same underlying file. This is often called a <em>hard link</em>. There is only one copy of the file data, so changes made through one filename will appear in the other.</li> <li>You can delete (also known as <code>unlink</code>) a file that is currently open. All that happens is the directory entry is removed, but this doesn't affect any other process that might still have the file open. The process with the file open hangs on to the inode, rather than to the directory entry. When the process closes the file, the OS deletes the inode because there are no more directory entries pointing at it and no more processes with the inode open.</li> </ul> <p>This difference is important, but it is unrelated to things like the performance of <code>grep</code>.</p>
<p>The answer turns out to have very little to do with the filesystem and everything to do with the filesystem access drivers.</p> <p>In particular, the implementation of NTFS on Windows is very slow compared to ext2/ext3. Also on Windows, "can't delete file in use" even though NTFS should be able to support it.</p>
5,614
<p>Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.).</p> <p>I also want to be able to define a transparent color (not alpha channel) for this image.</p> <p><strong>The GdiPlus solution seems to be limited to images of width divisible by 4</strong>. Anything else fails during the call to Save(). Does anyone know the reason for this limitation and how/whether I can work around it?</p> <p><strong>Update: Bounty</strong></p> <p>I'm starting a bounty (I really want this to work). I implemented the GDI+ solution, but as I said, it's limited to images with quad width. The bounty will go to anyone who can solve this width issue (without changing the image dimensions), or can offer an alternative non-GDI+ solution that works.</p>
<p>I read and write PNGs using <a href="http://www.libpng.org/pub/png/libpng.html" rel="noreferrer">libpng</a> and it seems to deal with everthing I throw at it (I've used it in unit-tests with things like 257x255 images and they cause no trouble). I believe the <a href="http://www.libpng.org/pub/png/libpng-1.2.5-manual.html" rel="noreferrer">API</a> is flexible enough to not be tied to file I/O (or at least you can override its default behaviour e.g see <code>png_set_write_fn</code> in section on <a href="http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-5" rel="noreferrer">customization</a>)</p> <p>In practice I always use it via the much cleaner <a href="http://www.boost.org/doc/libs/1_38_0/libs/gil/doc/index.html" rel="noreferrer">boost::gil</a> <a href="http://stlab.adobe.com/gil/html/group___p_n_g___i_o.html" rel="noreferrer">PNG IO extension</a>, but unfortunately that takes <code>char*</code> filenames and if you dig into it the <code>png_writer</code> and <code>file_mgr</code> classes in its implementation it seem pretty tied to <code>FILE*</code> (although if you were on Linux a version using fmemopen and in-memory buffers could probably be cooked up quite easily).</p>
<p>It would probably be better to use a library instead of reinventing the wheel yourself.</p> <p>Look into <a href="http://freeimage.sourceforge.net/" rel="nofollow noreferrer">freeImage</a></p>
47,868
<p>I recently encountered an odd problem with <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.verifyhash.aspx" rel="noreferrer"><code>RSACryptoServiceProvider.VerifyHash</code></a>. </p> <p>I have a web application using it for decryption. When users running the web service were doing so over our VPN it became very very slow. When they had no connection or a internet connection they were fine.</p> <p>After much digging I found that every time <code>RSACryptoServiceProvider.VerifyHash</code> is called it makes an LDAP request to check <code>MyMachineName\ASPNET</code>.</p> <p>This doesn't happen with our WebDev (cassini based) servers as they run as the current user, and it is only really slow over the VPN, but it shouldn't happen at all.</p> <p>This seems wrong for a couple of reasons: </p> <ul> <li>Why is it checking the domain controller for a local machine user?</li> <li>Why does it care? The encryption/decryption works regardless.</li> </ul> <p>Does anyone know why this occurs or how best to work around it?</p>
<p>From this KB it looks like a 'wrinkle' in the code that needs sorting:</p> <p><a href="http://support.microsoft.com/kb/948080" rel="noreferrer">http://support.microsoft.com/kb/948080</a></p>
<p>Thanks (+1 &amp; ans)</p> <p>Tested and works.</p> <p>From the KB article:</p> <blockquote> <p>The SignData or VerifyData methods always perform an OID lookup query which is sent to the domain controller, even when the application is running in a local user account. This may cause slowness while signing or verifying data. Logon failure audit events occur on the DC because the client machine's local user account is not recognized by the domain. Therefore, the OID lookup fails.</p> </blockquote> <p>This is exactly what we were seeing.</p> <p>We changed this line:</p> <pre><code>rsa.VerifyHash( hashedData, CryptoConfig.MapNameToOID( "SHA1" ), signature ); </code></pre> <p>To this:</p> <pre><code>rsa.VerifyHash( hashedData, null, signature ); </code></pre> <p>And that fixed it.</p>
21,017
<p>With the age of text messages and things like that, what's a good way to store phone numbers in a database?</p> <p>In the USA, text messages are handled by phone numbers but in other countries I hear they use email addresses so I guess there needs to be a way to differentiate between countries that use cell phone numbers as their address. </p> <p>Addition: For example, people in the USA might use 432-342-3333 or 1-432-342-3333 while in the UK they might use +44 800 400000 or they might even leave out the 44. The 44 and the 1 makes a difference when automatically sending out SMS. However, checking the phone number for each country can get tedious. In this case, would you split the country code or would you merge it into a single column and deal it with it there? </p>
<p>I would primarily use a text field, or a series of text fields, even if you are using a numerical phone number for the following reasons. </p> <ol> <li>Phone numbers have a great range of values, including extension numbers which may result in numerical columns losing precision.</li> <li>Losing precision in a phone number is rather bad. </li> <li>There is no logical reason to want to perform math ( addition/multiplication ) on a phone number. </li> </ol> <p>Additionally, you may want to specify how you are using this data. If you are planning an automated messaging service, you're going to need a series of relaying agents to broadcast via, so you may as well add an identifier that pertains to the relay the information pertains to. Then all you have to worry about is that the relaying agent can understand the content in the text fields. </p>
<p>I don't know if you have read these two questions, but they might help you a little.</p> <ul> <li><a href="https://stackoverflow.com/questions/290597/phone-number-columns-in-a-database">Phone Number Columns in a Database</a></li> <li><a href="https://stackoverflow.com/questions/41925/is-there-a-standard-for-storing-normalized-phone-numbers-in-a-database">Is there a standard for storing normalized phone numbers in a database?</a></li> </ul> <p>Perhaps it would be wise to store the type of number (landline, cell, fax) and/or the messages that can be received on it (voice, text, email). Note that in the US, it is also possible to send text messages to a phone via email, but I believe that is dependent on the carrier.</p>
40,616
<p>Trying to use a guid as a resource id in a rest url but cant find any resource on how to. My best right now (not working though) is: <a href="http://localhost:49157/PhotogalleryDS.svc/gallery" rel="nofollow noreferrer">http://localhost:49157/PhotogalleryDS.svc/gallery</a>('1d03beb3-6d63-498b-aad7-fab0b1480996') (I've tried duouble/single quotes. And also {guid....} with braces. Still no luck.</p> <p>i only get: Syntax error '"' at position 0. </p> <p>Question is: How would I (with regard to specification) write the url for a resource where the id is a guid?</p>
<p>I figured it out!</p> <p><a href="http://localhost:49157/PhotogalleryDS.svc/photo(guid" rel="nofollow noreferrer">http://localhost:49157/PhotogalleryDS.svc/photo(guid</a>'01231cc7-1e26-4f33-9fdf-fdf7015267dd')</p> <p>This is the way</p>
<p>My best guess based on what you've written is that you're wrapping that URL in double quotes. The position 0 in that error message probably refers to the character directly before http</p>
4,648
<p>I'm generating a menu with a Repeater control bound to an XmlDataSource. </p> <pre><code>&lt;asp:Repeater ID="myRepeater" runat="server" DataSourceID="myDataSource" onitemdatabound="myRepeater_ItemDataBound" onitemcreated="myRepeater_ItemCreated"&gt; &lt;HeaderTemplate&gt; &lt;ul class="menu_list"&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;li id="liMenu" runat="server"&gt;&lt;asp:HyperLink ID="hrefMenuItem" runat="server" Text='&lt;%# XPath("@text")%&gt;' NavigateUrl='&lt;%# XPath("@href")%&gt;'&gt;&lt;/asp:HyperLink&gt;&lt;/li&gt; &lt;/ItemTemplate&gt; &lt;FooterTemplate&gt; &lt;/ul&gt; &lt;/FooterTemplate&gt; &lt;/asp:Repeater&gt; &lt;asp:XmlDataSource runat="server" ID ="myDataSource" XPath="Menu/Items/*" EnableCaching="False" /&gt; </code></pre> <p>I'd like to be able to set the style of the containing LI based on mouseover events and currently selected menu item. I tried via the HtmlGenericControl, but I receive an error that it's readonly.</p> <pre><code>protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { HyperLink hrefCurrentMenuLink = e.Item.FindControl("hrefMenuItem") as HyperLink; HtmlGenericControl l_genericControl = e.Item.FindControl("liMenu") as HtmlGenericControl; if ((hrefCurrentMenuLink != null) &amp;&amp; (l_genericControl != null)) { string l_currentPage = GetCurrentWebPage(); if (String.Compare(Path.GetFileNameWithoutExtension(hrefCurrentMenuLink.NavigateUrl), l_currentPage, StringComparison.OrdinalIgnoreCase) == 0) l_genericControl.Style = "on-nav"; else l_genericControl.Style = "off-nav"; l_genericControl.Attributes.Add("onmouseover", "navOn(this)"); l_genericControl.Attributes.Add("onmouseout", "navOff(this)"); } } } </code></pre> <p>Is there any way to accomplish this?</p>
<p>The style property is a collection. Do this:</p> <pre><code>l_genericControl.Style.Add("css-name", "css-value") </code></pre> <p>Or if you are using CSS classes, then change the CssClass property:</p> <pre><code>l_genericControl.CssClass = "on-nav"; </code></pre> <p>If you're trying to toggle the CSS class with your javascript, try something like this (untested):</p> <pre><code>l_genericControl.Attributes.Add("onmouseover", "this.className='on-nav';"); l_genericControl.Attributes.Add("onmouseout", "this.className='off-nav';"); </code></pre> <p>If you want to change the style with your javascript, this might work:</p> <pre><code>l_genericControl.Attributes.Add("onmouseover", "this.style.color='red'; this.style.backgroundColor='yellow';"); l_genericControl.Attributes.Add("onmouseout", "this.style.color='black'; this.style.backgroundColor='none';"); </code></pre>
<p>at the basic level, you could do:</p> <pre><code>l_genericControl.Attributes["class"] = "on-nav"; </code></pre>
43,991
<p>Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.</p> <p>Edit: Whilst not necessarily a solution, the work-around provided here: </p> <p><a href="https://stackoverflow.com/questions/39474/how-to-get-intellisense-to-reliably-work-in-visual-studio-2008#39590">How to get IntelliSense to reliably work in Visual Studio 2008</a></p> <p>Is probably the best bet if I want a decent IntelliSense system.</p>
<p>I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea.</p> <p>This is why we have bought <a href="http://www.wholetomato.com/" rel="noreferrer">Visual Assist</a> (from <a href="http://www.wholetomato.com/" rel="noreferrer">Tomato software</a>) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages)</p> <p>This is not a solution, just a workaround.</p>
<p>About this problem i've notice something interesting (on Visual Studio 2010): to solve this problem i've changed <code>#include</code> sintax in my header files, before was (old project done with VS 2005 and reopened using VS 2010):</p> <pre><code>#include &lt;myfile.h&gt; </code></pre> <p>and i fix this with:</p> <pre><code>#include "myfile.h" </code></pre> <p>After intellisense start working correctly! I hope this can help!</p>
6,054
<p>I've been doing c# for a long time, and have never come across an easy way to just new up a hash.</p> <p>I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.</p> <pre><code>{ "whatever" =&gt; {i =&gt; 1}; "and then something else" =&gt; {j =&gt; 2}}; </code></pre>
<p>If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.</p> <p>This example is based on the <a href="http://msdn.microsoft.com/en-us/library/bb531208.aspx" rel="noreferrer">MSDN Example</a></p> <pre><code>var students = new Dictionary&lt;int, StudentName&gt;() { { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }} }; </code></pre>
<pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Dictionary { class Program { static void Main(string[] args) { Program p = new Program(); Dictionary&lt;object, object &gt; d = p.Dic&lt;object, object&gt;("Age",32,"Height",177,"wrest",36);//(un)comment //Dictionary&lt;object, object&gt; d = p.Dic&lt;object, object&gt;();//(un)comment foreach(object o in d) { Console.WriteLine(" {0}",o.ToString()); } Console.ReadLine(); } public Dictionary&lt;K, V&gt; Dic&lt;K, V&gt;(params object[] data) { //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null; if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary&lt;K,V&gt;(1){{ (K)new Object(), (V)new object()}}; Dictionary&lt;K, V&gt; dc = new Dictionary&lt;K, V&gt;(data.Length / 2); int i = 0; while (i &lt; data.Length) { dc.Add((K)data[i], (V)data[++i]); i++; } return dc; } } } </code></pre>
7,568
<p>Notice how the default domain for stackoverflow is <a href="http://stackoverflow.com">http://stackoverflow.com</a> and if you try to goto <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> it bounces you to <a href="http://stackoverflow.com">http://stackoverflow.com</a> ?</p> <p>What is the reason for this? Not the tech reason (as in the http code, etc) but why would the site owners want to do this?</p> <p>I know it's purely aesthetic and I always have host-headers for both www and not, but is there a reason to bounce a user to a single domain, subheaded or not?</p> <h2>Update 1</h2> <h2>Not having a subdomain is called a <em>bare domain</em>. Thanks peeps! never knew it had a term :) Update 2</h2> <p>Thanks for the answers so far - please note I understand that <a href="http://www.domain.com" rel="nofollow noreferrer">www.domain.com</a> can point to domain.com. This is not a question about if i should offer both or either/or, it's asking why some sites default to a baredomain instead of www subdomains, or vice-versa. Cheers.</p> <p>Jeff Atwood actually HAS explained why he's gone for bare domains <a href="https://blog.stackoverflow.com/2008/06/dropping-the-www-prefix/">here</a> and <a href="https://blog.codinghorror.com/the-great-dub-dub-dub-debate/" rel="nofollow noreferrer">here</a>. (Nod to <a href="https://stackoverflow.com/users/1918/jonas-pegerfalk">Jonas Pegerfalk</a> for the post :) )</p> <p>Jeff's post (and others in this thread) also talk about the problems of a bare domain with cookies and static images. Basically, if you have cookies on in a bare domain, then all subdomains are forced also. The solution is to purchase another domain, as posted by the <a href="http://developer.yahoo.com/performance/rules.html#cookie_free" rel="nofollow noreferrer">Yahoo Perf Team here</a>.</p>
<p>Jeff Atwood has written a great article about the <a href="https://blog.codinghorror.com/the-great-dub-dub-dub-debate/" rel="nofollow noreferrer">The Great Dub-Dub-Dub Debate</a>. There is also a blog entry in the Stackoverflow blog on why and how Stackoverflow has <a href="https://stackoverflow.blog/2008/06/14/dropping-the-www-prefix/">dropped the www prefix</a>.</p>
<p>actually you can use both of them. So it's better to find user your address or some. I mean actually it doesn't really matter tho :)</p> <p>But putting www as a prefix is more common in public so I guess I'd prefer to use www behind it.</p>
46,297
<p>I'm using Windows XP Service Pack 3 and have Command Extensions enabled by default in the Windows Registry. Somehow, the following command does not work on this version of Windows but if I run it in Windows Server 2003 or Windows Vista Business, it works just fine. Any clue?</p> <p>The problem is that on Windows XP, it seems like the /f option is not working at all and the do part of the command never gets executed.</p> <p>This is the command:</p> <pre><code>for /f "tokens=1 delims=: " %A in ('tasklist /FI "IMAGENAME eq python.exe" /NH') do ( If "%A" == "python.exe" ( echo "It's running" ) Else ( echo "It's not running" ) ) </code></pre> <p>Thanks in advance.</p>
<p>That's because <code>tasklist.exe</code> outputs to <code>STDERR</code> when no task is found. The <code>for /f</code> loop gets to see <code>STDOUT</code> only, so in case <code>python.exe</code> is not running, it has nothing to loop on.</p> <p>Redirecting <code>STDERR</code> into <code>STDOUT</code> (<code>2&gt;&amp;1</code>) works:</p> <pre><code>for /F "tokens=1 delims=: " %A in ('tasklist /FI "IMAGENAME eq python.exe" /NH 2^&gt;^&amp;1') do ( if "%A"=="python.exe" ( echo "It's running" ) else ( echo "It's not running" ) ) </code></pre> <p>The <code>^</code> characters are escape sequences necessary for this to work.</p>
<p>This will work and not display the</p> <blockquote> <p>INFO: No tasks running with the specified criteria</p> </blockquote> <p>message:</p> <pre><code>@echo off set found=0 for /f "tokens=1 delims=: " %%A in ('tasklist /NH') do ( If /i "%%A" equ "python.exe" ( set found=1 ) ) if %found%==1 ( @echo It's running ) else ( @echo It's not running ) </code></pre>
46,850
<p>Suppose that you have two huge files (several GB) that you want to concatenate together, but that you have very little spare disk space (let's say a couple hundred MB). That is, given <code>file1</code> and <code>file2</code>, you want to end up with a single file which is the result of concatenating <code>file1</code> and <code>file2</code> together byte-for-byte, and delete the original files.</p> <p>You can't do the obvious <code>cat file2 &gt;&gt; file1; rm file2</code>, since in between the two operations, you'd run out of disk space.</p> <p>Solutions on any and all platforms with free or non-free tools are welcome; this is a hypothetical problem I thought up while I was downloading a Linux ISO the other day, and the download got interrupted partway through due to a wireless hiccup.</p>
<p>I think the difficulty is determining how the space can be recovered from the original files.</p> <p>I think the following might work:</p> <ol> <li>Allocate a sparse file of the combined size.</li> <li>Copy 100Mb from the end of the second file to the end of the new file.</li> <li>Truncate 100Mb of the end of the second file</li> <li>Loop 2&amp;3 till you finish the second file (With 2. modified to the correct place in the destination file).</li> <li>Do 2&amp;3&amp;4 but with the first file.</li> </ol> <p>This all relies on sparse file support, and file truncation freeing space immediately.</p> <p>If you actually wanted to do this then you should investigate the <code>dd</code> command. which can do the copying step</p> <p>Someone in another answer gave a neat solution that doesn't require sparse files, but does copy file2 twice:</p> <ol> <li>Copy 100Mb chunks from the end of file 2 to a new file 3, ending up in reverse order. Truncating file 2 as you go.</li> <li>Copy 100Mb chunks from the end of file 3 into file 1, ending up with the chunks in their original order, at the end of file 1. Truncating file 3 as you go.</li> </ol>
<p>"fiemap"</p> <p><a href="http://www.mjmwired.net/kernel/Documentation/filesystems/fiemap.txt" rel="nofollow noreferrer">http://www.mjmwired.net/kernel/Documentation/filesystems/fiemap.txt</a></p>
37,068
<p>I have a UL that looks like this:</p> <pre><code>&lt;ul class="popular-pages"&gt; &lt;li&gt;&lt;a href="region/us/california/"&gt;California&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/michigan/"&gt;Michigan&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/missouri/"&gt;Missouri&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/new-york/"&gt;New York&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/oregon/"&gt;Oregon&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/oregon-washington/"&gt;Oregon; Washington&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/pennsylvania/"&gt;Pennsylvania&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/texas/"&gt;Texas&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/virginia/"&gt;Virginia&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="region/us/washington/"&gt;Washington&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And CSS that looks like this:</p> <pre><code>ul.popular-pages li a { display:block; float:left; border-right:1px solid #b0b0b0; border-bottom:1px solid #8d8d8d; padding:10px; background-color:#ebf4e0; margin:2px; color:#526d3f } ul.popular-pages li a:hover { text-decoration:none; border-left:1px solid #b0b0b0; border-top:1px solid #8d8d8d; border-right:none; border-bottom:none; } </code></pre> <p>So it's working fine in modern browsers, but it's looking like this in IE6. Any suggestions? <img src="https://thecleverest.com/Picture_26.png" alt="alt text"></p>
<p>The reason for your layout is probably because you have the float on the anchor, move it to the list-item instead.</p> <pre> ul.popular-pages li { float: left; } </pre> <p>Since you're not setting any width in your LI's, I suggest skipping the float and set display: inline on your LI's instead, if you want them on a row. </p> <p>Adjust with padding/margin to get appropriate spacing between them, and line-height to get correct behaviour for any eventual 2nd line.</p> <p>That way you won't have problem with your UL not taking up space, without the need of a hidden clear-element at the end of the list (which is your other alternative)</p>
<p>What DOCTYPE are you using? DOCTYPE has an impact on how browsers render.</p>
35,591
<p>I need to know about Epoll On linux System.</p> <p>Could you recommend manual or guides about epoll library?</p> <p>need more detailed guides. it's better to have some examples.</p> <p>help me. and Thank you for reading.</p>
<p>Here's an introduction to Epoll, a pretty basic tutorial: <a href="https://kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/" rel="nofollow noreferrer">http://blog.kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/</a></p> <p>A more complete example can be found here: <a href="https://web.archive.org/web/20120504033548/https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/" rel="nofollow noreferrer">https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/</a></p> <p>Also, <a href="https://www.man7.org/linux/man-pages/man7/epoll.7.html" rel="nofollow noreferrer">the man pages</a></p>
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;sys/epoll.h&gt; #define PORT 1500 #define MAX_CON (1200) static struct epoll_event *events; int main(int argc, char *argv[]) { fd_set master; fd_set read_fds; struct sockaddr_in serveraddr; struct sockaddr_in clientaddr; int fdmax; int listener; int newfd; char buf[1024]; int nbytes; int addrlen; int yes; int epfd = -1; int res = -1; struct epoll_event ev; int i=0; int index = 0; int client_fd = -1; int SnumOfConnection = 0; time_t Sstart, Send; if((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Server-socket() error lol!"); exit(1); } if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &amp;yes, sizeof(int)) == -1) { perror("Server-setsockopt() error lol!"); exit(1); } serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = INADDR_ANY; serveraddr.sin_port = htons(PORT); memset(&amp;(serveraddr.sin_zero), '\0', 8); if(bind(listener, (struct sockaddr *)&amp;serveraddr, sizeof(serveraddr)) == -1) { perror("Server-bind() error lol!"); exit(1); } if(listen(listener, 10) == -1) { perror("Server-listen() error lol!"); exit(1); } fdmax = listener; /* so far, it's this one*/ events = calloc(MAX_CON, sizeof(struct epoll_event)); if ((epfd = epoll_create(MAX_CON)) == -1) { perror("epoll_create"); exit(1); } ev.events = EPOLLIN; ev.data.fd = fdmax; if (epoll_ctl(epfd, EPOLL_CTL_ADD, fdmax, &amp;ev) &lt; 0) { perror("epoll_ctl"); exit(1); } //time(&amp;start); for(;;) { res = epoll_wait(epfd, events, MAX_CON, -1); client_fd = events[index].data.fd; for (index = 0; index &lt; MAX_CON; index++) { if(client_fd == listener) { addrlen = sizeof(clientaddr); if((newfd = accept(listener, (struct sockaddr *)&amp;clientaddr, &amp;addrlen)) == -1) { perror("Server-accept() error lol!"); } else { // printf("Server-accept() is OK...\n"); ev.events = EPOLLIN; ev.data.fd = newfd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &amp;ev) &lt; 0) { perror("epoll_ctl"); exit(1); } } break; } else { if (events[index].events &amp; EPOLLHUP) { if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &amp;ev) &lt; 0) { perror("epoll_ctl"); } close(client_fd); break; } if (events[index].events &amp; EPOLLIN) { if((nbytes = recv(client_fd, buf, sizeof(buf), 0)) &lt;= 0) { if(nbytes == 0) { // printf("socket %d hung up\n", client_fd); } else { printf("recv() error lol! %d", client_fd); perror(""); } if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &amp;ev) &lt; 0) { perror("epoll_ctl"); } close(client_fd); } else { if(send(client_fd, buf, nbytes, 0) == -1) perror("send() error lol!"); } break; } } } } return 0; } </code></pre> <p>I wrote this program for testing and I was able to connect more than 80k connections and I find average system load only to 0.27%.</p>
4,689
<p>Unmanaged languages notwithstanding, is F# really better than C# for implementing math? And if that's the case, why?</p>
<p>I think most of the important points were already mentioned by someone else:</p> <ol> <li>F# lets you solve problems in a way mathematicians think about them</li> <li>Thanks to higher-order functions, you can use simpler concepts to solve difficult problems</li> <li>Everything is immutable by default, which makes the program easier to understand (and also easier to parallelize)</li> </ol> <p>It is definitely true that you can use some of the F# concepts in C# 3.0, but there are limitations. You cannot use any recursive computations (because C# doesn't have tail-recursion) and this is how you write primitive computations in functional/mathematical way. Also, writing complex higher order functions (that take other functions as arguments) in C# is difficult, because you have to write types explicitly (while in F#, types are inferred, but also automatically generalized, so you don't have to explicitly make a function generic).</p> <p>Also, I think the following point from Marc Gravell isn't a valid objection:</p> <blockquote> <p>From a maintenance angle, I'm of the view that suitably named properties etc are easier to use (over full life-cycle) than tuples and head/tail lists, but that might just be me.</p> </blockquote> <p>This is of course true. However, the great thing about F# is that you can start writing the program using tuples &amp; head/tail lists and later in the development process turn it into a program that uses .NET IEnumerables and types with properties (and that's how I believe typical F# programmer works*). Tuples etc. and F# interactive development tools give you a great way to quickly prototype solutions (and when doing something mathematical, this is essential because most of the development is just experimenting when you're looking for the best solution). Once you have the prototype, you can use simple source code transformations to wrap the code inisde an F# type (which can also be used from C# as an ordinary class). F# also gives you a lot of ways to optimize the code later in terms of performance.</p> <p>This gives you the benefits of easy to use langauges (e.g. Python), which many people use for prototyping phase. However, you don't have to rewrite the whole program later once you're done with prototyping using an efficient language (e.g. C++ or perhaps C#), because F# is both "easy to use" and "efficient" and you can fluently switch between these two styles.</p> <p>(*) I also use this style in my <a href="http://manning.com/petricek/" rel="noreferrer">functional programming book</a>.</p>
<p>One of the great advantages of functional languages is the fact they they can run on multi-processor or multi-core systems, in parallel without requiring you to change any code. That means you can speed up your algorithms by simply adding cores.</p>
49,755
<p>Say I have 2 tables: Customers and Orders. A Customer can have many Orders.</p> <p>Now, I need to show any Customers with his latest Order. This means if a Customer has more than one Orders, show only the Order with the latest Entry Time.</p> <p>This is how far I managed on my own:</p> <pre><code>SELECT a.*, b.Id FROM Customer a INNER JOIN Order b ON b.CustomerID = a.Id ORDER BY b.EntryTime DESC </code></pre> <p>This of course returns all Customers with one or more Orders, showing the latest Order first for each Customer, which is not what I wanted. My mind was stuck in a rut at this point, so I hope someone can point me in the right direction.</p> <p>For some reason, I <i>think</i> I need to use the MAX syntax somewhere, but it just escapes me right now.</p> <p><b>UPDATE:</b> After going through a few answers here (there's a lot!), I realized I made a mistake: I meant <b>any</b> Customer with his latest record. That means if he does not have an Order, then I do not need to list him. </p> <p><b>UPDATE2:</b> Fixed my own SQL statement, which probably caused no end of confusion to others.</p>
<p>I don't think you do want to use MAX() as you don't want to group the OrderID. What you need is an ordered sub query with a SELECT TOP 1.</p> <pre><code>select * from Customers inner join Orders on Customers.CustomerID = Orders.CustomerID and OrderID = ( SELECT TOP 1 subOrders.OrderID FROM Orders subOrders WHERE subOrders.CustomerID = Orders.CustomerID ORDER BY subOrders.OrderDate DESC ) </code></pre>
<p>Something like:</p> <pre><code>SELECT a.* FROM Customer a INNER JOIN Order b ON a.OrderID = b.Id INNER JOIN (SELECT Id, max(EntryTime) as EntryTime FROM Order b GROUP BY Id) met ON b.EntryTime = met.EntryTime and b.Id = met.Id </code></pre>
42,931
<p>I open a connection like this:</p> <pre><code>Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using </code></pre> <p>If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed.</p> <p>Is there any way of knowing <strong>programmatically</strong> <em>if</em> connection pooling is enabled or not? and the number of used and unused connections currently open in the pool?</p> <p><strong>EDIT:</strong> I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.</p>
<p>MSDN as <a href="http://msdn.microsoft.com/en-us/library/ms810829.aspx" rel="nofollow noreferrer">in-depth guidelines on this</a></p> <blockquote> <p><strong>Configuring Connection Pooling from the Data Source Administrator</strong></p> <p>[snip]</p> <p>Alternatively, you can start the ODBC Data Source Administrator at the Run prompt. On the taskbar, <strong>click Start, click Run, and then type Odbcad32.</strong></p> <p>The tab for managing connection pooling is found in the ODBC Data Source Administrator dialog box in version ODBC 3.5 and later. Configuring Connection Pooling from the Registry</p> <p>For versions prior to version 3.5 of the ODBC core components, you need to modify the registry directly to control the connection pooling CPTimeout value.</p> </blockquote> <p>Pooling is always handled by data server software. The whole point being is that in .NET you shouldn't have to worry about it (for example, this is why you should always use the SqlConnection when working with SQL Server - part of it is that it enables the connection pooling).</p> <h2>Update</h2> <p>On Vista, just type &quot;ODBC&quot; in the Start menu and it will find the app for you.</p> <h2>Update Following Clarification from OP</h2> <p>In terms of determining if connection pooling is enabled on each machine, looking at the <a href="http://msdn.microsoft.com/en-us/library/ms810829.aspx" rel="nofollow noreferrer">MSDN guidelines</a> I whould say you would best best if you check the registry values (See <a href="http://www.csharphelp.com/archives2/archive430.html" rel="nofollow noreferrer">this article</a> for pointers on registry access).</p> <p>TBH though, unless the client machines are really crappy, I would possibly not even bother.. AFAIK it is enabled by default, and opening connections on a client machine (in my experience) has never been a big deal. It only really becomes a big deal when <em>lots</em> are being opened.</p>
<p>To determine the number of open connections on each db, try this sql - I got it from a document on internet</p> <pre><code>select db_name(dbid) , count(*) 'connections count' from master..sysprocesses where spid &gt; 50 and spid @@spid group by db_name(dbid) order by count(*) desc </code></pre> <p>Spids &lt;=50 are used by sqlserver. So the above sql would tell you the connection used by your programs.</p>
15,265
<p><em>It is a messy question, hopefully you can figure out what I want :)</em></p> <p><strong>What is the best way to use Win32 functionality in a Qt Open Source Edition project?</strong></p> <p>Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenient and cumbersome. </p> <p>So, should I separate the Win32 stuff into a library or is there a sensible way of combining these two? Or have I just overlooked some Qt aspect that simplifies this?</p> <p><strong>EDIT</strong></p> <p>Removed the syntax stuff, its not really relevant, just annoying.</p>
<p>You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide the platform specific data in a private implementation. Trolltech has typically employed the <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="nofollow noreferrer">pimpl idiom</a> to accomplish such tasks. So, take a look at the Qt source code to see examples (i.e. look for the "d" pointers).</p>
<p>LPCWSTR should not be a problem; that's just a stupid name for <code>wchar_t const*</code>. LPARAM is not a problem either, you can store them in a long. Sure, those are just C++ types, not Qt. But Qt can still handle them.</p> <p>VS integration, as I understand it is related to the Visual Studio IDE, not the (V)C++ language.</p>
48,011
<p>I have checked with the <a href="http://en.wikipedia.org/wiki/Facade_pattern" rel="noreferrer">wikipedia article</a>, and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?</p>
<p><strong>Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.</strong></p> <p>An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified high-level interface) who then begins on a sequence of actions (turns the key, changes gears, presses the accelerator, etc...) to perform the task. He abstracts away the complexity of underlying subsystems (gearbox, engine, etc.) so that you don't have to worry about them. The driver also decouples you from the actual vehicle used... you do not directly interface with the car. You could potentially give him a Merc but your interface to the Driver would still be TakeMeTo( X ).. you're not tied down to any specific model/make of the car.</p> <p>In a real world example, you'll find facades where you interface with third party components or libraries. You don't want your code to depend on a specific vendor, so you introduce a facade interface to decouple. Also you'll simplify this interface, e.g. your facade interface would have a method called SendData( string ) but internally the implementation may call n methods on m sub-packages in a specific order to get the task done. This is what the diagram on the wikipedia page shows.</p> <p>e.g. Translating <a href="http://www.theperlreview.com/Articles/v0i4/facade.pdf" rel="noreferrer">an example</a> to C++ and keeping it tiny</p> <pre><code>sResource = LWCPPSimple::get("http://www.perl.org") </code></pre> <p>Here the fictitious Library For WWW in C++ is a facade that unifies protocol, network and parsing aspects of the problem so that I can concentrate on my primary focus of fetching the resource. The get method hides/encapsulates/keeps-in-one-place the complexity (and in some cases ugliness) of HTTP, FTP and other varied protocols, request-response, connection management, etc. Also if tomorrow the creators of LWCPPSimple find a way to make get() to be twice as fast, I get the performance benefits for free. My client code doesn't have to change.</p>
<pre><code>class A { private B b; // Class A uses Class B, the "interface" public int f() { return b.g(); } }; class B { private C c; // class B uses class C, a "subsystem" private ... ...; // other subsystems can be added public int g() { c.h(); return c.i(); } }; class C { // a subsystem public void h() { ... } public int i() { return x; } }; </code></pre> <p>Class A will not directly use any methods or directly affect the state of class C or any other subsystem that class B contains. Only one subsystem is shown here because it doesn't matter how many subsystems there are.</p>
31,034
<p>I have a column that has fields such as C5, C6, C3, CC, CA, CD, etc. </p> <p>I want to be able to find all the columns that have a letter and then a number such as C5 and C6.</p> <p>I know if I do:</p> <pre><code>SELECT * FROM TABLE WHERE FIELD LIKE 'C%' </code></pre> <p>It will return CC,CA,CD as well, but I don't want that, I want to just return the ones numbers. I also want to update this column deleting the number, so C5 becomes C and C6 becomes C and so on.</p>
<p>The query would be <code>SELECT * FROM TABLE WHERE FIELD LIKE 'C[0-9]%'</code> </p>
<p>Use any of these</p> <pre><code>select LEFT(col,1) from @t where col like 'c[0-9]%' select substring(col,1,1) from @t where col like 'c[0-9]%' </code></pre>
49,983
<p>A have the document with 23 figures and 46 tables (appendix to journal article). There are 23 sections created in the exactly same manner. When viewing compiled dvi everything is in order, but after creating ps file from the dvi one of the section title is missing. Producing pdf from dvi doesn't help. What may be the problem? I can give source file if necessary.</p>
<p><a href="http://sectools.org/web-scanners.html" rel="noreferrer">Top 10 Web Vulnerability Scanners</a> from Insecure.org (listing from 2006). Their number one, Nikto2, can be found <a href="http://www.cirt.net/nikto2" rel="noreferrer">here</a>.</p>
<p>I'm a little late to the party, but since you specifically asked for easy to use and not-too-technical scanners, take a look at <a href="https://www.golemtechnologies.com" rel="nofollow">Golem Technologies website security scanner</a> - the full scan isn't free, but they have a demo scan which checks about 10% of a site and will catch a lot of the common vulnerabilities.</p>
44,102
<p>I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key.</p> <p>I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark.</p> <p>My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication.</p> <p>What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way?</p>
<p>When dealing with indexes, you have to determine what your table is going to be used for. If you are primarily inserting 1000 rows a second and not doing any querying, then a clustered index is a hit to performance. If you are doing 1000 queries a second, then not having an index will lead to very bad performance. The best thing to do when trying to tune queries/indexes is to use the Query Plan Analyzer and SQL Profiler in SQL Server. This will show you where you are running into costly table scans or other performance blockers.</p> <p>As for the GUID vs ID argument, you can find people online that swear by both. I have always been taught to use GUIDs unless I have a really good reason not to. Jeff has a good post that talks about the reasons for using GUIDs: <a href="https://blog.codinghorror.com/primary-keys-ids-versus-guids/" rel="noreferrer">https://blog.codinghorror.com/primary-keys-ids-versus-guids/</a>.</p> <p>As with most anything development related, if you are looking to improve performance there is not one, single right answer. It really depends on what you are trying to accomplish and how you are implementing the solution. The only true answer is to test, test, and test again against performance metrics to ensure that you are meeting your goals.</p> <p>[Edit] @Matt, after doing some more research on the GUID/ID debate I came across this post. Like I mentioned before, there is not a true right or wrong answer. It depends on your specific implementation needs. But these are some pretty valid reasons to use GUIDs as the primary key:</p> <blockquote> <p>For example, there is an issue known as a &quot;hotspot&quot;, where certain pages of data in a table are under relatively high currency contention. Basically, what happens is most of the traffic on a table (and hence page-level locks) occurs on a small area of the table, towards the end. New records will always go to this hotspot, because IDENTITY is a sequential number generator. These inserts are troublesome because they require Exlusive page lock on the page they are added to (the hotspot). This effectively serializes all inserts to a table thanks to the page locking mechanism. NewID() on the other hand does not suffer from hotspots. Values generated using the NewID() function are only sequential for short bursts of inserts (where the function is being called very quickly, such as during a multi-row insert), which causes the inserted rows to spread randomly throughout the table's data pages instead of all at the end - thus eliminating a hotspot from inserts.</p> <p>Also, because the inserts are randomly distributed, the chance of page splits is greatly reduced. While a page split here and there isnt too bad, the effects do add up quickly. With IDENTITY, page Fill Factor is pretty useless as a tuning mechanism and might as well be set to 100% - rows will never be inserted in any page but the last one. With NewID(), you can actually make use of Fill Factor as a performance-enabling tool. You can set Fill Factor to a level that approximates estimated volume growth between index rebuilds, and then schedule the rebuilds during off-peak hours using dbcc reindex. This effectively delays the performance hits of page splits until off-peak times.</p> <p>If you even <em>think</em> you might need to enable replication for the table in question - then you might as well make the PK a uniqueidentifier and flag the guid field as ROWGUIDCOL. Replication will require a uniquely valued guid field with this attribute, and it will add one if none exists. If a suitable field exists, then it will just use the one thats there.</p> <p>Yet another huge benefit for using GUIDs for PKs is the fact that the value is indeed guaranteed unique - not just among all values generated by <em>this</em> server, but all values generated by <em>all</em> computers - whether it be your db server, web server, app server, or client machine. Pretty much every modern language has the capability of generating a valid guid now - in .NET you can use System.Guid.NewGuid. This is VERY handy when dealing with cached master-detail datasets in particular. You dont have to employ crazy temporary keying schemes just to relate your records together before they are committed. You just fetch a perfectly valid new Guid from the operating system for each new record's permanent key value at the time the record is created.</p> <p><a href="http://forums.asp.net/t/264350.aspx" rel="noreferrer">http://forums.asp.net/t/264350.aspx</a></p> </blockquote>
<p>I too have always heard having an auto-incrementing int is good for performance even if you don't actually use it.</p>
2,746
<p>When you use the WebBrowser control in .NET you can "embed" an instance of IE in your application, essentially making your own IE-based Web Browser.</p> <p>Does anyone know how to make any new windows created (like when the user selects "Open in New Window" from the context menu) open up in another Window of Your Web Browser Application, instead of the computers default browser??</p>
<p>Maybe the Source Code from this CodeProject article can help:</p> <p><a href="http://www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx" rel="noreferrer">Extended .NET 2.0 WebBrowser Control</a></p>
<p>There's a code sample here that contains code for adding the NewWindow2 event to the WebBrowser control. It sure would be nice if they added this event to the WebBrowser control itself.</p> <p><a href="http://zerosandtheone.com/media/p/277.aspx" rel="nofollow noreferrer">http://zerosandtheone.com/media/p/277.aspx</a></p>
14,387
<p>I am using msbuild to build a C++ project and I want to suppress the 'Post-Build Event'. I have tried the following properties with no success:</p> <pre><code>/property:PostBuildEvent= /property:VCPostBuildEventTool= </code></pre> <p>Neither will make any difference and the post build events are still executed.</p> <p>Does anyone know how to suppress these (and potentially other) events using msbuild?</p>
<p>I just figured out how to do this. There's 2 steps involved:</p> <p>First, if you're not starting the msbuild process using a batch file already, create a batch file that calls the msbuild process. Then add a variable in the batch file before you call the msbuild process. Something like this:</p> <pre><code>set ISFULLBUILD=True msbuild TFSBuild.proj &gt;&gt; BuildOutput.txt </code></pre> <p>Then, you need to modify your post build event to only do something if the variable is not set, or has the wrong value:</p> <pre><code>IF NOT '%ISFULLBUILD%'=='True' copy /y $(TargetFileName) "..\..\..\..\..\..\Binaries\$(ConfigurationName)\" </code></pre> <p>In this case - the TargetFileName (Whatever.dll) will only get copied when you're building from Visual Studio. But, when you build using your new batch file - it will NOT execute the command after the IF statement.</p>
<p>Have you tried setting the build event to something other than blank? If you overwrite it with something superfluous, like a "dir" or something, does it still execute the original post-build steps?</p> <p>It's not the most elegant solution, but it might work.</p>
33,174
<p>In java, does <code>file.delete()</code> return <code>true</code> or <code>false</code> where <code>File file</code> refers to a non-existent file?</p> <p>I realize this is kind of a basic question, and easy to very through test, but I'm getting strange results and would appreciate confirmation.</p>
<p>Doesn't that result in a FileNotFoundException?</p> <p>EDIT:</p> <p>Indeed it does result in false:</p> <pre><code>import java.io.File; public class FileDoesNotExistTest { public static void main( String[] args ) { final boolean result = new File( "test" ).delete(); System.out.println( "result: |" + result + "|" ); } } </code></pre> <p>prints <code>false</code></p>
<p>The official javadoc:</p> <pre><code>Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns: true if and only if the file or directory is successfully deleted; false otherwise Throws: SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file </code></pre> <p>so, false.</p>
39,651
<p>I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.</p> <p>I recently used a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">Maven structure</a> for a java project, but I am not sure it's the best structure for a non-maven driven project.</p> <p>So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. </p> <p>As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public_html ?</p>
<p>After a couple years working with different structures I recently found a structure that hols most variations for me:</p> <pre><code>/project_name (everything goes here) /web (htdocs) /img /css /app (usually some framework or sensitive code) /lib (externa libs) /vendor_1 /vendor_2 /tmp /cache /sql (sql scripts usually with maybe diagrams) /scripts /doc (usually an empty directory) </code></pre>
<p>I just found a interesting document about Directory structures on Zend website:<br> <a href="http://framework.zend.com/wiki/display/ZFDEV/Choosing+Your+Application%27s+Directory+Layout" rel="nofollow noreferrer">http://framework.zend.com/wiki/display/ZFDEV/Choosing+Your+Application%27s+Directory+Layout</a></p>
8,609
<p>I am considering converting a project that I've inherited from .net 1.1 to .net 2.0. The main warning I'm concerned about is that it wants me to switch from <code>System.Web.Mail</code> to using <code>System.Net.Mail</code>.</p> <p>I'm not ready to re-write all the components using the obsolete <code>System.Web.Mail</code>, so I'm curious to hear if any community members have had problems using it under .net 2.0?</p>
<p>System.Web.Mail is not a full .NET native implementation of the SMTP protocol. Instead, it uses the pre-existing COM functionality in CDONTS. System.Net.Mail, in contrast, is a fully managed implementation of an SMTP client.</p> <p>I've had far fewer problems with System.Net.Mail as it avoids COM hell.</p>
<p>Yes, we had the same issue, and we decided not to upgrade either. We haven't seen any problems, so you're OK ignoring the warnings.</p>
9,017
<p>Has anyone used the <a href="http://www.cs.tufts.edu/~nr/noweb/" rel="noreferrer">noweb</a> literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?</p>
<p>Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use * at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.</p> <pre><code>&lt;&lt;/path/to/file.java&gt;&gt;= reallyImportantVariable += 1; @ %def reallyImportantVariable </code></pre> <p>noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.</p> <p>I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.</p>
<p>Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors. This usually means pre processor support, which Java doesn't support.</p> <p>Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present. The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.</p> <p>To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).</p> <p>Any particular reason you are considering it?</p>
18,353
<p>I researched this a while ago and can't remember how to do it. I want to be able to prevent Firefox from running it's spell-checking functionality on certain input fields from within the page. I know it's possible but can't remember how to set it up.</p>
<p>Talk about having a big "duh" moment! I found the answer after some trial &amp; error:</p> <pre><code>&lt;textarea spellcheck="false"&gt;&lt;/textarea&gt; </code></pre>
<p>The downside of this is that the W3 strict validator gives - Attribute "spellcheck" is not a valid attribute. Bad news for those of us with OCD that love to see 0 errors in validating our sites.</p>
27,659
<p>Is there a (portable) way to rotate text in a HTML table cell by 90°?</p> <p>(I have a table with many columns and much text for the headings, so I'd like to write it vertically to save space.)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.box_rotate { -moz-transform: rotate(7.5deg); /* FF3.5+ */ -o-transform: rotate(7.5deg); /* Opera 10.5 */ -webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */ filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */ -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt; &lt;div class="box_rotate"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;</code></pre> </div> </div> </p> <p>Taken from <a href="http://css3please.com/" rel="nofollow noreferrer">http://css3please.com/</a></p> <p>As of 2017, the aforementioned site has simplified the rule set to drop legacy Internet Explorer filter and rely more in the now standard <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform" rel="nofollow noreferrer"><code>transform</code> property</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.box_rotate { -webkit-transform: rotate(7.5deg); /* Chrome, Opera 15+, Safari 3.1+ */ -ms-transform: rotate(7.5deg); /* IE 9 */ transform: rotate(7.5deg); /* Firefox 16+, IE 10+, Opera */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt; &lt;div class="box_rotate"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;</code></pre> </div> </div> </p>
<pre class="lang-css prettyprint-override"><code>-moz-transform: rotate(7.5deg); /* FF3.5+ */ -o-transform: rotate(7.5deg); /* Opera 10.5 */ -webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */ filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); /* IE6,IE7 allows only 1, 2, 3 */ -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; /* IE8 allows only 1 2 or 3*/ </code></pre>
34,352
<p>Consider the following code:</p> <pre><code>Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak() </code></pre> <p>How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?</p>
<p>You don't; the subclass's method overrides the superclass's method, by definition of inheritance.</p> <p>If you want the overridden method to be available, expose it in the subclass, e.g.</p> <pre><code>Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function Public Function SpeakAsAnimal() As String Return MyBase.Speak() End Function End Class </code></pre>
<p>I don't think you can. </p> <p>The thing is that the object is still a dog. the behavior you're describing (getting "ruff" from the casted object rather than "hello") is standard because you want to be able to use the animal class to let a bunch of different type of animals speak.</p> <p>For example, if you had a third class as thus:</p> <pre><code>Public Class Cat Inherits Animal Public Overrides Function Speak() As String Return "Meow" End Function End Class </code></pre> <p>Then you'd be able to access them like thus:</p> <pre><code>protected sub Something Dim oCat as New Cat Dim oDog as New Dog MakeSpeak(oCat) MakeSpeak(oDog) End sub protected sub MakeSpeak(ani as animal) Console.WriteLine(ani.Speak()) end sub </code></pre> <p>What you're talking about doing basically breaks the inheritance chain. Now, this can be done, by setting up the <strong>Speak</strong> function to accept a parameter which tells it to return it's base value or not or a separate SPEAK function for the base value, but out of the box, you're not going to get things that behave this way.</p>
30,375
<p>I've been reading about thread-safe singleton patterns here:</p> <p><a href="http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29</a></p> <p>And it says at the bottom that the only safe way is to use pthread_once - which isn't available on Windows.</p> <p>Is that the <strong>only</strong> way of guaranteeing thread safe initialisation?</p> <p>I've read this thread on SO:</p> <p><a href="https://stackoverflow.com/questions/6915/thread-safe-lazy-contruction-of-a-singleton-in-c">Thread safe lazy construction of a singleton in C++</a></p> <p>And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms683568.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms683568.aspx</a></p> <p>Can this do what I want?</p> <p><strong>Edit:</strong> I would like lazy initialisation and for there to only ever be one instance of the class.</p> <p>Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"?</p> <p><strong>Accepted Answer:</strong><br> I've accepted <a href="https://stackoverflow.com/questions/164496/how-can-i-create-a-thread-safe-singleton-pattern-in-windows#164640">Josh's answer</a> as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!!</p> <p><strong>Edit:</strong> <strong>The code works fine except the return statement - I get an error: error C2440: 'return' : cannot convert from 'volatile Singleton *' to 'Singleton *'. Should I modify the return value to be volatile Singleton *?</strong></p> <p><strong>Edit:</strong> Apparently const_cast&lt;> will remove the volatile qualifier. Thanks again to Josh.</p>
<p>If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "<a href="http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Microsoft_Visual_C.2B.2B" rel="noreferrer">volatile variables behave as fences</a>". This is the most efficient way to implement a lazy-initialized singleton.</p> <p>From <a href="http://msdn.microsoft.com/en-us/magazine/cc163405.aspx" rel="noreferrer">MSDN Magazine:</a></p> <pre><code>Singleton* GetSingleton() { volatile static Singleton* pSingleton = 0; if (pSingleton == NULL) { EnterCriticalSection(&amp;cs); if (pSingleton == NULL) { try { pSingleton = new Singleton(); } catch (...) { // Something went wrong. } } LeaveCriticalSection(&amp;cs); } return const_cast&lt;Singleton*&gt;(pSingleton); } </code></pre> <p>Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer.</p> <p><em>DO NOT</em> use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible.</p> <p>You'll have to declare and <a href="http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx" rel="noreferrer">initialize the CRITICAL SECTION</a> elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.</p>
<p>There are many ways to do thread safe Singleton* initialization on windows. In fact some of them are even cross-platform. In the SO thread that you linked to, they were looking for a Singleton that is lazily constructed in C, which is a bit more specific, and can be a bit trickier to do right, given the intricacies of the memory model you are working under.</p> <ul> <li>which you should never use</li> </ul>
19,888
<p>I have multiple processes monitoring an MSMQ queue. I want to do multi-step operations like first peek the message and then based on some criteria receive the message. A single message may pass the receiving criteria of multiple processes so that more than one process may try to receive the same message. Will these operations be thread safe? If not what should I do to prevent one process from failing to receive the message that other process has already received?</p>
<p>The operations themselves are thread safe. However, if you perform a multi-step operation you may find that the results are not consistent (for example, peeking to see if data is in the queue, then calling to receive the data, only to discover it's not there any longer).</p>
<p>You may be interested in a <a href="http://msmq.spaces.live.com/blog/cns!393534E869CE55B7!293.entry" rel="noreferrer">blog entry</a> I wrote on this subject.</p> <p>In short, MSMQ C++ API is thread safe, but not all System.Messaging methods are thread safe. In the blog entry I discuss how to call MessageQueue.Send in a thread-safe way.</p>
27,756
<p>What are the best places to find out everything there is to know about Domain-Driven Design, from beginner to advanced.</p> <ul> <li>Books </li> <li>Websites </li> <li>Mailing lists </li> <li>User groups</li> <li>Conferences</li> <li>etc</li> </ul>
<p>Here are some interesting sources:</p> <ul> <li>the <a href="http://dddcommunity.org/books/index.html#DDD" rel="noreferrer">DDD</a> book by Eric Evans</li> <li>the free <a href="http://dddcommunity.org/books/index.html#DDD_quickly" rel="noreferrer">DDD Quickly</a> book</li> <li>the <a href="http://groups.yahoo.com/group/domaindrivendesign/" rel="noreferrer">DDD newsgroup</a></li> </ul>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321268202" rel="nofollow noreferrer" rel="nofollow noreferrer">Applying Domain-Driven Design and Patterns</a> is a very good book on the subject. Lots of good examples as well as discussion of related subjects like test driven development and how they apply.</p> <p>Also check out <a href="http://domaindrivendesign.org/" rel="nofollow noreferrer">domaindrivendesign.org</a>.</p>
15,067
<p>Say I have:</p> <pre><code>&lt;ul&gt; &lt;li id="x"&gt; &lt;a href="x"&gt;x&lt;/a&gt; &lt;/li&gt; &lt;li id="y"&gt; &lt;a href="y"&gt;y&lt;/a&gt; &lt;ul&gt; &lt;li id="z"&gt; &lt;a href="z"&gt;z&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.</p> <p>Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?</p> <p>Thanks!</p>
<p>I would use XSLT. You can specify to search for nodes that are ancestors of z .</p>
<p>I suggest you parse it into a DOM and recurse backwards like you were thinking. Regular expressions don't work very well for nested structures with arbitrary nesting levels.</p>
8,110
<p>Is an opensource/commercial tool/framework, available for automated web app testing in Google Chrome browser on Windows XP / Vista? ( An alpha/beta Tool is also OK)</p> <p>Thanks</p>
<p>Selenium supports Chrome pretty much out of the box because it works by injecting javascript in the web page. <a href="http://selenium-rc.openqa.org/" rel="nofollow noreferrer">http://selenium-rc.openqa.org/</a></p> <p>Webdriver has an early version of Chrome driver. <a href="http://code.google.com/p/webdriver/" rel="nofollow noreferrer">http://code.google.com/p/webdriver/</a></p> <p>Both are open source and works on Windows.</p>
<p>For those who are not developers you could try <a href="https://www.frontendtest.org" rel="nofollow noreferrer">FRET</a> for automated web testing with Chrome. It's still in beta and even though it states that no programming is needed a basic understanding of HTML / CSS etc. is recommended.</p>
11,355
<p>A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me.</p> <p>What are the most common scenarios you have found where you need to clone an object?</p>
<p>I assume you are referring to <code>Object.clone()</code> in Java. If yes, be advised that <code>Object.clone()</code> has some major problems, and its use is discouraged in most cases. Please see Item 11, from <a href="http://java.sun.com/docs/books/effective/" rel="noreferrer">"Effective Java"</a> by Joshua Bloch for a complete answer. I believe you can safely use <code>Object.clone()</code> on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.</p>
<p>I have used Object.clone() in a Spring webflow application to check what has changed when a user edits / enters data on a form for auditing purposes.</p> <p>At the beginning of the flow, I call the clone method which was implemented on the form backing object used in the spring webflow and save the instance of the clone to the user session. Once the user has completed editing data on the html form and pressed the save button I compare the new values bound to the backing object to the cloned value to determine what data the user has changed.</p> <p>This worked well and was really easy to implement, I haven't really experienced any issues with cloning in Java.</p>
33,976
<p>I've been testing out <a href="http://www.automatedqa.com/products/aqtime/" rel="noreferrer">the performance and memory profiler AQTime</a> to see if it's worthwhile spending those big $$$ for it for my Delphi application. </p> <p>What amazes me is how it can give you source line level performance tracing (which includes the number of times each line was executed and the amount of time that line took) without modifying the application's source code and without adding an inordinate amount of time to the debug run.</p> <p>The way that they do this so efficiently makes me think there might be some techniques/technologies used here that I don't know about that would be useful to know about.</p> <p>Do you know what kind of methods they use to capture the execution line-by-line without code changes? </p> <p>Are there other profiling tools that also do non-invasive line-by-line checking and if so, do they use the same techniques?</p>
<p>This is just speculation, but perhaps AQtime is based on a technology that is similar to <a href="http://research.microsoft.com/sn/detours/" rel="noreferrer">Microsoft Detours</a>? </p> <blockquote> <p>Detours is a library for instrumenting arbitrary Win32 functions on x86, x64, and IA64 machines. Detours intercepts Win32 functions by re-writing the in-memory code for target functions.</p> </blockquote>
<p>I don't know about Delphi in particular, but a C application debugger can do line-by-line profiling relatively easily - it can load the code and associate every code path with a block of code. Then it can break on all the conditional jump instructions and just watch and see what code path is taken. Debuggers like gdb can operate relatively efficiently because they work through the kernel and don't modify the code, they just get informed when each line is executed. If something causes the block to be exited early (longjmp), the debugger can hook that and figure out how far it got into the blocks when it happened and increment only those lines.</p> <p>Of course, it would still be tough to code, but when I say easily I mean that you could do it without wasting time breaking on each and every instruction to update a counter.</p>
41,724
<p>I have been asked to develop some usercontrols in ASP.NET that will at a later point be pulled into a SharePoint site as web parts. I am new to SharePoint and will not have access to a SharePoint server during the time I need to prototype these parts.</p> <p>Does anyone know of any reasons that this approach will not work? If this approach is not recommended, what would other options be? Any suggestions on a resource/tutorial on what to consider when developing an ASP.NET web part with SharePoint in mind?</p> <p>Thanks</p> <p><strong>Edit: 12/31/2008</strong> I finally marked an answer to this one. It took me a while to realize that going the SharePoint route right away, though painful at first, is the best way to go about it. The free VPC image makes getting set up to develop relatively painless. </p> <p>While you can, as I did, develop web parts in ASP.NET without SharePoint, when it comes to developing and deploying SharePoint applications you haven't learned a thing, only pushed the learning curve off into a time when you think you are done, (and have probably informed stakeholders to that effect). To delay the SharePoint learning curve doesn't do you or your project any favors, and your final product will better for the expertise you gain along the way.</p>
<p>If it's a very short-term thing, Microsoft has a time-limited WSS evaluation VPC image:</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=1beeac6f-2ea1-4769-9948-74a74bd604fa&amp;displaylang=en&amp;tm" rel="nofollow noreferrer">WSS3 SP1 Developer Evaluation VPC image</a></p> <p>That will get you started if you don't have time/resources to set up your own VPC image right now.</p>
<p>you need to have access to a sharepoint server because you can't simulate your webpart without it, you have to deploy it to your sharepoint site to test if it's working. debugging would also be a pain. or you can use SmartPart, it's a webpart that acts like a wrapper for your user controls to display in a sharepoint site.</p>
16,141
<p>I have almost the worst spec in the world. An application that exists and used to work. My aim is to recreate this app and make it work. </p> <p>It's a <em>very</em> simple util that just displays the following information to screen:</p> <ul> <li>ARFCN - Absolute Radio Frequency Channel Number</li> <li>LAC - Location Area Code of the cell (unique in PLMN)</li> <li>RAC - Routing Area Identifier Code of the cell (unique in PLMN)</li> <li>MNC / MCC - Mobile Network Code / Mobile Country Code</li> <li>NCellInfo1-6 - ?</li> <li>Rx Quality - </li> <li>Frequency Hopping -</li> <li>Last registered network</li> <li>TMSI - ?</li> <li>Periodic Location Update value</li> <li>Band</li> <li>Channel in use</li> <li>RSSI 1 - received signal strength indication</li> <li>Last call release cause</li> </ul> <p>I'm hoping I can gain some of this information via OpenNETCF's network information, maybe some P/Invokes somewhere or (worst case scenario) some kind of custom SDK that i'll need to find for the device (and its a niche device so I hope this isn't the case).</p> <p>However wishing to utilise the powers of Stackoverflow I wondered if someone would be able to point me in the right direction to get this data off a device. Anyone know of any libs that specifically provide this kind of information?</p>
<p>OpenNETCF's NetworkInformation namespace is not going to help - it's a wrapper around NDIS and WZC, which is not of much use for telephony. What is probebly relevent here is the <a href="http://msdn.microsoft.com/en-us/library/aa450239.aspx" rel="nofollow noreferrer">Telephony API (TAPI)</a>, though I have doubts whether even TAPI is going to give all of this info (it's been a while since I fought with TAPI).</p> <p>My guess is that you'll be able to get some of the info through TAPI, but a lot of it i probably retrieved through a proprietary API that the radio vendor provides, and without info on that API (from the radio vendor or the device OEM) you're probably out of luck.</p>
<p>OpenNETCF's NetworkInformation namespace is not going to help - it's a wrapper around NDIS and WZC, which is not of much use for telephony. What is probebly relevent here is the <a href="http://msdn.microsoft.com/en-us/library/aa450239.aspx" rel="nofollow noreferrer">Telephony API (TAPI)</a>, though I have doubts whether even TAPI is going to give all of this info (it's been a while since I fought with TAPI).</p> <p>My guess is that you'll be able to get some of the info through TAPI, but a lot of it i probably retrieved through a proprietary API that the radio vendor provides, and without info on that API (from the radio vendor or the device OEM) you're probably out of luck.</p>
34,392
<p>I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process?</p>
<p>If the pieces of data are independant then treat the pieces of data as work items to be processed by a pool of threads. Use the thread pool and <code>QueueUserWorkItem</code> to post the data to the thread(s). You should get better scalability using a pool of symmetric threads and limiting the amount of synchronisation that has to occur between the producer and consumer(s).</p> <p>For example (from <a href="http://msdn.microsoft.com/en-us/library/4yd16hza.aspx" rel="noreferrer">MSDN</a>):</p> <pre><code> TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42); // Queue the task and data. if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) { Console.WriteLine("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the ThreadPool task has a chance to run. ThreadPool uses // background threads, which do not keep the application // running. (This is a simple example of a race condition.) Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } else { Console.WriteLine("Unable to queue ThreadPool request."); } // The thread procedure performs the independent task, in this case // formatting and printing a very simple report. // static void ThreadProc(Object stateInfo) { TaskInfo ti = (TaskInfo) stateInfo; Console.WriteLine(ti.Boilerplate, ti.Value); } </code></pre>
<p>Does the "store in the DB" thread always need to be running? It seems like perhaps the best option (if possible) would be to have the polling thread spin up another thread to do the save. Depending on the number of threads being created though, it could be that having the first polling thread use ThreadPool.QueueUserWorkItem() might be the more efficient route. </p> <p>For more efficiency, when saving to the database, I would use async I/O on the DB rather than the sync methods. </p> <p>Anytime you can get away from having to communicate directly between two threads, you should. Having to throw together some sync primitives, your code won't be as easy to debug and could introduce some very subtle race conditions that cause "once in a million execution" type bugs (which are far from fun to find/fix). </p> <p>If the second thread always needs to be executing, let us know why with some more information and we can come back with a more in-depth answer.</p> <p>Good luck!</p>
13,255
<p>e.g, Is the user playing a movie full screen, or looking at powerpoint in full screen mode?</p> <p>I could have sworn I saw a IsFullScreenInteractive API before, but can't find it now</p>
<p>Here's how I've solved this problem:</p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; namespace Test { class Program { static void Main(string[] args) { Console.WriteLine(IsForegroundWwindowFullScreen()); } [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetSystemMetrics(int smIndex); public const int SM_CXSCREEN = 0; public const int SM_CYSCREEN = 1; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowRect(IntPtr hWnd, out W32RECT lpRect); [StructLayout(LayoutKind.Sequential)] public struct W32RECT { public int Left; public int Top; public int Right; public int Bottom; } public static bool IsForegroundWwindowFullScreen() { int scrX = GetSystemMetrics(SM_CXSCREEN), scrY = GetSystemMetrics(SM_CYSCREEN); IntPtr handle = GetForegroundWindow(); if (handle == IntPtr.Zero) return false; W32RECT wRect; if (!GetWindowRect(handle, out wRect)) return false; return scrX == (wRect.Right - wRect.Left) &amp;&amp; scrY == (wRect.Bottom - wRect.Top); } } } </code></pre>
<p>The preferred way of detecting the state of a window is by calling <a href="http://msdn.microsoft.com/en-us/library/ms633518(VS.85).aspx" rel="nofollow noreferrer">GetWindowPlacement</a>. If you do that in conjunction with GetForegroundWindow, you can easily check if the user sees a fullscreen window or not.</p>
24,782
<p>Similar to <a href="https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p> <p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p> <p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p> <p>The struct package seems to be what I want, but I can't get it to work.</p> <p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p> <pre><code>def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] </code></pre> <p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
<p>If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:</p> <pre><code>&gt;&gt;&gt; s = '\0\x02' &gt;&gt;&gt; struct.unpack('&gt;H', s) (2,) </code></pre> <p>Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.</p> <p>For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details.</p> <p>You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value:</p> <pre><code>&gt;&gt;&gt; a,b,c = struct.unpack('&gt;HHi', some_string) </code></pre> <p>Going by your code, you are looking for (in order):</p> <ul> <li>a 3 char string</li> <li>2 single byte values (major and minor version)</li> <li>a 1 byte flags variable</li> <li>a 32 bit length quantity</li> </ul> <p>The format string for this would be:</p> <pre><code>ident, major, minor, flags, len = struct.unpack('&gt;3sBBBI', ten_byte_string) </code></pre>
<p>I was going to recommend the <code>struct</code> package but then you said you had tried it. Try this:</p> <pre><code>self.major_version = struct.unpack('H', self.whole_string[3:5]) </code></pre> <p>The <code>pack()</code> function convers Python data types to bits, and the <code>unpack()</code> function converts bits to Python data types.</p>
18,144
<p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p> <p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p> <p>Any suggestions how I could accomplish this?</p>
<p>Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:</p> <pre><code>import mechanize class HeadRequest(mechanize.Request): def get_method(self): return "HEAD" request = HeadRequest("http://www.example.com/") response = mechanize.urlopen(request) print response.info() </code></pre>
<p>In mechanize there is no need to do HeadRequest class etc.</p> <p>Simply</p> <pre><code> import mechanize br = mechanize.Browser() r = br.open("http://www.example.com/") print r.info() </code></pre> <p>That's all.</p>
16,639
<p>I need to, preferably in C# - but c++ will do, find a way to filter the list of printers in the windows print dialog for any windows printing.</p> <p>I have come across WinAPIOverride and have figured I am going to have to write my own dll which overrides the method to get the printers list, then filter it and return it. I would then have to inject the dll into all running processes.</p> <p>Can anybody assist me with something that is already developed or perhaps an easier way of accomplishing this? The only way the list of printers comes out is from the API method call and I have even considered modifying the registry, but this will slow down the response of the print dialog box to the point that it would be annoying to the user.</p>
<p>I don't think that (re)writing a DLL is the easiest method. Why not use <a href="http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx" rel="nofollow noreferrer">WMI</a> to retrieve the wanted <a href="http://msdn.microsoft.com/en-us/library/aa394363.aspx" rel="nofollow noreferrer">information (printers in this case)</a>?</p> <p>The following code is for retrieving all the locally installed printers:<br> (code samples borrowed from <a href="http://weblogs.asp.net/aghausman/archive/2008/12/30/get-list-of-installed-printers-using-c-wmi.aspx" rel="nofollow noreferrer">here</a>)</p> <pre><code> ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access objScope.Connect(); SelectQuery selectQuery = new SelectQuery(); selectQuery.QueryString = "Select * from win32_Printer"; ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery); ManagementObjectCollection MOC = MOS.Get(); foreach (ManagementObject mo in MOC) { listBox1.Items.Add(mo["Name"].ToString().ToUpper()); } </code></pre> <p>To get the printers known accross a domain use this: </p> <pre><code>ConnectionOptions objConnection = new ConnectionOptions(); objConnection.Username = "USERNAME"; objConnection.Password = "PASSWORD"; objConnection.Authority = "ntlmdomain:DDI"; //Where DDI is the name of my domain // Make sure the user you specified have enough permission to access the resource. ManagementScope objScope = new ManagementScope(@"\\10.0.0.4\root\cimv2",objConnection); //For the local Access objScope.Connect(); SelectQuery selectQuery = new SelectQuery(); selectQuery.QueryString = "Select * from win32_Printer"; ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery); ManagementObjectCollection MOC = MOS.Get(); foreach (ManagementObject mo in MOC) { listBox1.Items.Add(mo["Name"].ToString().ToUpper()); } </code></pre> <p>Of course, the list is not "filtered" as you would like as you didn't specify any criteria. But I'm sure you can manage from here on by yourself.</p>
<p>Thanks for the interesting code.</p> <p>The idea is to apply a filtered printer list to the system as globally as possible without interfering with the user. This means the filtered list has to apply to the standard windows print dialogs unfortunately...</p> <p>So your WMI code, albeit kind of cool, would not be appropriate. If I were building my own print dialogs, it could come in pretty handy ;)</p>
19,235
<p>I have a current system which is build as a Windows Application, and does certain tasks in very close to real time. There are nodes in a network that communicate with our custom server, communicating status, and sending and receiving commands.</p> <p>We are looking to move to a web deployed platform. The nodes, say 60-100 of them, need to communicate with the server, and display to the client quickly. I'm talking milliseconds, not seconds. The network connection is LAN/100mbit or gigabit, with a reliably fast connection from the clients to the server. The node communication is also small, and it already sent as XML messages, which are not huge in size, and not overwhelming in quantity.</p> <p>Our System Architect is confident, and assures us, that this can be done with LAMP + AJAX. I personally have been involved with similar systems before, and I'm skeptical about the guarantee delivery of messages this close to real time.</p> <p>In order to have a sanity check, am I wrong? Can this be done (well) with LAMP, or any similar language? (Not Java, I know a launched Java applet can do this).</p>
<p>If you're talking about a near-realtime application such as a messaging program and not actual realtime then it can be done. The technique is called 'long-polling' or <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow noreferrer">comet</a> and has been used successfully by several major web startups (<a href="http://www.meebo.com/" rel="nofollow noreferrer">Meebo</a> for example).</p> <p>HTML 5 specifications also include a built-in <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html" rel="nofollow noreferrer">messaging API</a> which should really propel those techniques into the mainstream as it is implemented in the next generation of browsers (and some of the current generation as well).</p>
<p>The AJAX part of this is fine. Products like Lightstreamer and other Comet (Http server push) servers can provide near real time communication.</p> <p>The LAMP part of the equation is the one that worries me. You'll probably need a custom back end of sorts in order to achieve high performance. The LA parts are fine. The needs of your application may cause you to reconsider the MP.</p>
47,149
<p>Is there a detailed guide which explains how to host a website on your own server on linux. I have currently hosted it on one of the commerical web-hosts. Also the domain is registered to a different vendor.</p> <p>Thanks</p>
<p><a href="http://gentoo-wiki.com/HOWTO_setup_a_home-server" rel="noreferrer">This guide</a> is probably more info than you really requested, but webserver information is in there. It's Gentoo-specific, but you can apply the same information with minor translations to any other distro.</p>
<p>I think it depends on how familiar you are with linux. Certainly, many people do this for hobbyist websites.</p> <p>There are many aspects involved - you should begin with something simple like getting apache running and visible to the outside world.</p>
10,817
<p>I have a web application which provides Excel files via IE 7. It requests the files with an HTTP GET from a URL which returns the data with a content type of 'application/vnd.ms-excel'. It then opens the spreadsheets in an IFrame.</p> <p>This all works fine unless Excel is already open when a spreadsheet is downloaded. In this case it is still displayed correctly but reuses the instance of Excel which is open. When the IFrame is closed, Excel hangs. Excel only becomes unlocked if the user logs out of the web application or if they download a file of a different type.</p> <p>I've tried turning on the 'Ignore other applications' setting under Tools | Options | General but it didn't solve the problem.</p> <p>I've also tried following the steps in <a href="https://stackoverflow.com/questions/213110/make-excel-2003-open-spreadsheets-in-new-instances/213187#213187">this answer</a> (as the <a href="http://www.drewery.net/blog/2006/08/29/utilising-dual-monitors-with-microsoft-excel-2003/" rel="nofollow noreferrer">linked reference</a> says 'This issue has been addressed in Excel 2007 beta 2.') with no luck.</p> <p>Is there some kind of 'disposal' step which I'm not currently doing which would prevent Excel from hanging?</p> <p>Versions:</p> <p>Excel 2003 (11.8220.8221) SP3</p> <p>IE 7.0.5730.11 (Update Versions: 0)</p>
<p>Further to <a href="https://stackoverflow.com/questions/201355/how-can-i-stop-excel-2003-from-hanging-after-opening-a-spreadsheet-in-ie/497100#497100">Robert's answer</a>, the following line of (Java) code fixes this problem, in that it prevents Excel from hanging:</p> <pre><code>response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); </code></pre> <p>[NB 'response' is an HttpServletResponse]</p> <p>However, it forces the spreadsheet to be loaded into an Excel window rather than being displayed in the IFrame...</p> <p><strong>Update:</strong> Resetting the URL of the IFrame to blank forces the Excel instance to be disposed and fixes this problem (without requiring the <code>Content-Disposition</code> change).</p>
<p>Unfortunately, this is completely out of your hands. It really depends on what version of excel they have and what updates have been applied.</p>
24,582
<p>I would like to know if there is a jQuery event that I can use to determine when a particular DIV's <code>top</code> property has changed.</p> <p>For instance, I have invisible content above a DIV. When that content becomes visible, the DIV is shifted down. I would like to capture that event and then use the <code>offset()</code> function to get the X/Y coordinates.</p>
<p>The easy answer is that there are no events in the DOM for detecting layout updates.</p> <p>You have a couple options the way I see it:</p> <ol> <li><p>Poll, nasty but it may work depending on your update frequency requirements.</p></li> <li><p>Tap into whatever event causes the invisible DIV to change size and do whatever you need to do in that handler</p></li> </ol> <hr> <p>I shall correct myself.</p> <p>I took a look at the DOM and noticed the DOMAttrModified event and found this <a href="http://www.west-wind.com/weblog/posts/478985.aspx" rel="nofollow noreferrer">JQuery Plug-In</a> that you might be able to leverage to do what you want.</p> <p>As the article mentions, it works great in IE and Firefox but seems to have problems in WebKit.</p>
<pre><code>$("#someId").resize(function () { // your code }); </code></pre>
46,263
<p>Can anyone recommend a ready-to-use class/library compatible with C/C++/MFC/ATL that would parse iCal/vCal/Google calendar files (with recurrences)? It can be free or commercial.</p>
<p>there is a <a href="http://www.phpclasses.org/browse/package/3278.html" rel="nofollow noreferrer">parser in PHP for iCal</a>, you can downloaded and check the code to suit your language.</p> <p>for vCal/vCard parsing <a href="http://sourceforge.net/projects/ccard" rel="nofollow noreferrer">there's a C Library</a>.</p> <p>for Google Calendar I couldn't find any exact answer, so, try to Google it.</p>
<p>The only problem with the CCard project is that it's a generic parser (similar to what I already have implemented myself) - what would be really valuable to me is something that "understands" all varieties of recurrences and such. Those differ between vCal and iCal as well, adding to the complexity.</p>
24,769
<p>I am running a series of JUnits using Apache ANT using JDK 1.5.</p> <p>All JUnits that use an Oracle JDBC driver give the UnsatisfiedLinkError shown below.</p> <p>What native library is it looking for and how do I solve this? What should the PATH variable contain?</p> <pre><code>java.lang.UnsatisfiedLinkError: oracle/jdbc/driver/T2CConnection.t2cGetCharSet([CI[CI[CI[CII[SLoracle/jdbc/driver/GetCharSetError;)S at oracle.jdbc.driver.T2CConnection.getCharSetIds(T2CConnection.java:2957) at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:320) at oracle.jdbc.driver.PhysicalConnection.&lt;init&gt;(PhysicalConnection.java:361) at oracle.jdbc.driver.T2CConnection.&lt;init&gt;(T2CConnection.java:142) at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:79) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:595) at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:196) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:114) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:77) at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:59) at oracle.jdbc.pool.OracleConnectionCacheImpl.getNewPoolOrXAConnection(OracleConnectionCacheImpl.java:401) at oracle.jdbc.pool.OracleConnectionCacheImpl.setMinLimit(OracleConnectionCacheImpl.java:752) </code></pre>
<p>Resolved!</p> <p>It was actually an out-of-date ojdbc14.jar file causing this issue. All I did was update it and the problem is fixed now. The classes file </p> <p>Thanks</p>
<p>Had this one, you should add classes12.jar or classes13.jar to your classpath (not sure about the name, it's been over a year, google these...)</p>
21,105
<p>Is there a way to reuse a 3rd party control reference?</p> <p>For example, I have this referenced in my App.xaml</p> <pre><code>xmlns:cust="clr-namespace:ThirdParty.Controls;assembly=ThirdParty.Controls" </code></pre> <p>I don't want to repeat this 3rd party control xml namespace on each page/control that needs a control from the library. </p> <p>Is there anyway to centralize these references and use the prefix defined here? The possibility of each control having a different prefix is also worrisome. In asp.net you would put a reference in the web.config and it was available globally, I'm just looking to see if there is a similar method in WPF.</p>
<p>Two options I am thinking </p> <p>1) Wrap that control into a UserControl and then use your UserControl in all the places.</p> <p>2) Declare the third party control as a Resource somewhere and then use DynamicResource reference to that on your other places.</p> <p>The second option can be implemented as bellow.</p> <p>Where ever you want the third party control put a ContentControl like bellow</p> <pre><code>&lt;ContentControl Template="{DynamicResource thirdPartyControlTemplate}" /&gt; </code></pre> <p>The ControlTemplate will be in the Resource file or at App.Xaml as bellow.</p> <pre><code> xmlns:thridParty="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1" &gt; &lt;Application.Resources&gt; &lt;ControlTemplate x:Key="thirdPartyControlTemplate" TargetType="{x:Type ContentControl}"&gt; &lt;thridParty:ThirdPartyControl /&gt; &lt;/ControlTemplate&gt; &lt;/Application.Resources&gt; </code></pre> <p>You can see that the namespace declaration will be always on this resource file and you will be able to use that Control control from any place</p>
<p>Take an example from the built-in control template for a Label:</p> <pre><code>&lt;ControlTemplate TargetType="Label" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; </code></pre> <p><a href="http://www.sellsbrothers.com/tools/#ShowMeTheTemplate" rel="nofollow noreferrer">Show Me The Template</a> is an amazingly helpful resource for these kinds of things. HTH</p>
39,469
<p>I'm using System.Reflection.Emit for a while now, and find it (who don't?) as painful as bug prone.</p> <p>Do you know if there is a good wrapper around the IL Generator, something that I can rely on to emit IL in a more safe and easier manner than with playing directly with SRE?</p> <p><strong>Edit:</strong></p> <p>I know that manipulating expression trees is definitively easier and safer than emitting IL directly, but they also have some constraints right now. I can't create code blocs, use loops, declare and work with several locals, etc. We need to wait until .NET 4 comes out :)</p> <p>Moreover, I'm dealing with a code base which already relies on SRE.</p> <p>Obviously, ILGenerator do everything I need. But I would appreciate more assistance when manipulating it. When I'm referring to a ILGenerator wrapper, which remains at a pretty low level, I think about something which could provide methods like:</p> <pre><code>// Performs a virtual or direct call on the method, depending if it is a // virtual or a static one. Call(MethodInfo methodInfo) // Pushes the default value of the type on the stack, then emit // the Ret opcode. ReturnDefault(Type type) // Test the object type to emit the corresponding push // opcode (Ldstr, Ldc_I*, Ldc_R*, etc.) LoadConstant(object o) </code></pre> <p>It's really 3 naive examples, but it could be enough to demonstrate what I expect. We can see that as a set of extension methods, but it could be nice to have support for conditional statements and loops like in <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx" rel="noreferrer">RunSharp</a>. In fact, RunSharp is pretty close that what I want, but it abstracts the ILGenerator too much and doesn't expose all its functionality.</p> <p>I can't remember where, but I already saw such an helper in an open source project.</p>
<p>If you're using .NET 3.5, you may find using Expression Trees to be more reasonable. It entirely depends on what you're doing - and it can still be quite painful - but it's certainly another option to be aware of.</p>
<p>[updated]: I thought of the name ;-p <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx" rel="nofollow noreferrer">RunSharp</a>. I can't vouch for it, but it might be what you need.</p> <p>However; what do you need to generate? <a href="http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx" rel="nofollow noreferrer">CodeDom</a> is one option. For creating methods, you might find that you can do a lot more than you expect with the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx" rel="nofollow noreferrer">Expression</a> class in .NET 3.5 (after compiling it to a typed delegate via Expression.Lambda/Compile.</p>
23,945
<p>I've been using:</p> <p><a href="http://www.webmin.com" rel="nofollow noreferrer">Webmin</a> Free, Apache only</p> <p><a href="http://www.cpanel.net" rel="nofollow noreferrer">Cpanel</a> Paid, Apache only I believe</p> <p><a href="http://www.parallels.com/plesk/" rel="nofollow noreferrer">Plesk</a> Paid, supports IIS</p> <p>Recently managing sites on our Windows/IIS machines have been becoming a chore. Installations, Configurations, Monitoring; have all been mostly done by hand and with a mess of scripts we've put together over time.</p> <p>Does anyone know of any tools similar to the above that work in this kind of environment?</p> <p>edit: we're using remote desktop now, the problem is we don't always know which web site is on which machine... yes, that's more of an internal problem. but it would be great to have a resource with administrative capability that does more than setup/configure sites, but the ftp accounts, email accounts, disk quota management, etc.</p>
<p>It's not quite what you're after (I think), but if you virtualized your Windows/IIS environments, and ran them on Microsoft Virtual Server, that would give you a remote, web-based interface for administration. </p> <p>Not quite in the vein of the examples you listed, but still...</p>
<p>I've never come across one. Never thought to ask about one either, so I'm glad I came across your question. Hope someone knows of something.</p> <p>A few of the companies that I've worked for / with have had the same issues: many web servers, outdated documentation (or no documentation) and little time to get anything done.</p> <p>I've usually just created scripts that export info on them to xml files. Microsoft has a decent IIS 6 scripting repository (though, you're out of luck if you're running pre Win2003): <a href="http://www.microsoft.com/technet/scriptcenter/scripts/iis/iis6/default.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/scripts/iis/iis6/default.mspx?mfr=true</a></p>
14,806
<p>I've been given the task of doing some work customizing an artist's space in MySpace. It seems that you sort of hack the HTML you want into your edit profile page (which has several empty boxes). The MySpace page, it seems, is already HTML so you can only hack into that. Suggested "tweaks" include incomplete HTML code (e.g., a <code>&lt;DIV&gt;</code> tag without a <code>&lt;/DIV&gt;</code> tag to supress certain sections) and stylesheet pieces that you can "place anywhere" (meaning somewhere on your edit profile page). And the best one is that sites that offer layouts say, "Layout Code - Copy and Paste the code at the bottom of your 'I'd Like to Meet' Section!"</p> <p>This cannot possibly be this lame, can it?</p> <p>Is there any coherent guide to customizing MySpace pages for programmers/HTML designers? Is there a coherent DOM (including things like <code>.contactTable</code> etc.)? Could it be that all the tweaks are just hacks people have figured out from looking at the generated HTML?</p> <p>Thanks!</p>
<p>This shouldn't be too hard if you whip out Firebug and do a bunch of "Inspect > click on page > edit CSS in Firebug's editor" work to see what you can learn about the structure of the page. Then mock it up to roughly how you want it and note down which elements and which styles need work and figure out how to get that set up in the profile editor.</p> <p>Try approaching this from the point of view of a challenge. On the upside, MySpace allows you access to the DOM so you can screw with all sorts of things. On the downside, their choice of HTML composition is somewhat arguable.</p>
<p>Your fears are correct. MySpace "customization" is a bunch of hacks. Good luck.</p>
14,206