instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I hate to have to ask, but I'm pretty stuck here.</p> <p>I need to test a sequence of numbers to find the first which has over 500 factors: <a href="http://projecteuler.net/index.php?section=problems&amp;id=12" rel="nofollow noreferrer">http://projecteuler.net/index.php?section=problems&amp;id=12</a></p> <p>-At first I attempted to brute force the answer (finding a number with 480 after a LONG time)</p> <p>-I am now looking at determining the prime factors of a number and then use them to find all other factors.</p> <p>I am currently at the stage where I can get an array of prime factors for any number I input - i.e 300 has the prime factors 2 2 3 5 5</p> <p>Using this array of prime factors I need to be able to calculate the remaining factors - This is the part I am stuck on. Basically, as I understand it, I need to calculate ALL possible combinations of the numbers in the array...</p> <p>i.e 2 * 2 <br> 2 * 2 * 3 <br> 2 * 2 * 3 * 5 <br> 2 * 3 <br> 2 * 3 * 3 <br> ...and so forth - But where it gets interesting is with things like...<br> 2 * 5 <br> 2 * 3 * 5 <br> ...i.e Numbers which are not adjacent to each other in the array</p> <p>I can't think of a way to code this in a generic fashion for any length array...</p> <p>I need help! P.S - I am working in Java</p> <p>EDIT: My brute force code - As it has been suggested brute forcing the problem will work and so there may be an error in my code :(</p> <pre><code>package euler.problem12; public class Solution { public static void main(String[] args) { int next = 1; int triangle = 0; int maxFactors = 0; while(true) { triangle = triangle + next; int factors = 1; int max = (int) triangle / 2; for(int i = 1; i &lt;= max; ++i) { if(triangle % i == 0) { factors ++; } } if(factors &gt; maxFactors) { maxFactors = factors; System.out.println(triangle + "\t" + factors); } next++; } } } </code></pre>
<p>As far as I can tell, question 12 doesn't mention anything about prime numbers? Is this the one you're looking at? </p> <blockquote> <p>The sequence of triangle numbers is generated by adding the natural numbers...</p> </blockquote> <p>If so, then perhaps not thinking about primes will help? ;)</p>
<p>Possibly 3 months too late, but here goes...</p> <p>I see that answer two has privided the function to give you the answer you require, but in answer to your original question on how you generate all the factors assuming you need to for some reason, then here's how you do it:</p> <p>Assuming that you have the factors in an array:</p> <p>int[] primeFactors = new int[] {2, 2, 3, 5, 5};</p> <p>What you need to do is recurse every in-order permutation for each possible depth, and then reduce the resulting result set to just the unique values.</p> <p>I'll explain what I mean: "In-order permutation": assuming you start at position 0 of the array, the next element must be 1, 2, 3 or 4, if you start from 1 then the next one must be 2, 3 or 4 and so on.</p> <p>"Each possible depth": each single factor, then any two factors, then any three factors and so on until you get to all five factors.</p> <p>"Reduce the set": If you take two elements, say 0&amp;3, 0&amp;4, 1&amp;3 or 1&amp;4 they all give you 2 * 5 = 10, they all provide the factor 10, so you need to winnow your set to just distinct values. (Phew, this is getting longer than I expected... :))</p> <p>The way to do this is to use two methods, one to select the maximum depth of recursion, kick off the recustion and the winnow the final results, and the other to recurse the values:</p> <pre><code>public static void main(String[] args) { int[] primeFactors = new int[] {2, 2, 3, 5, 5}; List&lt;Integer&gt; allFactors = getAllFactors(primeFactors); for (int factor : allFactors) { System.out.println("Factor: " + factor); } } private static List&lt;Integer&gt; getAllFactors(int[] primeFactors) { Set&lt;Integer&gt; distinctFactors = new HashSet&lt;Integer&gt;(); for (int maxDepth = 0; maxDepth &lt;= primeFactors.length; maxDepth++) { permutatPrimeFactors(0, maxDepth, 0, 1, primeFactors, distinctFactors); } List&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(distinctFactors); Collections.sort(result); return result; } private static void permutatPrimeFactors(int depth, int maxDepth, int minIndex, int valueSoFar, int[] primeFactors, Set&lt;Integer&gt; distinctFactors) { if (depth == maxDepth) { distinctFactors.add(valueSoFar); return; } for (int index = minIndex; index &lt; primeFactors.length; index++) { permutatPrimeFactors(depth + 1, maxDepth, index + 1, valueSoFar * primeFactors[index], primeFactors, distinctFactors); } } </code></pre> <p>The getAllFactors uses a Set to make sure we only get distinct values, than adds them to a list and sorts that so that we can display the factors in order.</p> <p>While permutatPrimeFactors, generates from zero terms (factor = 1) though to all terms (factor = 1 * 2 * 2 *3 * 5 * 5 = 300).</p> <p>Hope that helps.</p>
34,998
<p>There are many drawbacks to using <code>void *</code> in C (memory related, type related, efficiency wise ...). In spite of them we use them a lot for the flexibility they provide.</p> <p>List the disadvantages/drawbacks using <code>void *</code> (and preferred solution in C - if possible).</p> <p><strong>EDIT:</strong> please go through the follwoing link: <a href="http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/" rel="nofollow noreferrer">http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/</a></p>
<p>There are no efficiency issues with void pointers. The only limitations with void pointers are:</p> <ul> <li>you cannot dereference void pointer for obvious reasons</li> <li><code>sizeof(void)</code> is illegal</li> <li>you cannot perform pointer arithmetics on void pointers</li> </ul> <p>However GCC assumes that <code>sizeof(void)</code> is 1 and allows pointer arithmetics on void pointers - <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Pointer-Arith.html" rel="noreferrer">see here</a></p>
<p>Your given link, is partially true. Especially, when you are not dealing with objects (structs), or in general with types that aren't already allocated. Using native types like ints, doubles etc. and void-pointers (e.g. for a container) is nearly always an icky affair, because you have either the choice to cast the int (for a double this doesn't work) to a pointer or you need to allocate extra memory for the data type.</p> <p>First choice is bad because it is not portable, 0s are maybe not allowed as a value and it simply feels bad. Second choice wastes memory and is indeed a (massive) slow down because of the extra allocations.</p> <p><strong>But</strong> in most cases you aren't dealing with native types, but with objects, better said with pointers to objects, which are already allocated, at least I do. I never needed a hash-table or a map for integers or doubles. And having different container implementations only for type safeness of pointers feels wrong to me, because every implementation will increase your binary size. So if you are only need a container to store your pointers, there is no slow down or memory waste in using void-pointers.</p> <p>But note, this was all about container implementations, like btw the blog article you mentioned. In general there are many things you cannot accomplish without using void-pointers.</p>
44,143
<p>How to use data mining feature of SQL Server 2008 with ASP.Net</p>
<p>Take a look at <a href="http://www.sqlserverdatamining.com/ssdm/" rel="nofollow noreferrer">SqlServerDataMining.com</a>, a site run by Microsoft's SQL Server Data Mining team.</p>
<p>In a nutshell, you want to:</p> <ul> <li>Build cubes to model your data</li> <li>Build a prediction calculator (or whatever kind of calculator you're looking to use)</li> <li>Expose that via a web service</li> <li>Call the web service in your app</li> </ul> <p>For example, if you want to model whether or not a customer is likely to abandon their shopping card, you would figure out what characteristics of a shopper you want to capture and analyze. You set up your cubes to model what characteristics are indicative of a soon-to-be-bailing-out shopper. During the shopping process, your web app would send the shopper's characteristics to the SSAS server, which would return back a guess about whether or not the shopper is going to abandon the cart. Then your web app can take proactive measures before they leave.</p> <p>All of the steps in here are kinda complicated - your best bet is probably to refine your question to focus on the areas you're responsible for.</p>
20,009
<p>I have an old project that was built using visual studio 2003 and I recompiled it with vs2005 recently. However, during runtime, I get the following error:</p> <p>list iterator not incrementable</p> <p>I traced the program to this function:</p> <pre><code>void InputQueue::update() { list&lt;PCB&gt;::iterator iter; list&lt;PCB&gt;::iterator iterTemp; for(iter = begin(); iter != end(); iter++) { if(iter-&gt;arrivalTime == 0) { ReadyQueue::getInstance()-&gt;add(*iter); iterTemp = iter; iter++; erase(iterTemp); } } } </code></pre> <p>I'm not a C++ expert and this is as far as the VS debugger got me. Could somebody explain to me what the problem is?</p> <p>Thanks</p>
<p>I would re-write your loop to be like the following:</p> <pre><code>while (iter != end()) { if (iter-&gt;arrivalTime == 0) { ReadyQueue::getInstance()-&gt;add(*iter); iter = erase(iter); } else { ++iter; } } </code></pre> <p>Now you are correctly looping through the list checking every index.</p>
<p>I beliebe Chris is right. However, another problem might stem from the fact that you assign to the iterator. – Are list iterators guaranteed to be assignable? Without looking at the standard, I don't think so because assignability is nowhere mentioned in the SGI documentation of iterators.</p>
23,942
<p>I've got a strange problem with indexing PDF files in SQL Server 2005, and hope someone can help. My database has a table called MediaFile with the following fields - MediaFileId int identity pk, FileContent image, and FileExtension varchar(5). I've got my web application storing file contents in this table with no problems, and am able to use full-text searching on doc, xls, etc with no problems - the only file extension not working is PDF. When performing full-text searches on this table for words which I know exist inside of PDF files saved in the table, these files are not returned in the search results.</p> <p>The OS is Windows Server 2003 SP2, and I've installed <a href="http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611" rel="noreferrer">Adobe iFilter 6.0</a>. Following the instructions on <a href="http://weblogs.asp.net/wallym/archive/2005/02/28/382060.aspx" rel="noreferrer">this blog entry</a>, I executed the following commands:</p> <pre><code>exec sp_fulltext_service 'load_os_resources', 1; exec sp_fulltext_service 'verify_signature', 0; </code></pre> <p>After this, I restarted the SQL Server, and verified that the iFilter for the PDF extensions is installed correctly by executing the following command:</p> <pre><code>select document_type, path from sys.fulltext_document_types where document_type = '.pdf' </code></pre> <p>This returns the following information, which looks correct:</p> <blockquote> <p>document_type: .pdf<br/> path: C:\Program Files\Adobe\PDF IFilter 6.0\PDFFILT.dll</p> </blockquote> <p>Then I (re)created the index on the MediaFile table, selecting FileContent as the column to index and the FileExtension as its type. The wizard creates the index and completes successfully. To test, I'm performing a search like this:</p> <pre><code>SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(*, '"house"'); </code></pre> <p>This returns DOC files which contain this term, but not any PDF files, although I know that there are definitely PDF files in the table which contain the word <em>house</em>.</p> <p>Incidentally, I got this working once for a few minutes, where the search above returned the correct PDF files, but then it just stopped working again for no apparent reason.</p> <p>Any ideas as to what could be stopping SQL Server 2005 from indexing PDF's, even though Adobe iFilter is installed and appears to be loaded?</p>
<p>Thanks Ivan. Managed to eventually get this working by starting everything from scratch. It seems like the order in which things are done makes a big difference, and the advice given on the linked blog to to turn off the 'load_os_resources' setting after loading the iFilter probably isn't the best option, as this will cause the iFilter to not be loaded when the SQL Server is restarted.</p> <p>If I recall correctly, the sequence of steps that eventually worked for me was as follows:</p> <ol> <li>Ensure that the table does not have an index already (and if so, delete it)</li> <li>Install Adobe iFilter</li> <li>Execute the command exec sp_fulltext_service 'load_os_resources', 1;</li> <li>Execute the command exec sp_fulltext_service 'verify_signature', 0;</li> <li>Restart SQL Server</li> <li>Verify PDF iFilter is installed</li> <li>Create full-text index on table</li> <li>Do full re-index</li> </ol> <p>Although this did the trick, I'm quite sure I performed these steps a few times before it eventually started working properly.</p>
<p>I've just struggled with it for an hour, but finally got it working. I did everything you did, so just try to simplify the query (I replaced <code>*</code> with field name and removed double quotes on term):</p> <pre><code>SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(FileContent, 'house') </code></pre> <p>Also when you create full text index make sure you specify the language. And the last thing is maybe you can try to change the field type from <code>Image</code> to <code>varbinary(MAX)</code>.</p>
34,332
<p>I have seen mechanical (micro switch), optical and magnetic(magnet + hall sensor) end stops.</p> <p>Are there any differences in how exact they switch at the right location? If so which are the most precise?</p>
<p>There are some different criteria that we should use to select a switch type:</p> <ul> <li>Precision / repeatability: does the switch trigger at the same place every time? How much spread is there in the trigger position? Do environmental changes or machine setting changes affect the trigger position?</li> <li>Contact distance: does the switch register with enough clearance to its hard-stop that the homing axis can stop before colliding with something?</li> <li>Noise-rejection: does the switch ONLY trigger when it is supposed to? </li> </ul> <p>It's important to ask, how much switch precision do we actually need? A typical 3d printer drivetrain using a microstepping stepper motor can only accurately position the moving load within +/- one 1/16th microstep (even if using finer microstepping than that) due to error-inducing effects like friction torque and magnetic detent angle error. That's around +/-0.01mm for most printers. The homing switch only needs to be as precise as the motor's positioning! Nothing is gained by having, say, 0.001mm precision endstops. </p> <p>This precision of +/-0.01mm is achievable for all types of endstop switches, with proper switch selection and configuration. </p> <p>Then there are three "standard" switching types in use in consumer/hobbyist 3d printers:</p> <ul> <li>Mechanical switches, typically dual NO/NC limit switches, which either pull up or pull down a signal pin by connecting an electrical circuit when triggered</li> <li>Optical switches, which use transistors to detect when an obstacle ("flag") is blocking the window between the emitter and sensor</li> <li>Hall effect switches, which use transistors to detect when a magnetic field exceeds a particular field strength cutoff</li> </ul> <p><strong>Mechanical Switches</strong></p> <p>Precision/repeatability depends on the switch quality, length of lever arm attached (longer increases contact distance but is worse for precision), and impact speed of the carriage with the switch. It's possible to have a good mechanical switch or a bad mechanical switch. This is typically a reasonable default choice because it is simple and cheap. </p> <p>A small mechanical switch with a short lever arm (or the lever arm removed) will generally achieve the required +/-0.01mm switching precision. Very cheap switches, high contact speeds, and long lever arms may provide inadequate resolution for Z homing or probing, but will still be adequate for low-precision X and Y homing purposes. </p> <p>Where mechanical switches tend to cause issues is in noise rejection. Different controller boards use different ways of wiring the switch: some use two wires and only send a signal when triggered. When not triggered, the signal wire is left floating or weakly pulled up by the microcontroller, while attached to a long wire that acts as an antenna to pick up EM noise. It is VERY common for heater or stepper wiring to emit nasty EMR due to the PWM current control. Two-wire endstop cables should always be run away from stepper and heater wiring. Shielding and twisting the conductors is a good idea too. </p> <p>A more robust approach is to use three-wire switches that actively pull the signal line high or low depending on the switch position. These will tend to reject noise better. </p> <p>Very cheap mechanical switches may fail within the life of the printer. However, most limit switches are rated for millions of cycles, which is unlikely to occur over any normal printer's lifespan. </p> <p>Mechanical switches are easy to align and easy to trigger by hand during troubleshooting. </p> <p><strong>Optical Switches</strong></p> <p>These rely on a flag blocking a window between a light emitter and a detector. This is non-contact and can be quite reliable, but introduces some challenges. The exact trigger position (and thus precision) may depend on ambient light levels in the room, because the sensor is monitoring for light to decrease below a specific intensity. So it may be very repeatable/precise in the short term but have some drift if the sensor moves in and out of the sun through the day.</p> <p>Switching tends to be more consistent and reliable if the flag enters the window from the side, rather than the top. </p> <p>Optical switches will actively pull the signal line high or low, and thus have good electrical noise rejection.</p> <p><strong>Hall Effect Switches</strong></p> <p>These measure the intensity of the nearby magnetic field and trigger when it exceeds a certain amount in a certain polarity. This is highly precise/repeatable (better than +/-0.01mm) and extremely resistant to noise and environmental conditions. (Unless your printer is next to something that emits large magnetic fields, anyway.) </p> <p>The hall switches I've seen have an adjustable trim pot to tune the trigger distance. That's a nice feature when trying to manually calibrate a Delta or a Z-bed for first layer height. </p> <p>The primary downside to hall switches is that they need a magnet to trigger the switch. This can be difficult to trigger by hand during troubleshooting, and requires attaching a magnet somewhere on the moving carriage. Glue works fine... but don't glue the magnet in place backwards!</p>
<p>A separate issue not addressed in other answers is that the end stops for X/Y axes have different requirements than those for the Z axis.</p> <h3>X/Y Axes</h3> <p>When the printer offers XYZ calibration (like Prusa i3 MK2), the properties of the X and Y switches play a role, since for the Z probing the probe should be centered above the fiducials (copper circles) in the bed. The XY part of the calibration measures the position of the fiducials relative to the end-stop trigger point. Then the Z calibration measures the height of each fiducial.</p> <p>When the XYZ calibration is not offered, there's usually no need for very repeatable positioning relative to the X and Y travel ends, and on most printers you could simply move the motors until they start skipping steps and call that a day - it will be accurate to within a few steps.</p> <h3>Z Axis</h3> <p>The Z axis always has a high requirement on accuracy and repeatability, and there are two general approaches to determining its position:</p> <ol> <li><p>No end-stops on the Z-axis drive system, a probe is mounted on the print head and is used to detect when the head is a certain distance above the print bed. This can be used for 9-point calibration of the bed shape and thus removes the need for bed levelling.</p> </li> <li><p>End-stops used on the Z-axis drive system. No sensor on the print head. The bed needs to be separately leveled in reference to the nozzle - thus the bed leveling screws.</p> </li> </ol> <h3>Delta Z</h3> <p>For Delta, you essentially have three Z axis drivers, and similar to the Cartesian XYZ drive, you don't need any end-stops if you have a probe on the print head. You can also perform multi-point bed leveling with such a probe.</p> <h3>Other Approaches</h3> <p>X and Y endstops become unnecessary once you use closed-loop stepper control, such as <a href="http://tropical-labs.com/index.php/mechaduino" rel="nofollow noreferrer">Mechaduino</a> or linear digital position sensors (e.g. as used in CNC machines).</p> <p>The Z probe is still useful if you don't want to perform bed leveling manually.</p>
278
<p>How do you round a Double down to the nearest integer in VB .NET?</p>
<p>This is pretty old, but the accepted answer of using <code>Math.Truncate</code> is technically incorrect: Truncate rounds <em>towards zero</em>, not down. For example, -1.5 is rounded to -1 instead of -2.</p> <p>In order to always round <em>down</em>, use <code>Math.Floor</code>.</p>
<p>This is the logic we have used:</p> <pre><code>dim d as decimal = 1.50 dim I as int64 = convert.toint64(D) </code></pre>
49,540
<p>Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> <a href="http://en.wikipedia.org/wiki/ISO_week_date" rel="noreferrer">week number</a> of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way.</p> <p>I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine.</p>
<h1>tl;dr</h1> <pre><code>LocalDate.of( 2015 , 12 , 30 ) .get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) </code></pre> <blockquote> <p>53</p> </blockquote> <p>…or…</p> <pre><code>org.threeten.extra.YearWeek.from ( LocalDate.of( 2015 , 12 , 30 ) ) </code></pre> <blockquote> <p>2015-W53</p> </blockquote> <h1>java.time</h1> <p>Support for the <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="noreferrer">ISO 8601 week</a> is now built into Java 8 and later, in the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> framework. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes as they have been supplanted by java.time.</p> <p>These new java.time classes include <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="noreferrer"><code>LocalDate</code></a> for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); </code></pre> <p>Or specify the year, month, and day-of-month as suggested in the Question.</p> <pre><code>LocalDate localDate = LocalDate.of( year , month , dayOfMonth ); </code></pre> <p>The <a href="https://docs.oracle.com/javase/8/docs/api/java/time/temporal/IsoFields.html" rel="noreferrer"><code>IsoFields</code></a> class provides info according to the ISO 8601 standard including the week-of-year for a week-based year.</p> <pre><code>int calendarYear = now.getYear(); int weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR ); int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR ); </code></pre> <p>Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 &amp; 1 become 52 &amp; 53.</p> <p><a href="https://i.stack.imgur.com/8WO81.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8WO81.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/kHwC5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kHwC5.png" alt="enter image description here"></a></p> <h1>ThreeTen-Extra — <code>YearWeek</code></h1> <p>The <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="noreferrer"><code>YearWeek</code></a> class represents both the ISO 8601 week-based year number <em>and</em> the week number together as a single object. This class is found in the <a href="http://www.threeten.org/threeten-extra/" rel="noreferrer"><em>ThreeTen-Extra</em></a> project. The project adds functionality to the java.time classes built into Java.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); YearWeek yw = YearWeek.now( zoneId ) ; </code></pre> <p>Generate a <code>YearWeek</code> from a date.</p> <pre><code>YearWeek yw = YearWeek.from ( LocalDate.of( 2015 , 12 , 30 ) ) </code></pre> <p>This class can generate and parse strings in standard ISO 8601 format.</p> <pre><code>String output = yw.toString() ; </code></pre> <blockquote> <p>2015-W53</p> </blockquote> <pre><code>YearWeek yw = YearWeek.parse( "2015-W53" ) ; </code></pre> <p>You can extract the week number or the week-based-year number.</p> <pre><code>int weekNumber = yw.getWeek() ; int weekBasedYearNumber = yw.getYear() ; </code></pre> <p>You can generate a particular date (<code>LocalDate</code>) by specifying a desired day-of-week to be found within that week. To specify the day-of-week, use the <code>DayOfWeek</code> enum built into Java 8 and later.</p> <pre><code>LocalDate ld = yw.atDay( DayOfWeek.WEDNESDAY ) ; </code></pre> <hr> <h1>About <em>java.time</em></h1> <p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href="https://en.wikipedia.org/wiki/Legacy_system" rel="noreferrer">legacy</a> date-time classes such as <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Date.html" rel="noreferrer"><code>java.util.Date</code></a>, <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html" rel="noreferrer"><code>Calendar</code></a>, &amp; <a href="http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a>.</p> <p>To learn more, see the <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="noreferrer"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a>.</p> <p>The <a href="http://www.joda.org/joda-time/" rel="noreferrer"><em>Joda-Time</em></a> project, now in <a href="https://en.wikipedia.org/wiki/Maintenance_mode" rel="noreferrer">maintenance mode</a>, advises migration to the <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> classes.</p> <p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="noreferrer">JDBC driver</a> compliant with <a href="http://openjdk.java.net/jeps/170" rel="noreferrer">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p> <p>Where to obtain the java.time classes? </p> <ul> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="noreferrer"><strong>Java SE 8</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9" rel="noreferrer"><strong>Java SE 9</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10" rel="noreferrer"><strong>Java SE 10</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11" rel="noreferrer"><strong>Java SE 11</strong></a>, and later - Part of the standard Java API with a bundled implementation. <ul> <li>Java 9 adds some minor features and fixes.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6" rel="noreferrer"><strong>Java SE 6</strong></a> and <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7" rel="noreferrer"><strong>Java SE 7</strong></a> <ul> <li>Most of the <em>java.time</em> functionality is back-ported to Java 6 &amp; 7 in <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a>.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="noreferrer"><strong>Android</strong></a> <ul> <li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li> <li>For earlier Android (&lt;26), the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href="http://stackoverflow.com/q/38922754/642706"><em>How to use ThreeTenABP…</em></a>.</li> </ul></li> </ul> <p>The <a href="http://www.threeten.org/threeten-extra/" rel="noreferrer"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="noreferrer"><code>Interval</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="noreferrer"><code>YearWeek</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html" rel="noreferrer"><code>YearQuarter</code></a>, and <a href="http://www.threeten.org/threeten-extra/apidocs/index.html" rel="noreferrer">more</a>.</p>
<p>this is the reverse: gives you the date of the monday of the week (in perl)</p> <pre><code>use POSIX qw(mktime); use Time::localtime; sub monday_of_week { my $year=shift; my $week=shift; my $p_date=shift; my $seconds_1_jan=mktime(0,0,0,1,0,$year-1900,0,0,0); my $t1=localtime($seconds_1_jan); my $seconds_for_week; if (@$t1[6] &lt; 5) { #first of january is a thursday (or below) $seconds_for_week=$seconds_1_jan+3600*24*(7*($week-1)-@$t1[6]+1); } else { $seconds_for_week=$seconds_1_jan+3600*24*(7*($week-1)-@$t1[6]+8); } my $wt=localtime($seconds_for_week); $$p_date=sprintf("%02d/%02d/%04d",@$wt[3],@$wt[4]+1,@$wt[5]+1900); } </code></pre> <p></p>
17,719
<p>I’ve almost 6 years of experience in application development using .net technologies. Over the years I have improved as a better OO programmer but when I see code written by other guys (especially the likes of Jeffrey Richter, Peter Golde, Ayende Rahien, Jeremy Miller etc), I feel there is a generation gap between mine and their designs. I usually design my classes on the fly with some help from tools like ReSharper for refactoring and code organization. </p> <p>So, my question is “what does it takes to be a better OO programmer”. Is it </p> <p>a) Experience</p> <p>b) Books (reference please)</p> <p>c) Process (tdd or uml) </p> <p>d) patterns</p> <p>e) anything else?</p> <p>And how should one validate that the design is good, easy to understand and maintainable. As there are so many buzzwords in industry like dependency injection, IoC, MVC, MVP, etc where should one concentrate more in design. I feel abstraction is the key. What else?</p>
<p>you'll probably find that the elegant OO designs that you admire <em>are not the first iteration</em>, but result from several adjustments, refactorings, and fine-tunings</p> <p>try to qualify why you think their designs are 'better' than yours, and adjust accordingly</p> <p>the difference between an amateur writer and a professional writer is that the professional <em>rewrites</em>; the same holds for programming</p>
<p>knowing and understanding the GoF (Gamma et al.) design patterns is never wrong. they can be applied to a lot of situations. i guess they are essential stuff for every developer!</p>
28,794
<p>can anyone please suggest a <strong>good code example</strong> of vb.net/c# code to put the application in system tray when minized.</p>
<p>Add a NotifyIcon control to your form, then use the following code:</p> <pre><code> private void frm_main_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.ShowInTaskbar = false; this.Hide(); notifyIcon1.Visible = true; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; notifyIcon1.Visible = false; } </code></pre> <p>You may not need to set the ShowInTaskbar property.</p>
<p>You can do this by adding a NotifyIcon to your form and handling the form's resize event. To get back from the tray handle the NotifyIcon's double-click event.</p> <p>If you want to add a little animation you can do this too...</p> <p>1) Add the following module:</p> <pre><code>Module AnimatedMinimizeToTray Structure RECT Public left As Integer Public top As Integer Public right As Integer Public bottom As Integer End Structure Structure APPBARDATA Public cbSize As Integer Public hWnd As IntPtr Public uCallbackMessage As Integer Public uEdge As ABEdge Public rc As RECT Public lParam As IntPtr End Structure Enum ABMsg ABM_NEW = 0 ABM_REMOVE = 1 ABM_QUERYPOS = 2 ABM_SETPOS = 3 ABM_GETSTATE = 4 ABM_GETTASKBARPOS = 5 ABM_ACTIVATE = 6 ABM_GETAUTOHIDEBAR = 7 ABM_SETAUTOHIDEBAR = 8 ABM_WINDOWPOSCHANGED = 9 ABM_SETSTATE = 10 End Enum Enum ABNotify ABN_STATECHANGE = 0 ABN_POSCHANGED ABN_FULLSCREENAPP ABN_WINDOWARRANGE End Enum Enum ABEdge ABE_LEFT = 0 ABE_TOP ABE_RIGHT ABE_BOTTOM End Enum Public Declare Function SHAppBarMessage Lib "shell32.dll" Alias "SHAppBarMessage" (ByVal dwMessage As Integer, ByRef pData As APPBARDATA) As Integer Public Const ABM_GETTASKBARPOS As Integer = &amp;H5&amp; Public Const WM_SYSCOMMAND As Integer = &amp;H112 Public Const SC_MINIMIZE As Integer = &amp;HF020 Public Sub AnimateWindow(ByVal ToTray As Boolean, ByRef frm As Form, ByRef icon As NotifyIcon) ' get the screen dimensions Dim screenRect As Rectangle = Screen.GetBounds(frm.Location) ' figure out where the taskbar is (and consequently the tray) Dim destPoint As Point Dim BarData As APPBARDATA BarData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(BarData) SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, BarData) Select Case BarData.uEdge Case ABEdge.ABE_BOTTOM, ABEdge.ABE_RIGHT ' Tray is to the Bottom Right destPoint = New Point(screenRect.Width, screenRect.Height) Case ABEdge.ABE_LEFT ' Tray is to the Bottom Left destPoint = New Point(0, screenRect.Height) Case ABEdge.ABE_TOP ' Tray is to the Top Right destPoint = New Point(screenRect.Width, 0) End Select ' setup our loop based on the direction Dim a, b, s As Single If ToTray Then a = 0 b = 1 s = 0.05 Else a = 1 b = 0 s = -0.05 End If ' "animate" the window Dim curPoint As Point, curSize As Size Dim startPoint As Point = frm.Location Dim dWidth As Integer = destPoint.X - startPoint.X Dim dHeight As Integer = destPoint.Y - startPoint.Y Dim startWidth As Integer = frm.Width Dim startHeight As Integer = frm.Height Dim i As Single For i = a To b Step s curPoint = New Point(startPoint.X + i * dWidth, startPoint.Y + i * dHeight) curSize = New Size((1 - i) * startWidth, (1 - i) * startHeight) ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick) System.Threading.Thread.Sleep(15) ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick) Next If ToTray Then ' hide the form and show the notifyicon frm.Hide() icon.Visible = True Else ' hide the notifyicon and show the form icon.Visible = False frm.Show() End If End Sub End Module </code></pre> <p>2) Add a NotifyIcon to your form an add the following:</p> <pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) If m.Msg = WM_SYSCOMMAND AndAlso m.WParam.ToInt32() = SC_MINIMIZE Then AnimateWindow(True, Me, NotifyIcon1) Exit Sub End If MyBase.WndProc(m) End Sub Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick AnimateWindow(False, Me, NotifyIcon1) End Sub </code></pre>
10,171
<p>Is there a way to access Visual Studio's built-in ASP.NET Development Server over HTTPS?</p>
<p>As of now we can use IIS Express to develop and test in SSL. Here is a complete article explaning how to use IIS Express and Visual Studion 2010 to develop websites in SSL.</p> <p><img src="https://i.stack.imgur.com/jvqeG.png" alt="enter image description here"></p> <p><strong>Next</strong></p> <p><img src="https://i.stack.imgur.com/3didG.png" alt="enter image description here"></p> <p><strong>Then you will get this</strong> </p> <p><img src="https://i.stack.imgur.com/Oh154.png" alt="enter image description here"></p> <p><a href="http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx" rel="noreferrer">Working with SSL at Development Time is easier with IISExpress</a></p> <p><a href="http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx" rel="noreferrer">Introducing IIS Express </a></p>
<p><strong>Select the project-file in the Solution Explorer:</strong> for example: "WebApplication1". </p> <p>With pressing <strong>ALT+ENTER</strong> you enter the project-properties. </p> <p>Select <strong>"DEBUG"</strong> on the <strong>left side</strong>.</p> <p>Here you can select <strong>"Enable SSL"</strong>.</p> <p><em>Then you can start your project with IIS Express normally and it will start using SSL, the new Port will be 44301</em> </p>
8,493
<p>What does the following Guile scheme code do?</p> <pre><code>(eq? y '.) (cons x '.) </code></pre> <p>The code is not valid in MzScheme, is there a portable equivalent across scheme implementations?</p> <p>I am trying to port this code written by someone else. Guile seems to respond to '. with #{.}#, but I'm not sure what it means or how to do this in another scheme.</p>
<p>Okay, it seems that '. is valid syntax for (string->symbol ".") in Guile, whereas MzScheme at least requires |.| for the period as a symbol.</p>
<p>I'm surprised any Scheme system will accept a dot symbol at all. My advice is to use another symbol as (I'm sure you're aware) the dot is a shorthand to represent a pair, and even if you can find a Scheme that will take your code you will likely confuse anyone that has the unfortunate task of actually reading your code.</p>
9,007
<p>I'm curious what techniques you find to be the best for storage and maintaining of viewstate with respect to an ASP.Net application running within a mobile web browser (i.e. Treo with Windows Mobile, or Blackberry Curve web browser).</p>
<p>If you use the mobile controls, the view state can actually be stored in the session instead so it doesn't eat bandwidth. See this link <a href="http://msdn.microsoft.com/en-us/library/cteh3e77.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cteh3e77.aspx</a> for more about mobile controls and maintaining state.</p> <p>Hope this helps.</p>
<p>Some of the mobile controls still store settings in ways that older phones may not support. If you are targeting older mobile phones, you should either change your session settings to cookieless or start using the HiddenVariables collection instead (which older phones can use). We used hiddenvariables since changing our whole site over to cookieless was not an option. However, hiddenvariables can only be strings so you will need to be ready to serialize objects into hidden fields as strings, just like viewstate does.</p>
26,353
<p>Recently I had to develop a SharePoint workflow, and I found the experience quite honestly the most painful programming task I've ever had to tackle. One big problem I had was the problems I encountered when I had to step through it in the debugger.</p> <p>There's an article on how to debug a SharePoint workflow <a href="http://www.andrewconnell.com/blog/archive/2008/06/11/SharePoint-Debugging-and-Logging-Tips-and-Tricks.aspx" rel="nofollow noreferrer">here</a> that tells you how to set breakpoints etc. This involves copying the .pdb file into the GAC alongside the .dll file containing your workflow. You have to do this from a command prompt (or a batch file) because Windows Explorer doesn't let you view the relevant subdirectory of c:\windows\assembly.</p> <p>However, if you do this, the next time you try to deploy the workflow from within Visual Studio, it complains that it can't be deployed because "the file may not be signed" and if you attempt to copy the new version of the dll into the GAC, it tells you that the .dll file is locked.</p> <p>I've found that some of the time, you can get round this by doing an iisreset, but on other occasions you have to restart Visual Studio and there have been frequent times when I've even had to reboot the computer altogether because some mystery process has locked the file. When I don't use the debugger, on the other hand, everything works just fine.</p> <p>Does anyone know of a simpler way of debugging workflows than this?</p>
<p>The SharePoint team is currently working on MOSS extensions for VS 2008 which will allow this type of functionality. This was available in VS 2005 with MOSS extensions, but has to be run off Windows Server with a full MOSS installation and the correct permissions set.</p>
<p>Check out <a href="http://www.codeplex.com/stsdev" rel="nofollow noreferrer">STSDev</a> on CodePlex by SharePoint MVPs like Ted Pattison, Andrew Connell, Scot Hillier, and more.</p> <blockquote> <p>STSDEV is a proof-of-concept utility application which demonstrates how to generate Visual Studio project files and solution files to facilitate the development and deployment of templates and components for the SharePoint 2007 platform including Windows SharePoint Services 3.0 (WSS) and Microsoft Office SharePoint Server 2007 (MOSS). Note that the current version of the stsdev utility only supports creating projects with the C# programming language.</p> </blockquote> <p>Keith</p>
2,877
<p>I need some help with XSLT syntax. Here is my scenario, I have an XML file that needs to be transformed in to a different look and feel of XML file, I have several sections where if particular node set don't contain any value the whole section shouldn't be processed.</p> <p>Here is an example of XML:</p> <pre><code>&lt;Dates&gt; &lt;Date&gt; &lt;VALUE1&gt;&lt;/VALUE1&gt; &lt;VALUE2&gt;&lt;/VALUE2&gt; &lt;VALUE3&gt;&lt;/VALUE3&gt; &lt;VALUE4&gt;&lt;/VALUE4&gt; &lt;VALUE5&gt;3333&lt;/VALUE5&gt; &lt;/Date&gt; &lt;Date&gt; &lt;VALUE1&gt;AAAA&lt;/VALUE1&gt; &lt;VALUE2&gt;&lt;/VALUE2&gt; &lt;VALUE3&gt;JJJJ&lt;/VALUE3&gt; &lt;VALUE4&gt;&lt;/VALUE4&gt; &lt;VALUE5&gt;12345&lt;/VALUE5&gt; &lt;/Date&gt; &lt;/Dates&gt; </code></pre> <p><a href="http://img162.imageshack.us/my.php?image=xmlscreenshotgk7.gif" rel="noreferrer">screenshot of xml</a></p> <p>Here is my XSLT with the if statement that don't work right</p> <pre><code>&lt;xsl:for-each select="Level1/Level2/Level3"&gt; &lt;xsl:if test="@VALUE1!=''"&gt; &lt;MyDates&gt; &lt;value_1&gt; &lt;xsl:value-of select="VALUE1"/&gt; &lt;/value_1&gt; &lt;value_2&gt; &lt;xsl:value-of select="VALUE2"/&gt; &lt;/value_2&gt; &lt;value_3&gt; &lt;xsl:value-of select="VALUE3"/&gt; &lt;/value_3&gt; &lt;value_4&gt; &lt;xsl:value-of select="VALUE4"/&gt; &lt;/value_4&gt; &lt;/MyDates&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; </code></pre> <p>So as you can see I basically want all nodes (VALUE1, VALUE2, VALUE3, etc) to have values or else don't process and move on to the next section</p> <p>(If you cannot see the XML come thought, I also made a screen shot)</p>
<p>You are trying to match xml elements with names "Level1", "Level2", etc... that don't exist in the document. Then, you are looking for a VALUE1 attribute on the last element.</p> <p>I <em>think</em> you want something like this:</p> <pre><code>&lt;xsl:for-each select="Dates"&gt; &lt;MyDates&gt; &lt;xsl:for-each select="Date"&gt; &lt;xsl:if test="not(*[.=''])"&gt; &lt;MyDate&gt; &lt;value_1&gt; &lt;xsl:value-of select="VALUE1"/&gt; &lt;/value_1&gt; &lt;value_2&gt; &lt;xsl:value-of select="VALUE2"/&gt; &lt;/value_2&gt; &lt;value_3&gt; &lt;xsl:value-of select="VALUE3"/&gt; &lt;/value_3&gt; &lt;value_4&gt; &lt;xsl:value-of select="VALUE4"/&gt; &lt;/value_4&gt; &lt;/MyDate&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/MyDates&gt; &lt;/xsl:for-each&gt; </code></pre> <p>This will add a new MyDate element as long as <em>every</em> value in the corresponding Date element is not empty.</p> <p>What it does is</p> <ol> <li>Create a new MyDates element for each Dates element.</li> <li>Check each Date element. The <code>*</code> matches all children. <code>[.='']</code> means "is empty". Finally, it wraps all that in a not. This means the if only passes if there is not any child that is empty.</li> <li>If it has no children that are empty, it creates a new MyDate element with a copy of each value.</li> </ol> <p>You may also want to check the W3Schools <a href="http://www.w3schools.com/xsl/default.asp" rel="noreferrer">XSL</a> and <a href="http://www.w3schools.com/xpath/default.asp" rel="noreferrer">XPath</a> tutorials.</p>
<pre><code>&lt;xsl:template match="Dates"&gt; &lt;table border="1"&gt; &lt;tr bgcolor="#9acd32"&gt;&lt;th&gt;NAME&lt;/th&gt;&lt;th&gt;INVALUE&lt;/th&gt;&lt;/tr&gt; &lt;xsl:for-each select="Date"&gt; &lt;xsl:if test="(VALUE1 != '') and (VALUE2 != '') and (VALUE3 != '') and (VALUE4 != '') and (VALUE5 != '')" &gt; &lt;tr&gt;&lt;td&gt;VALUE1&lt;/td&gt;&lt;td&gt;&lt;xsl:value-of select="VALUE1"&gt;&lt;/xsl:value-of&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;VALUE2&lt;/td&gt;&lt;td&gt;&lt;xsl:value-of select="VALUE2"&gt;&lt;/xsl:value-of&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;VALUE3&lt;/td&gt;&lt;td&gt;&lt;xsl:value-of select="VALUE3"&gt;&lt;/xsl:value-of&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;VALUE4&lt;/td&gt;&lt;td&gt;&lt;xsl:value-of select="VALUE4"&gt;&lt;/xsl:value-of&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;VALUE5&lt;/td&gt;&lt;td&gt;&lt;xsl:value-of select="VALUE5"&gt;&lt;/xsl:value-of&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/table&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
45,644
<p>I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? </p> <pre><code>for (var i = 0; i &lt; 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } </code></pre> <p>vs</p> <pre><code>function myEventHandler() { // do something } for (var i = 0; i &lt; 1000; ++i) { myObjects[i].onMyEvent = myEventHandler; } </code></pre> <p>The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?</p>
<p>The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function:</p> <pre><code>for (var i = 0; i &lt; 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } </code></pre> <p>You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope (<a href="http://www.google.com/search?q=javascript+closure" rel="noreferrer">closure</a>). The following seems faster, on the other hand, because it simply assigns the <em>same</em> function reference to the array elements throughout the loop:</p> <pre><code>function myEventHandler() { // do something } for (var i = 0; i &lt; 1000; ++i) { myObjects[i].onMyEvent = myEventHandler; } </code></pre> <p>If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version:</p> <pre><code>var handler = function() { // do something }; for (var i = 0; i &lt; 1000; ++i) { myObjects[i].onMyEvent = handler; } </code></pre> <p>In short, there is no observable performance cost to using anonymous over named functions.</p> <p>As an aside, it may appear from above that there is no difference between:</p> <pre><code>function myEventHandler() { /* ... */ } </code></pre> <p>and:</p> <pre><code>var myEventHandler = function() { /* ... */ } </code></pre> <p>The former is a <em>function declaration</em> whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “<a href="http://www.dustindiaz.com/javascript-function-declaration-ambiguity/" rel="noreferrer">JavaScript function declaration ambiguity</a>”.</p> <p>The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit <a href="http://jsperf.com/named-or-anonymous-functions/12" rel="noreferrer">the JS Perf site</a></p>
<p>Anonymous objects are faster than named objects. But calling more functions is more expensive, and to a degree which eclipses any savings you might get from using anonymous functions. Each function called adds to the call stack, which introduces a small but non-trivial amount of overhead.</p> <p>But unless you're writing encryption/decryption routines or something similarly sensitive to performance, as many others have noted it's always better to optimize for elegant, easy-to-read code over fast code.</p> <p>Assuming you are writing well-architected code, then issues of speed should be the responsibility of those writing the interpreters/compilers.</p>
10,636
<p>I've got two directories containing ~20 GB of music files (mostly mp3, some ogg), and I would like to detect all duplicate songs. There are two complicating factors:</p> <ol> <li>A song may have different filenames in the two directories.</li> <li>Two files containing the same song may have different ID3 tags and thus have different checksums.</li> </ol> <p>What is a good approach to solving this?</p>
<p>The way I have gone about this in the past is to use genpuids that come from Music IP. The closed source software creates an audio fingerprint of a file regardless of format, id3, checksum etc. </p> <p>More information can be found <a href="http://musicbrainz.org/doc/genpuid" rel="nofollow noreferrer">here</a>.</p> <p>This should ensure the most amount of positive duplicate matches and minimize false positives. It can also correctly tag incorrect id3 tags.</p>
<p>Perhaps the <a href="http://www.last.fm/api/show?service=356" rel="nofollow noreferrer">Last.fm API</a> would be useful. It includes a track.getInfo call which returns XML including the track's length, artist name, track number, etc. You could compare tracks and see if they have more than N fields equal and if so, assume they're the same track.</p> <p>I have no idea about whether they're going to be OK with you submitting API requests for 40gb of music, though.</p>
27,548
<p>I just launched my <a href="http://www.dudlers.com" rel="noreferrer">tiny webapp</a> on my humble dedicated server (Win2003)... running ASP.NET MVC, LINQ2SQL, SQL Express 2005, and IIS6 (setup with <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true" rel="noreferrer">wildcard mapping</a>)</p> <p>The website runs smoothly 90% of the times. However, on <em>relatively</em> high traffic, LINQ2SQL throws the error: Specified cast is not valid</p> <p>This error is ONLY thrown at high traffic. I have <strong>NO IDEA</strong> how or exactly why this happens. Caching did not remove this problem entirely.</p> <p>Anyone seen this problem before? are there any secret SQL Server tweaking I should've done? Or at least, <strong>any ideas on how to diagnose this issue?</strong> because i'm out!</p> <p>Naimi</p> <p>Stacktrace (from Event Log):</p> <pre> at System.Data.SqlClient.SqlBuffer.get_SqlGuid() at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i) at Read_Friend(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at Dudlers.Web.Models.DudlersDataContext.GetFriendRequests(Guid userId) in C:\Web\Models\DudlersDataContext.cs:line 562 at Dudlers.Web.Controllers.BaseController.View(String viewName, String masterName, Object viewData) in C:\Web\Controllers\BaseController.cs:line 39 at System.Web.Mvc.Controller.View(String viewName) at Dudlers.Web.Controllers.CatController.Index() in C:\Web\Controllers\CatController.cs:line 25 at lambda_method(ExecutionScope , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(MethodInfo methodInfo, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.b__8() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.c__DisplayClassd.b__a() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(MethodInfo methodInfo, IDictionary`2 parameters, IList`1 filters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) </pre>
<p>We had a similar problem with LINQ that we get "Unable to cast object of type 'System.Int32' to type 'System.String'" and "Specified cast is not valid."</p> <p>Examples of stacktraces</p> <pre><code>System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at System.Data.SqlClient.SqlBuffer.get_String() at System.Data.SqlClient.SqlDataReader.GetString(Int32 i) at Read_Person(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at RF.Ias.Services.Person.BusinessLogic.PersonTransactionScripts.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact) at CompositionAopProxy_5b0727341ad64f29b816c1b73d11dd44.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact) at RF.Ias.Services.Person.ServiceImplementation.PersonService.GetPersons(GetPersonRequest request) System.InvalidCastException: Specified cast is not valid. at System.Data.SqlClient.SqlBuffer.get_Int32() at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) at Read_GetRolesForOrganisationResult(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at RF.Ias.Services.Role.DataAccess.RoleDataAccess.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32&amp; recordCount) at RF.Ias.Services.Role.BusinessLogic.RoleTransactionScripts.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32&amp; recordCount) at CompositionAopProxy_4bd29c6074f54d10a2c09bd4ab27ca66.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32&amp; recordCount) at RF.Ias.Services.Role.ServiceImplementation.RoleService.GetRolesForOrganisation(GetRolesForOrganisationRequest request) </code></pre> <p>We used to get these exceptions if we first got a exception like this "System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first." or " A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)".</p> <p>The first exception occur for a different instance of the DataCOntext then for all those that then are following.</p> <p>After some research and asking in this <a href="https://stackoverflow.com/questions/780447/is-it-possible-to-gets-sql-connection-leaks-using-linq/780669#780669">thread</a> , I found that the reason was that I did not dispose the DataContexts. After I started to do that, it dissappered.</p>
<p>Sounds like maybe a race condition, or perhaps a <em>rare</em> bug that is only <em>correlated</em> with high traffic because that when most of your requests occur.</p>
41,199
<p>I'm trying to localize my aspx pages. I'm done with content localization using L10n features provided by .net f/w, like resource files. But I'm finding it difficult to set local data in page titles. </p> <p>Most of the browsers, including IE and FF, shows content on window title with some boxes (FF will show properly localized text in tab, IE doesn't even do that). But its working fine in safari (on windows). </p> <p>When I did a research it seems like this issue exits ONLY for some of the languages. For example, the <a href="http://www.bbc.co.uk/hindi/" rel="nofollow noreferrer">Hindi version of BBC</a> shows the title with boxes. But <a href="http://news.bbc.co.uk/hi/arabic/news/" rel="nofollow noreferrer">Arabic version</a> shows the localized text in title.</p> <p>Can somebody please tell me why this is happening? How we can solve this issue?</p> <p>Note: My site is using Asp.net 2.0 / IIS</p>
<p>I suspect this is a typeface issue. The browser title bar and other window ornaments are usually rendered by your OS, not by the browser itself, so if you've configured Windows to use a typeface that doesn't support the additional character glyphs required for Hindi, Arabic, etc., then you'll get the boxes instead. Within your actual pages, you're probably using a typeface which does include support for all these extended characters, which is why you're only seeing the problem on the window titles.</p> <p>Safari uses its own rendering engine for everything including the window chrome, which is why it doesn't look like a normal Windows app, and why your localized titles are working.</p> <p>You might want to try changing your Windows "Active Title Bar" font (under Display Properties, Appearance, Advanced) to something like Arial which covers the full set of Unicode characters, and see if this resolves the problem? </p>
<p>It's a font issue, and not something you can fix on the server side. If the font used for title bar text is missing glyphs present in the font used for tabs, then it will appear correctly in the tab but not the title bar. That would also explain why Safari works -- it uses its own fonts and font rendering system for everything.</p>
21,951
<p>In a world where IE didn't exist, what things would be easier, less hacky, less buggy and generally more used.</p> <p>What could the internet have been if all features were available cross browser?</p> <p>List one point per post.</p> <p>This is community wiki, so feel free to amend the question/answers for clarity.</p>
<p>1) :before and :after psuedo elements.</p> <p>2) 'content' attribute.</p> <p>3) :hover on any element (not just anchors).</p>
<p>Lets starts with <del>javascript</del> <a href="http://en.wikipedia.org/wiki/ECMAScript" rel="nofollow noreferrer">EcmaScript</a>: today you have to make one version for Mozilla/Opera/Safari and another version for IE.</p> <p>Both Opera and Firefox support some CSS3. Guess what: IE don't. What about the CSS2-standard? No, IE still not ready to use that one. I'm not sure about how much of the CSS1-standard IE7 support, but I do know that IE6 didn't support it completely.</p> <p>Today you can't use xhtml properly: IE doesnt suppert documents beeing served as xhtml.. </p> <p>A solution many webdevelopers does today, is to create a lot of nested &lt;div>-tags to force IE to display the page properly. Most modern browser (not IE6) support css-rules on the 'html' and 'body'-tag, and therefor div-mania can be avoided. (Well; div-mania can be avoided on IE today, so this last point isn't that relevant)</p> <p>PNG-pictures is also an issue, as Rich Bradshaw pointed out.</p>
43,260
<p>I am hosting a WCF service in a Windows Service on one of our servers. After making it work in basicHttpBinding and building a test client in .NET (which finally worked) I went along and try to access it from PHP using the SoapClient class. The final consumer will be a PHP site so I need to make it consumable in PHP.</p> <p>I got stumped when I had to enter the WSDL url in the constructor of the SoapClient class in the PHP code. Where is the WSDL? All I have is :</p> <p><a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> and <a href="http://172.27.7.123:8000/WordService/mex" rel="noreferrer">http://172.27.7.123:8000/WordService/mex</a></p> <p>None of these do not expose WSDL.</p> <p>Being a newbie in WCF I might have asked a dumb thing (or I might have a wrong assumption somewhere). Please be gentle :D</p> <p>And no, <a href="http://172.27.7.123:8000/WordService?wsdl" rel="noreferrer">http://172.27.7.123:8000/WordService?wsdl</a> does not show anything different than <a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> :(</p> <p>Am I forced to host it in IIS? Am I forced to use a regular WebService?</p>
<p>This might help:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms734765.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms734765.aspx</a></p> <p>In a nutshell you need to configure your service endpoints and behaviour. Here is a minimal example:</p> <pre><code>&lt;system.serviceModel&gt; &lt;services&gt; &lt;service &lt;!-- Namespace.ServiceClass implementation --&gt; name="WcfService1.Service1" &lt;!-- User behaviour defined below --&gt; behaviorConfiguration="SimpleServiceBehaviour"&gt; &lt;endpoint address="" binding="basicHttpBinding" &lt;!-- Namespace.Interface that defines our service contract --&gt; contract="WcfService1.IService1"/&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="SimpleServiceBehaviour"&gt; &lt;serviceMetadata &lt;!-- We allow HTTP GET --&gt; httpGetEnabled="true" &lt;!-- Conform to WS-Policy 1.5 when generating metadata --&gt; policyVersion="Policy15"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Don't forget to remove the XML comments as they're invalid where they are.</p>
<p>Please see this link:</p> <p><a href="http://keithelder.net/blog/archive/2008/01/17/Exposing-a-WCF-Service-With-Multiple-Bindings-and-Endpoints.aspx" rel="nofollow noreferrer">Exposing a WCF Service With Multiple Bindings and Endpoints</a></p> <pre> Unlike previous ASMX services, the WSDL (web service definition language) for WCF services is not automatically generated. The previous image even tells us that "Metadata publishing for this service is currently disabled.". This is because we haven't configured our service to expose any meta data about it. To expose a WSDL for a service we need to configure our service to provide meta information. Note: The mexHttpBinding is also used to share meta information about a service. While the name isn't very "gump" it stands for Meta Data Exchange. </pre>
20,274
<p>I have successfully added a custom assembly, added it to the report using <code>AddTrustedCodeModuleInCurrentAppDomain</code>. I am executing the report in the current appdomain.</p> <p>When I try to access SQL I get reporting services <code>System.Data.SqlClient.SqlClientPermission failed.</code> I have tried adding <code>System.Data</code> to the trusted assemblies as above but it doesn't help.</p> <p>How do I ensure that this permission is present?</p>
<p>If you're running IIS6 the guys at OrcsWeb have a nice wee article -</p> <blockquote> <p><a href="http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx</a></p> </blockquote> <p>We have customers running the port80 software because they get more control:</p> <blockquote> <p><a href="http://www.port80software.com/products/zipenable/" rel="nofollow noreferrer">http://www.port80software.com/products/zipenable/</a> <a href="http://www.port80software.com/products/httpzip/" rel="nofollow noreferrer">http://www.port80software.com/products/httpzip/</a></p> </blockquote>
<p>Check out the JSCompress task in the MSBuild Community Tasks (<a href="http://msbuildtasks.tigris.org/" rel="nofollow noreferrer">http://msbuildtasks.tigris.org/</a>). It'll strip out the whitespace from a JS file for you.</p>
16,784
<p>In ASP.NET MVC, we're required to use the suffix "Controller" for all controllers. This seems unnecessarily restrictive - is there a technical reason for it? </p> <p>I'm mostly just curious, but can see situations where more flexible naming rules could improve code organization. Couldn't the discovery of possible controller classes be easily made using reflection to search for <code>Controller</code> derived classes? Or require that controller classes be marked with a <code>ControllerAttribute</code>? </p>
<p>The MVC community is heavily influenced by <a href="http://www.rubyonrails.org/" rel="nofollow noreferrer">Ruby on Rails</a>, which values "<a href="http://en.wikipedia.org/wiki/Convention_over_Configuration" rel="nofollow noreferrer">convention over configuration</a>". By just naming things consistently, the application can run with zero configuration.</p>
<p>One of the benefits of this convention is that it's common to have a URL segment, controller, and a model class all have the same name.</p> <p>URL: /product/ Controller: Product : Controller Model: Product</p> <p>This would cause a naming conflict. So we made a convention to have controller names suffixed with "Controller" to avoid this conflict. However, you can override this behavior via our extensibility APIs.</p>
33,364
<p>I've been thinking, just how deep into everything do you have to go before something is automatically thread-safe?</p> <p>Quick example:</p> <pre><code>int dat = 0; void SetInt(int data) { dat = data; } </code></pre> <p>.. Would this method be considered threadsafe? I ussually wrap all my set-methods in mutex'es, just to be sure, but everytime I do so I can't help but to think that it's a useless perfomance overhead. I guess it all breaks down to the assembly the compiler generates? When are threads able to break into code? Per assembly-instruction or per code-line? Can a thread break in during the set-up or destruction of a method-stack? Would an instruction like i++ be considered threadsafe - and if not, what about ++i?</p> <p>Lotsa questions here - and I dont expect a direct answer, but some info on the subject would be great :)</p> <p>[UPDATE] Since it's clear for me now (thx to you guys &lt;3 ), that the only atomic-guarenteed stuff in threading is an assembly instruction, I know came to think: What about mutex- and semaphore-wrapperclasses? Classes like this ussually use methods which makes callstacks - and custom semaphoreclasses that ussually utilizes some kind of internal counter can not be guarenteed to be atomic / threadsafe (whatever you wanna call it, as long as you know what I mean, I dont care :P )</p>
<p>In general, a thread context switch can happen at <em>any</em> time, between any two assembly language instructions. The CPU is completely unaware of how the assembly language maps to your source code. Furthermore, with multiple processors, other instructions can be executing on a different CPU core at the very same time.</p> <p>Having said that, in the example you gave the assigment of a CPU-sized word to a memory location is generally an atomic operation. This means that from the point of view of an observer (another thread), the assignment has either not started yet, or has been completed. There is no in-between state.</p> <p>There are many subtleties in multiprocessing, so it's good to be aware of the possibilities for the hardware and OS environment in which you're working.</p>
<p>The above code is threadsafe!</p> <p>The main thing to look out for is static (i.e.shared) variables.</p> <p>These are not thread safe unless update is managed by some sort of locking machanism such as a mutex. The same obviously applies to any OS provided shared memory.</p> <p>So as long as your code has no static data it will be thread safe in itself.</p> <p>You then need to check whether any libraries or system calls you use are thread safe. This is stated explicitly in the documentation of most system calls.</p>
47,262
<p>I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).</p> <p>The first one registers ok, then multiple ones fail, saying class already registered - as expected.</p> <p>My question is - is this bad? I was thinking of using a hash table to store the ATOM results in, to look up before calling RegisterWindow, but it seems Windows does this already? </p>
<p>You can test if the window class was previously registered calling <strong>GetClassInfoEx</strong>.</p> <blockquote> <p>If the function finds a matching class and successfully copies the data, the return value is nonzero.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx</a></p> <p>This way you can conditionally register the window class based on the return of <strong>GetClassInfoEx</strong>.</p>
<p>Well, you might be able to avoid a call down into the kernel - RegisterClass seems to need to get down there - but window classes are per-process and per-module, so you shouldn't hurt anything by registering a class multiple times.</p> <p>Given that there aren't generally that many classes, I wouldn't be too surprised to find it was actually implemented as a linked-list. You might get a little gain by looking it up in a hash table, but you'd probably be better off doing it as a simple boolean.</p>
18,182
<p>A few quick searches discovered that I'm obviously <a href="http://morethanseven.net/2008/10/13/unit-testing-css-looking-solution/" rel="noreferrer">not the</a> <a href="http://www.thoughtballoon.co.uk/blog/2008/11/11/example-css-style-guide-unit-testing-for-css" rel="noreferrer">first person</a> to have the thought <strong>"Can I unit test my CSS?"</strong>. </p> <p>I'm wondering if anyone here has taken on CSS Unit Testing successfully? If you've tried and failed, or just have your own theories, please tell me why it (apparently) hasn't been done yet?</p>
<p>You could use Selenium, which is a web testing framework. This way you could assert what styles are to be applied to elements in the DOM etc. </p> <p><a href="http://docs.seleniumhq.org/" rel="noreferrer">Selenium</a></p> <p>Otherwise, not sure what your aim is. Unit testing is, as the name suggests, testing 'Units', and to me, this only makes sense with code, not css.</p>
<p>Currently, understanding whether CSS is working properly or not is visually determined. So far, the best way to test it is through installing multiple browsers on your dev machine. Start using tools like Firebug and Web Developer on Firefox, and forget about Unit testing CSS until it becomes Turing complete. :-)</p>
44,542
<p>Let's say I have a generic pointer in objective-c. This pointer could either be a <code>Class</code> object, or it could be an <i>instance</i> of that class. Is there any way to tell the difference between the two?</p> <p>Example:</p> <pre><code> id pointerA = [someClass class]; id pointerB = [[someClass alloc] init]; bool pointerAIsAClass = is_this_a_Class(pointerA); // should be true bool pointerBIsAClass = is_this_a_Class(pointerB); // should be false </code></pre> <p>How would I write the <code><code>is_this_a_Class</code></code> function so that it returns the proper <code>bool</code> value?</p> <pre><code>bool is_this_a_Class(id somePointer) { // your code goes here }</code></pre>
<p>The most correct way is to check the class of the object, and see if it's a metaclass:</p> <pre><code>BOOL object_isClass(id object) { return class_isMetaClass(object_getClass(object)); } </code></pre> <p>There are more answers here: <a href="https://stackoverflow.com/questions/6536244/check-if-object-is-class-type">Check if object is Class type</a></p>
<p>I don't see a better way, and this isn't foolproof, but this should work:</p> <pre><code>BOOL pointer_isClass(id object) { return [object respondsToSelector:@selector(instancesRespondToSelector:)]; } </code></pre> <p>Since, theoretically, only <code>Class</code> objects would respond to the <code>-instancesRespondToSelector:</code> message this should work. Outside of an actual <code>objc_*</code> call though I don't see any real API for this.</p> <p><strong>UPDATE:</strong> <br>After reading Giao's answer another thought came to me, test the pointer's response to the <code>-class</code> method. Calling <code>-class</code> on a class object should be equivalent to calling <code>-self</code> on an object instance but would return another object on an object instance.</p> <pre><code>BOOL pointer_isClass(id object) { return object == [object class]; } </code></pre> <p>I think this should be more foolproof, especially in the case where an object instance implements <code>-instancesRespondToSelector:</code> this one should work 100% of the time.</p>
46,308
<p>I want to write a real-time analysis tool for wireless traffic.</p> <p>Does anyone know how to read from a promiscuous (or sniffing) device in C? </p> <p>I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here.</p>
<p>On Linux you use a PF_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode: </p> <pre><code>s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) </code></pre> <p>This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the <A HREF="http://en.wikipedia.org/wiki/Berkeley_Packet_Filter" rel="noreferrer">Berkeley Packet Filter</A>. BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as: </p> <pre><code>ldh = load halfword (from packet) jeq = jump if equal ret = return with exit code </code></pre> <p>BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, ). (WARNING: The kernel takes a struct sock_fprog, not a struct bpf_program, do not mix those up or your program will not work on some platforms).</p> <p>For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. <A HREF="http://www.tcpdump.org/pcap.htm" rel="noreferrer">libpcap</A> will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see.</p> <p>libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else.</p>
<p>Why wouldn't you use something like <a href="http://www.wireshark.org/" rel="nofollow noreferrer">WireShark</a>?</p> <p>It is open source, so at least you could learn a few things from it if you don't want to just use it.</p>
14,008
<p>I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (<code>Entity</code>) that have it's <code>id</code> on several other tables as the Foreign Key <code>entity_id</code></p> <p>Some tables are one to one relations (Like a <code>Company</code> is one <code>Entity</code>) and some are one to many (<code>Entity</code> can have several <code>Addresses</code>) and so on.</p> <p><em>I won't/can't change the database model</em>, so this is the structure.</p> <p>I have been using <code>saveAll()</code> to save data on those tables with input names like:</p> <pre><code>Entity.type='x' (hidden inside the view) Company.name Address.0.street Address.0.city Address.1.street Address.1.city ... and so on ... </code></pre> <p>and my save all is doing all the hard job, <code>BEGIN TRANSACTION</code>, all <code>INSERT</code>s and a final <code>COMMIT</code> ...</p> <p>But now I've created a <code>EntityCategory</code> that is a n to n relation and created the full <code>HABTM</code> relation inside the model.</p> <p>It works when I <code>save()</code> it but just the <code>HABTM</code> relation, and it saves everthing when I use <code>saveAll()</code> (just as before) except for the <code>HABTM</code> relation.</p> <p>Am I missing something ? How I make this work correctly ? I am using the following code today:</p> <pre><code>if (!empty($this-&gt;data)) { $this-&gt;Entity-&gt;saveAll($this-&gt;data); $this-&gt;Entity-&gt;save($this-&gt;data); } </code></pre> <p>The <code>saveAll()</code> saves all data in several tables, saves the id in <code>Entity-&gt;id</code> and the <code>save()</code> saves the <code>HABTM</code> relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model.</p> <p>Is this the best way to use it? Is there a <em>correct</em> way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?</p>
<p>This is fixed if you download the <a href="http://cakephp.org/downloads/index/nightly/1.2.x.x" rel="nofollow noreferrer">nightly</a>.</p> <p>Be careful though, something else might break.</p>
<p>The problem with saveAll() and HABTM associations is a known CakePHP <a href="https://trac.cakephp.org/ticket/4389" rel="nofollow noreferrer">issue</a>, and has not been resolved as of 1.2 RC2. </p> <p>As fas as best pratices for saving related model data goes, according to the CakePHP <a href="http://book.cakephp.org/view/75/Saving-Your-Data#Saving-Related-Model-Data-hasOne-hasMany-belongsTo-84" rel="nofollow noreferrer">cookbook</a>:</p> <blockquote> <p>"When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation."</p> </blockquote> <p>However, using saveAll() and save() should work, and IMHO is a more flexible/generic solution.</p>
17,775
<p>When running wsdl.exe on a WSDL I created, I get this error:</p> <blockquote> <p>Error: Unable to import binding 'SomeBinding' from namespace 'SomeNS'.</p> <ul> <li>Unable to import operation 'someOperation'.</li> <li>These members may not be derived.</li> </ul> </blockquote> <p>I'm using the document-literal style, and to the best of my knowledge I'm following all the rules.</p> <p>To sum it up, I have a valid WSDL, but the tool doesn't like it.</p> <p>What I'm looking for is if someone has lots of experience with the wsdl.exe tool and knows about some secret gotcha that I don't.</p>
<p>I have came across to the same error message. After digging for a while, found out that one can supply xsd files in addition to wsdl file. So included/imported .xsd files in addition to .wsdl at the end of the wsdl command as follows:</p> <blockquote> <p>wsdl.exe myWebService.wsdl myXsd1.xsd myType1.xsd myXsd2.xsd ...</p> </blockquote> <p>Wsdl gave some warnings but it did create an ok service interface.</p>
<p>In case someone hits this wall, here is what caused the error in my case:</p> <p>I have an operation:</p> <pre><code>&lt;wsdl:operation name="FormatReport"&gt; &lt;wsdl:documentation&gt;Runs a report, which is returned as the response&lt;/wsdl:documentation&gt; &lt;wsdl:input message="FormatReportRequest" /&gt; &lt;wsdl:output message="FormatReportResponse" /&gt; &lt;/wsdl:operation&gt; </code></pre> <p>which takes an input:</p> <pre><code>&lt;wsdl:message name="FormatReportRequest"&gt; &lt;wsdl:part name="parameters" element="reporting:FormatReportInput" /&gt; &lt;/wsdl:message&gt; </code></pre> <p>and another operation:</p> <pre><code>&lt;wsdl:operation name="FormatReportAsync"&gt; &lt;wsdl:documentation&gt;Creates and submits an Async Report Job to be executed asynchronously by the Async Report Windows Service.&lt;/wsdl:documentation&gt; &lt;wsdl:input message="FormatReportAsyncRequest" /&gt; &lt;wsdl:output message="FormatReportAsyncResponse" /&gt; &lt;/wsdl:operation&gt; </code></pre> <p>taking an input:</p> <pre><code> &lt;wsdl:message name="FormatReportAsyncRequest"&gt; &lt;wsdl:part name="parameters" element="reporting:FormatReportInputAsync" /&gt; &lt;/wsdl:message&gt; </code></pre> <p>And the input elements are instances of two types:</p> <pre><code>&lt;xsd:element name="FormatReportInput" type="reporting:FormatReportInputType"/&gt; &lt;xsd:element name="FormatReportInputAsync" type="reporting:FormatReportAsyncInputType"/&gt; </code></pre> <p>Here is the catch - the <code>reporting:FormatReportAsyncInputType</code> type extends (derives from) the <code>reporting:FormatReportInputType</code> type. That's what seems to confuse the tool and cause the "These members may not be derived." error. You can go around that following teh suggestion in the accepted answer.</p>
10,303
<p>I am trying to loop on a recordset returned from db2 using a .wsf file and vbscript .</p> <p>the vbscript libfile(lib.vbs) is as follows</p> <pre><code>'*************** Const ADOCon="Provider=IBMDADB2.1;Password=*****;User ID=*****;Data Source=yourdatasourc;" '************************ 'ADO environment is Initialised here '************************* Function ADOINI(strDB2Cn) With objConnection .Open strSQLCn .CursorLocation=adUseClient End With If objConnection.Errors.Count &gt; 0 Then ErrorOut "Conncetion has Failed." End If With objCommand .ActiveConnection = objConnection .CommandType = adCmdText End With End Function '******************** 'Execute ADO Comand 'strSQL - SQL Statment to execute 'Return ADO RecordSet. '******************************* Function Exec(strSQL) objCommand.CommandText = strSQL Exec=objCommand.Execute End Function '****************************************** Function ErrorOut(errMsg) Wscript.StdErr.Write Now()&amp;" "&amp;errMsg&amp;vbCrLf End Function '**************** Function StdOut(msg) WScript.StdOut.Write Now()&amp;" "&amp;msg&amp;vbCrLf End Function '************************ </code></pre> <p>I am using a trial.wsf file , to getback a recordset on which i am trying to loop </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;package xmlns="http://schemas.microsoft.com/WindowsScriptHost"&gt; &lt;job id="main"&gt; &lt;object id="objConnection" progid="ADODB.Connection" /&gt; &lt;object id="objCommand" progid="ADODB.Command" /&gt; &lt;object id="objError" progid="ADODB.Error" /&gt; &lt;reference object="ADODB.Connection" /&gt; &lt;reference object="ADODB.Command" /&gt; &lt;reference object="ADODB.Error" /&gt; &lt;script language="VBScript" src="lib.vbs"&gt; ADOINI(ADOCon) Set objRS = Exec("SELECT REF_CRSETTINGS.NAME, REF_CRSETTINGS.VALUE FROM WMRCR.REF_CRSETTINGS REF_CRSETTINGS WHERE TRIM(UPPER(REF_CRSETTINGS.CATEGORY)) IN ('SAMPLE_SETTINGS') ORDER BY REF_CRSETTINGS.CRSETTINGSCODE") ' the above recordset is a name value pair based on the category StdOut objRS("NAME").Value 'this worked fine objRS.MoveNext ' this doesnt work neither does check for EOF or BOF &lt;/script&gt; &lt;/job&gt; &lt;/package&gt; </code></pre> <p>My intial thinking was that the cursor type might be wrong ,<br> but i am not even able to set the cursosr type to dynamic , got a vbscript error not supported . </p> <p>maybe its an issue with the provider , but am not able to confirm that . </p> <p>I want to do something like this , but am not able to loop on the recordset .. </p> <pre><code> Do While Not objRS.EOF Select Case UCase(trim(objRS("NAME").Value)) Case "SOAPSERVER" SOAPSERVER=objRS("VALUE").Value Case "SOAPMESSAGE" SOAPMESSAGE=objRS("VALUE").Value Case "SOAPACTION" SOAPACTION=objRS("VALUE").Value Case Else ErrorOut "Error: InCorrect Value" End Select objRS.MoveNext Loop </code></pre> <p>Am sure there is something basic/silly mistake over here , not well versed with wsf and scripting .. </p>
<p>Check out the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/CascadingDropDown/CascadingDropDown.aspx" rel="nofollow noreferrer">CascadingDropDown Control</a>. It's part of the ASP.NET Ajax Control Toolkit.</p>
<p>You can use onchange event of one drop down and on the event you can change the another dropdown contents using ajax</p>
49,930
<p>I'm using this XPath to get the value of a field:</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value </code></pre> <p>I get several results, but I only want the first. Using</p> <pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value[1] </code></pre> <p>Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:</p> <pre><code>alert("val " + val.snapshotItem); </code></pre> <p>But I think that's for the node, rather than the string.</p>
<p>For the XPath, try:</p> <pre> //input[@type="hidden" and @name="val" and position() = 1]/@value </pre> <p>For use in a GreaseMonkey script, do something like this:</p> <pre><code>var result = document.evaluate( "//input[@type='hidden' and @name='var' and position()=1]/@value", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); var hiddenval = result.snapshotItem(0); if (hiddenval) alert("Found: " + hiddenval.nodeValue); else alert("Not found."); </code></pre> <p>Strictly speaking: Using <code>"position()=1"</code> in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via <code>snapshotItem(0)</code>). But why build a larger result set than you really need.</p> <p>EDIT: Using an XPath result of the <code>ORDERED_NODE_SNAPSHOT_TYPE</code> type makes sure you get the nodes in <em>document order</em>. That means the first node of the result will also be the first node in the document.</p>
<p>One possibility is to include jQuery in your scripts. This will provide a simpler syntax for accessing elements.</p> <pre><code>// ==UserScript== // @name MyScript // @namespace http://example.com // @description Example // @include * // // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js // ==/UserScript== var input = $("input[type='hidden'][name='var']"); if (input) { alert("Found: " + input.val()); } else { alert("Not found."); } </code></pre>
33,357
<p>I can detect when the content of an iframe has loaded using the <em>load</em> event. Unfortunately, for my purposes, there are two problems with this:</p> <ul> <li>If there is an error loading the page (404/500, etc), the load event is never fired.</li> <li>If some images or other dependencies failed to load, the load event is fired as usual.</li> </ul> <p>Is there some way I can reliably determine if either of the above errors occurred?</p> <p>I'm writing a semi-web semi-desktop application based on Mozilla/XULRunner, so solutions that only work in Mozilla are welcome.</p>
<p>If you have control over the iframe page (and the pages are on the same domain name), a strategy could be as follows:</p> <ul> <li>In the parent document, initialize a variable <code>var iFrameLoaded = false;</code></li> <li>When the iframe document is loaded, set this variable in the parent to <code>true</code> calling from the iframe document a parent's function <code>(setIFrameLoaded();</code> for example).</li> <li>check the <code>iFrameLoaded</code> flag using the <code>timer</code> object (set the timer to your preferred timeout limit) - if the flag is still false you can tell that the iframe was not regularly loaded.</li> </ul> <p><em>I hope this helps.</em></p>
<p>Have a id for the top most (body) element in the page that is being loaded in your iframe.</p> <p>on the Load handler of your iframe, check to see if getElementById() returns a non null value. If it is, iframe has loaded successfully. else it has failed.</p> <p>in that case, put frame.src="about:blank". Make sure to remove the loadhandler before doing that.</p>
49,170
<p>I have a <a href="http://en.wikipedia.org/wiki/WiX" rel="nofollow noreferrer">WiX</a> installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so:</p> <pre><code>&lt;CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/&gt; &lt;CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/&gt; &lt;CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/&gt; &lt;CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/&gt; &lt;CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/&gt; </code></pre> <p>And eight within the <code>InstallExecuteSequence</code>, like so:</p> <pre><code>&lt;Custom Action="SetForRollbackDo" After="InstallFiles"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="RollbackDo" After="SetForRollbackDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="SetForDo" After="RollbackDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="Do" After="SetForDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="SetForRollbackUndo" After="InstallInitialize"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="RollbackUndo" After="SetForRollbackUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="SetForUndo" After="RollbackUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="Undo" After="SetForUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; </code></pre> <p>Is there a better way?</p>
<p>I came across the same problem when writing WiX installers. My approach to the problem is mostly like what Mike suggested and I have a blog post <em><a href="http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/" rel="nofollow">Implementing WiX custom actions part 2: using custom tables</a></em>.</p> <p>In short, you can define a custom table for your data:</p> <pre class="lang-xml prettyprint-override"><code>&lt;CustomTable Id="LocalGroupPermissionTable"&gt; &lt;Column Id="GroupName" Category="Text" PrimaryKey="yes" Type="string"/&gt; &lt;Column Id="ACL" Category="Text" PrimaryKey="no" Type="string"/&gt; &lt;Row&gt; &lt;Data Column="GroupName"&gt;GroupToCreate&lt;/Data&gt; &lt;Data Column="ACL"&gt;SeIncreaseQuotaPrivilege&lt;/Data&gt; &lt;/Row&gt; &lt;/CustomTable&gt; </code></pre> <p>Then write a single immediate custom action to schedule the deferred, rollback, and commit custom actions:</p> <pre class="lang-c prettyprint-override"><code>extern "C" UINT __stdcall ScheduleLocalGroupCreation(MSIHANDLE hInstall) { try { ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.deferred", L"create"); ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.rollback", L"create"); } catch( CMsiException &amp; ) { return ERROR_INSTALL_FAILURE; } return ERROR_SUCCESS; } </code></pre> <p>The following code shows how to schedule a single custom action. Basically you just open the custom table, read the property you want (you can get the schema of any custom table by calling <strong>MsiViewGetColumnInfo()</strong>), then format the properties needed into the <strong>CustomActionData</strong> property (I use the form <code>/propname:value</code>, although you can use anything you want).</p> <pre class="lang-c prettyprint-override"><code>void ScheduleAction(MSIHANDLE hInstall, const wchar_t *szQueryString, const wchar_t *szCustomActionName, const wchar_t *szAction) { CTableView view(hInstall,szQueryString); PMSIHANDLE record; //For each record in the custom action table while( view.Fetch(record) ) { //get the "GroupName" property wchar_t recordBuf[2048] = {0}; DWORD dwBufSize(_countof(recordBuf)); MsiRecordGetString(record, view.GetPropIdx(L"GroupName"), recordBuf, &amp;dwBufSize); //Format two properties "GroupName" and "Operation" into //the custom action data string. CCustomActionDataUtil formatter; formatter.addProp(L"GroupName", recordBuf); formatter.addProp(L"Operation", szAction ); //Set the "CustomActionData" property". MsiSetProperty(hInstall,szCustomActionName,formatter.GetCustomActionData()); //Add the custom action into installation script. Each //MsiDoAction adds a distinct custom action into the //script, so if we have multiple entries in the custom //action table, the deferred custom action will be called //multiple times. nRet = MsiDoAction(hInstall,szCustomActionName); } } </code></pre> <p>As for implementing the deferred, rollback and commit custom actions, I prefer to use only one function and use <strong>MsiGetMode()</strong> to distinguish what should be done:</p> <pre class="lang-c prettyprint-override"><code>extern "C" UINT __stdcall LocalGroupCustomAction(MSIHANDLE hInstall) { try { //Parse the properties from the "CustomActionData" property std::map&lt;std::wstring,std::wstring&gt; mapProps; { wchar_t szBuf[2048]={0}; DWORD dwBufSize = _countof(szBuf); MsiGetProperty(hInstall,L"CustomActionData",szBuf,&amp;dwBufSize); CCustomActionDataUtil::ParseCustomActionData(szBuf,mapProps); } //Find the "GroupName" and "Operation" property std::wstring sGroupName; bool bCreate = false; std::map&lt;std::wstring,std::wstring&gt;::const_iterator it; it = mapProps.find(L"GroupName"); if( mapProps.end() != it ) sGroupName = it-&gt;second; it = mapProps.find(L"Operation"); if( mapProps.end() != it ) bCreate = wcscmp(it-&gt;second.c_str(),L"create") == 0 ? true : false ; //Since we know what opeartion to perform, and we know whether it is //running rollback, commit or deferred script by MsiGetMode, the //implementation is straight forward if( MsiGetMode(hInstall,MSIRUNMODE_SCHEDULED) ) { if( bCreate ) CreateLocalGroup(sGroupName.c_str()); else DeleteLocalGroup(sGroupName.c_str()); } else if( MsiGetMode(hInstall,MSIRUNMODE_ROLLBACK) ) { if( bCreate ) DeleteLocalGroup(sGroupName.c_str()); else CreateLocalGroup(sGroupName.c_str()); } } catch( CMsiException &amp; ) { return ERROR_INSTALL_FAILURE; } return ERROR_SUCCESS; } </code></pre> <p>By using the above technique, for a typical custom action set you can reduce the custom action table to five entries:</p> <pre><code>&lt;CustomAction Id="CA.ScheduleLocalGroupCreation" Return="check" Execute="immediate" BinaryKey="CustomActionDLL" DllEntry="ScheduleLocalGroupCreation" HideTarget="yes"/&gt; &lt;CustomAction Id="CA.ScheduleLocalGroupDeletion" Return="check" Execute="immediate" BinaryKey="CustomActionDLL" DllEntry="ScheduleLocalGroupDeletion" HideTarget="yes"/&gt; &lt;CustomAction Id="CA.LocalGroupCustomAction.deferred" Return="check" Execute="deferred" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/&gt; &lt;CustomAction Id="CA.LocalGroupCustomAction.commit" Return="check" Execute="commit" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/&gt; &lt;CustomAction Id="CA.LocalGroupCustomAction.rollback" Return="check" Execute="rollback" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/&gt; </code></pre> <p>And InstallSquence table to only two entries:</p> <pre><code>&lt;InstallExecuteSequence&gt; &lt;Custom Action="CA.ScheduleLocalGroupCreation" After="InstallFiles"&gt; Not Installed &lt;/Custom&gt; &lt;Custom Action="CA.ScheduleLocalGroupDeletion" After="InstallFiles"&gt; Installed &lt;/Custom&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>In addition, with a little effort most of the code can be written to be reused (such as reading from custom table, getting the properties, formatting the needed properties and set to CustomActionData properties), and the entries in the custom action table now is not application specific (the application specific data is written in the custom table), we can put custom action table in a file of its own and just include it in each WiX project.</p> <p>For the custom action DLL file, since the application data is read from the custom table, we can keep application specific details out of the DLL implementation, so the custom action table can become a library and thus easier to reuse.</p> <p>This is how currently I write my WiX custom actions, if anyone knows how to improve further I would very appreciate it. :)</p> <p>(You can also find the complete source code in my blog post, <em><a href="http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/" rel="nofollow">Implementing Wix custom actions part 2: using custom tables</a></em>.).</p>
<p>If you have complex custom actions that need to support rollback, you might consider writing a Wix extension. Extensions typically provide authoring support (i.e. new XML tags that get mapped to MSI table entries), plus automatic scheduling of custom actions.</p> <p>It's more work than just writing a custom action, but once your CAs reach a certain level of complexity, the ease-of-authoring that extensions provide can be worth it.</p>
15,606
<p>I am having an Event Management System in which i want,</p> <p>If an event is registered for 5 days (21 jan 2009 to 26 Jan 2009) Then if another person wants to register an event between 22 jan 2009 to 24 jan 2009 then it will not allow to register. I want to check this using SQL query, so please tell me how can i do this.</p>
<p>SELECT *<br> FROM events e<br> WHERE (@startDate BETWEEN e.startDate and e.endDate)<br> OR (@endDate BETWEEN e.startDate and e.endDate)<br> OR (@startDate &lt; e.startDate AND @endDate > e.endDate) </p>
<p>Lookup DATEDIFF in SQL help.</p>
46,764
<p>I have a string that I would like to tokenize. But the C <code>strtok()</code> function requires my string to be a <code>char*</code>. How can I do this simply?</p> <p>I tried:</p> <pre><code>token = strtok(str.c_str(), " "); </code></pre> <p>which fails because it turns it into a <code>const char*</code>, not a <code>char*</code></p>
<pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; int main(){ std::string myText("some-text-to-tokenize"); std::istringstream iss(myText); std::string token; while (std::getline(iss, token, '-')) { std::cout &lt;&lt; token &lt;&lt; std::endl; } return 0; } </code></pre> <p>Or, as mentioned, use boost for more flexibility.</p>
<p>It fails because <strong><code>str.c_str()</code></strong> returns constant string but <code>char * strtok (char * str, const char * delimiters )</code> requires volatile string. So you need to use <strong>*const_cast&lt; char <em>></em></strong> inorder to make it voletile. I am giving you a complete but small program to tokenize the string using C strtok() function.</p> <pre class="lang-c prettyprint-override"><code> #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;string.h&gt; using namespace std; int main() { string s="20#6 5, 3"; // strtok requires volatile string as it modifies the supplied string in order to tokenize it char *str=const_cast&lt; char *&gt;(s.c_str()); char *tok; tok=strtok(str, "#, " ); int arr[4], i=0; while(tok!=NULL){ arr[i++]=stoi(tok); tok=strtok(NULL, "#, " ); } for(int i=0; i&lt;4; i++) cout&lt;&lt;arr[i]&lt;&lt;endl; return 0; } </code></pre> <hr> <p><strong>NOTE:</strong> strtok may not be suitable in all situation as <em><strong>the string passed to function gets modified by being broken into smaller strings</strong></em>. Pls., <a href="http://www.cplusplus.com/reference/cstring/strtok/" rel="nofollow noreferrer">ref</a> to get better understanding of strtok functionality.</p> <p><strong>How strtok works</strong></p> <p>Added few print statement to better understand the changes happning to string in each call to strtok and how it returns token.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;string.h&gt; using namespace std; int main() { string s="20#6 5, 3"; char *str=const_cast&lt; char *&gt;(s.c_str()); char *tok; cout&lt;&lt;"string: "&lt;&lt;s&lt;&lt;endl; tok=strtok(str, "#, " ); cout&lt;&lt;"String: "&lt;&lt;s&lt;&lt;"\tToken: "&lt;&lt;tok&lt;&lt;endl; while(tok!=NULL){ tok=strtok(NULL, "#, " ); cout&lt;&lt;"String: "&lt;&lt;s&lt;&lt;"\t\tToken: "&lt;&lt;tok&lt;&lt;endl; } return 0; } </code></pre> <p>Output:</p> <pre><code>string: 20#6 5, 3 String: 206 5, 3 Token: 20 String: 2065, 3 Token: 6 String: 2065 3 Token: 5 String: 2065 3 Token: 3 String: 2065 3 Token: </code></pre> <p>strtok iterate over the string first call find the non delemetor character (2 in this case) and marked it as token <em>start</em> then continues scan for a delimeter and replace it with null charater (# gets replaced in actual string) and return <em>start</em> which points to token start character( i.e., it return token 20 which is terminated by null). In subsequent call it start scaning from the next character and returns token if found else null. subsecuntly it returns token 6, 5, 3.</p>
36,844
<p>I am using Installshield 2008 Developer Edition and need to run SQL scripts against an existing SQL Server 2005 Express. When I do this without InstallShield, I would have to have some ODBC drivers installed for example. </p> <p>How does InstallShield do this? Does it include some sort of driver? Or does it depend on preexisting drivers?</p>
<p>If you are having the database installed by Installshield as part of your installation, Installshield has all the information to simply use a connection string like this:</p> <p>"Driver={SQL Native Client};Server=localhost;Database=newdatabase;Uid=proguser;Pwd=progpass;"</p> <p>There is no need to create an ODBC connection to use a connection string like this, and Installshield makes the SQL Native Client a prerequisite for SQL 2005 connected databases, so it is assured of having the correct driver available. </p>
<p>InstallShield has built-in support for SQL connections/scripts without the need for rolling custom code. The built-in custom actions use unmanaged ADO, specifically a property exposes the network library to be used:</p> <p>IS_SQLSERVER_NETLIB_MS -> Network Library=DBMSSOCN</p> <p>For more information refer to <a href="http://support.microsoft.com/kb/238949" rel="nofollow noreferrer">http://support.microsoft.com/kb/238949</a></p>
24,536
<p>I search about that topic, but all what I found, was the mechanical part of the 3d printer. But I didn't find, how to program it using arduino.</p> <p>I want to make a cartesian 3d printer. I don't have a printer yet, but I will buy all the components that I need actually.</p> <p>I know, how to control stepper motors, but I don't know, how I can program it in order to make the shape that I want.</p> <p>This is my question: what I need to learn in order to let this 3d printer make this shapes?</p>
<p>Yes. Look up Arduino Ramps 1.4</p> <p><a href="http://reprap.org/wiki/RAMPS_1.4" rel="noreferrer">http://reprap.org/wiki/RAMPS_1.4</a></p> <p>Following the programing is all done for you in the firmware. That said you can edit it. Just open the firmware files -- it is compiled when you upload them. Generally however one usually sticks to the preferences header alone..</p> <p><a href="http://reprap.org/wiki/List_of_Firmware" rel="noreferrer">http://reprap.org/wiki/List_of_Firmware</a></p> <p>Over all you are trying to reinvent the wheel. When I started 5-6 years ago it was barely a thing. Now you buy a proven kit and get to the printing. That said if you are truly interested in designing check out. </p> <p><a href="https://www.facebook.com/groups/cncbuilddesign/" rel="noreferrer">https://www.facebook.com/groups/cncbuilddesign/</a></p> <p>If you want help on picking a kit. Or what I really think you are looking for. A good place to start. This is one of the larger 3d printing groups. Full disclosure I run this one, but at 6k members I don't recruit. </p> <p><a href="https://www.facebook.com/groups/3DPrinterHobbyists/" rel="noreferrer">https://www.facebook.com/groups/3DPrinterHobbyists/</a></p> <p>I got my start in reprap IRC</p> <p><a href="http://reprap.org/wiki/IRC" rel="noreferrer">http://reprap.org/wiki/IRC</a></p> <p>Be aware there are trolls that now camp the IRC looking to sell you a printer. I would not engage with them, their printers are usually overpriced and sub par. </p> <p>Best of luck.</p> <p>Most of all I think you need to know it's Reprap all the way. Reprap forums, Reprap printers, Reprap kits, Reprap community. All the commercial printers started off the reprap project. Even if you buy a makerbot (don't) it's Reprap in it's roots.</p> <p><a href="https://vimeo.com/5202148" rel="noreferrer">https://vimeo.com/5202148</a></p>
<p>While Star Wind's answer is best as far as addressing what was not asked, but was probably the intent of the question, for educational purposes:</p> <p>To control the printer you need an microcontroller (most popular are Arduino) which will interface with the motor drivers. Microcontrollers cannot output the current needed to control the motors, so motor drivers (such as this <a href="https://www.pololu.com/product/1182" rel="noreferrer">https://www.pololu.com/product/1182</a> ) are easy ways to control a stepper motor with higher current (and usually voltage). You can build your own if you are particularlly adventurous, they are essentially two H-bridge circuits.</p> <p>The Arduino programming environment has a library for controlling stepper motors through a driver built in, you just tell it which pin to send the pulses to, and how fast, and a separate pin tells it to spin clockwise or counterclockwise. </p> <p>For a 3D printer you need at least four motors working in unison, one for the X, Y, Z axis, and one for the extruder (E axis). </p> <p>The existing programs that 3D printers use (Marlin, Sprinter, Teacup, etc) are all doing these simple steps at their core, but have implemented libraries of G-code that the printer uses to make control the stepper motors in unison to make the correct shape. Slicing programs such as Cura or Slic3r take in the 3D model and output the Gcode that the microcontroller is programmed to understand. </p>
330
<p>I am binding the dropdown with db entity. </p> <pre><code>ddlCustomer.DataSource = Customer.GetAll(); ddlCustomer.DataTextField = "CustomerName"; ddlCustomer.DataBind(); </code></pre> <p>I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?</p>
<p>Add: </p> <pre><code>ddlCustomer.Items.Insert(0, "SELECT"); </code></pre> <p>After ddlCustomer.DataBind();</p> <p>The item must be inserted after the data bind because the data bind clears the items.</p>
<p>I don't know if there is a one line solution to this, but what i was doing before is, not using DataBind , and first create the ListItem object that will have "Select" as the text, then loop through the collection returned from Customer.GetAll() and create a ListItem object for each item in the collection and add it to the drop down list using "DropDownList.Iems.Add(MyItem)" , i know it doesn't look very brilliant but it does the job , after all this is what DataBind is doing in behind.</p>
31,396
<p>I want to do preliminary check if entered string looks like <a href="http://en.wikipedia.org/wiki/Vehicle_identification_number" rel="noreferrer">Vehicle Identification Number (VIN)</a>. I know what it consists of 17 letters and digits, but letters I, O and Q are not allowed inside VIN, so I use this regular expression:</p> <pre><code>^[0-9A-Z-[IOQ]]{17}$ </code></pre> <p>Now if I check a string like 1G1FP22PXS2100001 with RegularExpressionValidator it fails, but CustomValidator with this OnServerValidate event handler</p> <pre><code>Regex r = new Regex("^[0-9A-Z-[IOQ]]{17}$"); args.IsValid = r.IsMatch(TextBox1.Text); </code></pre> <p>works well. </p> <p>Experiments show what RegularExpressionValidator doesn't support <a href="http://msdn.microsoft.com/en-us/library/ms994330.aspx" rel="noreferrer">Character Class Subtraction</a>, but Regex class does.</p> <p>Now I am interested why do these two .NET classes use different regex flavors? Is it documented somethere? </p>
<p>The RegularExpressionValidator also supports client-side validation using JavaScript, where the JavaScript Regex engine is used. The difference you see is the difference between the JavaScript and the .NET regex implementation. You can disable client-side validation and thus force the validator to use the .NET regex engine, at the price of the additional post-back.</p>
<p>Not a direct answer but just an obvious remark:</p> <p>If for some reason Character class subtraction is not supported, you always can use as a workaround:</p> <pre><code>^[0-9A-HJ-NPR-Z]{17}$ </code></pre> <hr /> <p>To document what I put in the comments of this question:</p> <p>The article <strong><a href="http://msdn.microsoft.com/en-us/library/6xh899wy(VS.85).aspx" rel="noreferrer">How to: Validate Against Patterns for ASP.NET Server Controls</a></strong>, does mention that the javascript client-side regex validator does not know &quot;character class subtraction&quot;</p> <p>As mentionned in <strong><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx" rel="noreferrer">RegularExpressionValidator Class .Net documentation</a></strong>:</p> <blockquote> <p>Both server-side and client-side validation are performed unless the browser does not support client-side validation or client-side validation is explicitly disabled (by setting the <code>EnableClientScript</code> property to false).</p> <p>The regular-expression validation implementation is slightly different on the client than on the server. On the client, JScript regular-expression syntax is used.<br /> On the server, <code>System.Text.RegularExpressions..::.Regex</code> syntax is used.<br /> <strong>JScript regular expression syntax is a subset of <code>System.Text.RegularExpressions..::.Regex</code> syntax</strong>.<br /> It is therefore recommended that <strong>JScript regular-expression syntax should be used</strong> in order to yield the same results on both the client and the server.</p> </blockquote> <p>Another illustration of that side-effect (different regex flavors between server and client sides) is mentionned in <a href="http://weblogs.asp.net/cosgood/archive/2003/05/06/6604.aspx" rel="noreferrer">RegularExpressionValidator woes</a> blog entry.</p>
44,129
<p>Design patterns are usually related to object oriented design.<br> <strong>Are there <a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)" rel="noreferrer">design patterns</a> for creating and programming <a href="http://en.wikipedia.org/wiki/Relational_database" rel="noreferrer">relational databases</a>?</strong><br> Many problems surely must have reusable solutions.</p> <p>Examples would include patterns for table design, stored procedures, triggers, etc...</p> <p>Is there an online repository of such patterns, similar to <a href="http://martinfowler.com" rel="noreferrer">martinfowler.com</a>?</p> <hr> <p>Examples of problems that patterns could solve:</p> <ul> <li>Storing hierarchical data (e.g. single table with type vs multiple tables with 1:1 key and differences...)</li> <li>Storing data with variable structure (e.g. generic columns vs xml vs delimited column...)</li> <li>Denormalize data (how to do it with minimal impact, etc...)</li> </ul>
<p>There's a book in Martin Fowler's Signature Series called <a href="http://www.ambysoft.com/books/refactoringDatabases.html" rel="noreferrer">Refactoring Databases</a>. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.</p> <p>I would also highly recommend David C. Hay's <a href="//www.amazon.com/dp/0120887983" rel="noreferrer">Data Model Patterns</a> and the follow up <a href="//www.amazon.com/dp/0120887983" rel="noreferrer">A Metadata Map</a> which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.</p> <p>Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series <a href="//www.amazon.com/dp/0471380237" rel="noreferrer">Volume 1</a> contains universally applicable data models (employees, accounts, shipping, purchases, etc), <a href="//www.amazon.com/dp/0471353485" rel="noreferrer">Volume 2</a> contains industry specific data models (accounting, healthcare, etc), <a href="//www.amazon.com/dp/0470178450" rel="noreferrer">Volume 3</a> provides data model patterns.</p> <p>Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's <a href="//www.amazon.com/dp/013011510X" rel="noreferrer">Modeling in Color With UML</a> provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model</p>
<p>Your question is a bit vague, but I suppose <a href="http://en.wikipedia.org/wiki/Upsert" rel="nofollow noreferrer"><code>UPSERT</code></a> could be considered a design pattern. For languages that don't implement <code>MERGE</code>, <a href="https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server">a number of alternatives to solve the problem</a> (if a suitable rows exists, <code>UPDATE</code>; else <code>INSERT</code>) exist.</p>
17,562
<p>Is there a way to get the count of rows in all tables in a MySQL database without running a <code>SELECT count()</code> on each table?</p>
<pre><code>SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{your_db}'; </code></pre> <p><a href="https://dev.mysql.com/doc/refman/5.7/en/tables-table.html" rel="noreferrer">Note from the docs though:</a> For InnoDB tables, <strong>the row count is only a rough estimate</strong> used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).</p>
<p>If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.</p> <p>Install following Gems:</p> <pre><code>$&gt; gem install dbi $&gt; gem install dbd-mysql </code></pre> <p>File: count_table_records.rb</p> <pre><code>require 'rubygems' require 'dbi' db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password') # Collect all Tables sql_1 = db_handler.prepare('SHOW tables;') sql_1.execute tables = sql_1.map { |row| row[0]} sql_1.finish tables.each do |table_name| sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};") sql_2.execute sql_2.each do |row| puts "Table #{table_name} has #{row[0]} rows." end sql_2.finish end db_handler.disconnect </code></pre> <p>Go back to the command-line:</p> <pre><code>$&gt; ruby count_table_records.rb </code></pre> <p>Output:</p> <pre><code>Table users has 7328974 rows. </code></pre>
36,336
<p>What replacements are available for pinging an ip address in Ruby? The stdlib "ping" library seems to be pretty limited in functionality. I'm not interested in rolling my own code here. Are there good gems available? Should I just suck it up and live with it?</p> <p>(I'm coding in Ruby 1.8.6 on Linux)</p>
<p><code><a href="https://rubygems.org/gems/net-ping" rel="nofollow noreferrer">net-ping</a></code> is worth a look. It allows for TCP pings (like the standard ruby <code>ping</code>) but also UDP, HTTP, and ICMP pings. An ICMP ping requires root privileges but the others do not. </p>
<p>To implement ping, you need to create a raw socket, which is restricted to root. So it isn't really possible to implement ping as a library, unless you know you will run as root. If the latter is acceptable, take a look at the <a href="http://raa.ruby-lang.org/project/icmpping/" rel="nofollow noreferrer">icmpping</a> library.</p>
43,112
<p>I want to get started using Dependency Injection and IOC and I want to get more into using Ninject.</p> <p>Are there any good application with sourcecode available that is written using Ninject that I can look at as a reference?</p>
<p>Shameless plug: I have put together a very basic tutorial to get started with Ninject. Have a look at <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Ninject Mini-Tutorial Part1</a> and <a href="http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/">Ninject Mini-Tutorial Part2</a>. That should help go get you started.</p> <p>There you can find a reference to the source code on Github.</p>
<p>I would recommend the book <a href="https://rads.stackoverflow.com/amzn/click/com/1430234040" rel="nofollow noreferrer" rel="nofollow noreferrer">Pro ASP.NET MVC 3 Framework</a>. It has some excellent samples and explanations on how to implement Ninject as well as Moq and Unit Testing, in an easy-to-read format that doesn't make you feel like a Dummy.</p>
34,138
<p>I'm working with asp.net (I'm a designer) and at some point during debugging it'll throw me and I'll get to an Exception objErr in the code - and when I hover it says "file not found". I assume it's an image but I've been searching and can't find anyway to pinpoint which file is missing. I hope this is enough information - if anyone could give me a direction I'll really appreciate it!</p> <p>AB</p>
<p>Find FileMon which is in the SysInternals package from Microsoft and run it when you get near to your file issue, maybe add a filter to filter out all of the OS file operations.</p> <p>You'll be able to see a file not found or access denied entry for the file if you have it set up right.</p> <p>I use FileMon all the time, it is free and really helps when troubleshooting permission and file IO problems.</p> <p>Ryan</p>
<p>I think you have not given full path for the image which you are searching.</p> <p>Another problem which might be possible is when it throws an error check the page in your url and check if that page exists in your project. I wish I could help you more but I need more info for that,</p>
45,404
<p>How can I make a variable (object) available for the whole lifetime of the webservice?</p> <p>Static variable seem to work but is there an other way to do it?</p>
<p>Static variables exist for the lifetime of the App Domain that contains them. In the case of a web service, this is usually the ASP.Net Worker Process. What that means is that when IIS decides to cycle the worker process, your static variable will be gone. This may be what you want, in which case it is probably a good choice. (Putting asside discussions of whether or not static variables are proper in a given context).</p> <p>Within the scope of a web service you also have access to the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplicationstate.aspx" rel="noreferrer">HttpApplicationState</a> via the Application property (this would be an asmx service...not sure if WCF is the same or not), so this could also be a good choice for stashing something needed for the lifetime of a service.</p>
<p>probably, but if static variable works then move on to the next problem ! :)</p>
37,367
<p>I'm looking for a way to slice up a 3D model and then get the profiles of each individual layer. I need to 2D print the different layers (with the layer height that I define) for a Styrofoam craft.</p> <p>Thank you very much!</p>
<p>I'm a fan of OpenSCAD and have used the method suggested in the first answer. For non-OpenSCAD users, another option exists, which I've also used.</p> <p>PrusaSlicer is a free 3D printer slicing program. One can configure layer heights as desired for the material thickness, even though it's not likely one will find a printer with such values, except perhaps concrete 3D printers!</p> <p>Once configured and sliced, the exported file (configured for a Prusa SL1 printer) is renamed to .ZIP and the files within extracted. The files of note are going to be PNG format, one file per layer.</p> <p>The settings within the slicer software have to be &quot;adjusted&quot; for your creation.</p> <p>In Print Settings tab, change the layer height to match your material thickness. Also in the Print Settings tab, turn off supports and turn off pad (left column selections).</p> <p>In Material Settings tab, change the Initial layer height to match your overall layer thickness. Unchanged, it remains the default 0.05 mm, unlikely to match your building material.</p> <p>On the Printer Settings tab, change the bed shape to match your objective plus a bit of spacing around the item. Change the max height appropriately.</p> <p>Set the Display Width parameters to match your output. Excessively large values will result in small model segments in a large blank area. Set pixel values to desired resolution of the output image file. For example, 200 is equivalent to a typical inkjet printer resolution.</p> <p>I performed all of the above steps for a simple cube, exported the file to the default .SL1 extension, renamed it to .ZIP and extracted to a folder. The folder contained a number of support files for the MSLA printer, but also a full list of the layer .PNG files. Depending on your system settings, you may be able to change the extension in the Save dialog to .ZIP.</p> <p>If PNG is not a suitable format, one can convert them to SVG using Inkscape bitmap trace or similar software.</p> <p>I recommend to create a model with some form of registration incorporated to the design. One can create and subtract a pair of cylinders, for example, that travels through each layer, allowing insertion of a dowel to more easily stack the slices for assembly.</p> <p>One can add primitives within the slicer, but they fall to the bed and also cannot be subtracted, at least so far as my limited research has shown. I've used Fusion 360 and Meshmixer to create such modifications.</p> <p>Another aspect of the slicer is the ability to hollow the model, which would provide for some interesting constructions as well as possibly easier alignment.</p> <p>This should be a .GIF animation of the results of my testing on Astronaut Phil A Ment, 1 millimeter layer height:</p> <p><a href="https://i.stack.imgur.com/ES8A3.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ES8A3.gif" alt="astronaut slicing animation" /></a></p> <p>stltopng conversion of original STL file of Phil:</p> <p><a href="https://i.stack.imgur.com/of3mZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/of3mZ.png" alt="phil a ment model" /></a></p>
<p>With OpenSCAD, you can <code>import</code> the STL file and apply <code>projection</code> with <code>cut=true</code> at successive Z-axis <code>translate</code> operations, and write out the result as SVG. This can all be automated from the command line to product a series of SVG files for your layers to &quot;2D print&quot;.</p>
2,150
<p>Is it alright to expect that the user using the back end will have Javascript enabled?</p> <p>I guess the answer I'll get is 'it depends on your target users'. I am developing a system for fun that will hopefully be used by other people. I would like to hear from other people developing back end systems, and what did they decide to do and why?</p> <p>SEO I'm not concerned with, and semantics aern't of as much importance.</p>
<p>Personally I would expect the failover, but there are circumstances (particularly low profile sites, intranets, e-learning content) where you can assume JS.</p> <p>Mostly you can even go with a simple "You require JS / This works better with JS" and I would consider that good enough, but there's a couple of instances where I would demand real failover: </p> <ul> <li><p>.gov or other public service sites (legal requirements)</p></li> <li><p>sites for web-tech companies (you need to demonstrate your ability to do this)</p></li> <li><p>very high traffic sites (where the 3% of non-JS users becomes a high absolute number)</p></li> <li><p>sites (or pages) for mobile devices (most of these haven't got JS reliably)</p></li> </ul> <p>In general, it's reasonably easy to provide <em>some</em> kind of noscript, so why not do it anyway?</p>
<p>As long as the function that your application will be serving is general, I'd say it is safe to rely on Javascript. One of the sites that I manage receives ~35,000 UV's on a good day. I think it is fair to say we come in contact with quite a variety of browser and operating system combinations. According to our stats, roughly 97% of our users have Javascript enabled.</p> <p>If it can fail elegantly without Javascript, I'd opt for that solution, but I wouldn't lose sleep over the fact that you <em>might</em> be losing a few people everyday.</p>
48,874
<p>Code I am trying to run:</p> <pre><code>$query = "DESCRIBE TABLE TABLENAME"; $result = odbc_exec($h, $query); </code></pre> <p>The result:</p> <blockquote> <p>PHP Warning: odbc_exec(): SQL error: [unixODBC][IBM][iSeries Access ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid tokens: INTO., SQL state 37000 in SQLExecDirect in ...</p> </blockquote> <p>There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error?</p>
<p>The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table:</p> <pre><code>select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table' </code></pre>
<p>To me it looks like you need to provide a way for the statement to return a value "Valid tokens: INTO" tells me that. I haven't used DESCRIBE before, but I would imagine that it returns something.</p> <p>Interactive SQL doesn't allow the command so I can't really help you much further than that.</p> <p>BTW, add the iSeries tag to your question. You might get a few more answers that way.</p>
18,592
<p>I am experiencing some weird behavior with localized messages reported from my background worker process in my windows forms application.</p> <p>The application is a setup application with windows forms. The application launches a background worker to perform and IIS reset and then install MSIs.</p> <p>The first time I run the application on a Spanish Win Server 2003 VM the forms are in spanish but not the BWP messages. If i immediately run it again, the messages are in spanish.</p> <p>The .Resources files are embedded resources and are extracted to the temp directory upon application startup.</p> <p>My code retrieves the localized strings through a custom resource manager class. This class creates a file based resource to the .Resources files in the temp directory. This is working correctly because the windows forms labels and title are localized every time.</p> <p>Has anyone experienced this? I'm absolutely stuck, please help. Thanks, Andrew</p>
<p>If your UIThread runs an other UICulture than your BackgroundWorker you can explicit change the culture of the worker thread by using an callback like this:</p> <pre><code> private delegate CultureInfo GetUICultureCallback(); private CultureInfo GetUICulture() { if (this.InvokeRequired) { return (CultureInfo)this.Invoke(new GetUICultureCallback(GetUICulture)); } return System.Threading.Thread.CurrentThread.CurrentUICulture; } void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.CurrentThread.CurrentUICulture = GetUICulture(); for (; ; ) { if (backgroundWorker.CancellationPending) { e.Cancel = true; return; } . . . </code></pre>
<p>The culture info is in thread-local storage, so if the background worker runs processes on different threads, this may be expected.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx</a></p> <p>I am not sure what the recommended practice for transfering culture info across threads, though.</p>
22,762
<p>I am looking for a way to create or implement a collapsible side panel inside of a form. Similar in the way a ToolStripContainer works I would like the same general concept except using panels that I can fill with controls. Does anyone know of a simple way to do this with the provided .Net controls or is this a total custom job. Either way I would appreciate some suggestions.</p>
<p>There is an example with code here: <a href="http://www.codeproject.com/Articles/8220/Collapsible-Panels-in-VB-NET" rel="nofollow">http://www.codeproject.com/Articles/8220/Collapsible-Panels-in-VB-NET</a></p>
<p>Try this it's in c# but I am sure it can be easily translated</p> <p>Start a new Project and add a panel. Dock that panel to the left of the Form. Add a button to the Panel dock it to the right Set the Button Text to "&lt;" and Width to 20. in the button1_Click event add this</p> <pre><code> private void button1_Click(object sender, EventArgs e) { if (button1.Text == "&gt;") { panel1.Width = 200; button1.Text = "&lt;"; } else { panel1.Width = button1.Width; button1.Text = "&gt;"; } } </code></pre> <p>What happens here is when the button is clicked the form is shrunk off to the left, leaving only the button visible. When the button is clicked again, it expands back out.</p>
25,082
<p>I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource </code></pre>
<p>Someone recently asked <a href="https://stackoverflow.com/questions/301924/python-urlliburllib2httplib-confusion">the same question you're asking</a>. If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standard library.</p> <p>The accepted answer might not be as useful to you as <a href="https://stackoverflow.com/questions/301924/python-urlliburllib2httplib-confusion#302184">this other answer</a>, since the accepted answer deals with a specific problem involving redirection. However, I recommend reading through all of the answers regardless.</p>
<p>You probably want to create an opener with these handlers and apply it to urllib2. With these applied your cookies are handled and you'll be redirected, if server decides it wants you somewhere else.</p> <pre><code># Create handlers cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection (not needed for javascript redirect?) # Create opener opener = urllib2.build_opener(cookieHandler,redirectionHandler) # Install the opener urllib2.install_opener(opener) </code></pre>
41,629
<p>I have an app that is failing on the install. The vendor says I probably have ini_set() disabled. How can I check this?</p>
<p>I did some research on this, and it turns out that sometimes ini_set will not return FALSE, but an empty string. This is mentioned in the URL pointed out by gabriel1836. The best way to check if it works is to first check the disable_functions flag in php.ini to see if it is disabled, and then (if it is not disabled), change a value with it, and echo phpinfo() immediately after. If the value is changed under the local column, then you know ini_set works.</p>
<p>You might want to take a look at the CHANGEABLE directives in php.ini: <a href="http://us3.php.net/manual/en/ini.php#ini.list" rel="nofollow noreferrer"><a href="http://us3.php.net/manual/en/ini.php#ini.list" rel="nofollow noreferrer">http://us3.php.net/manual/en/ini.php#ini.list</a></a></p> <p>In regard to verify whether an ini_set function worked, you can check the return value to make certain that it worked: <a href="http://us3.php.net/manual/en/function.ini-set.php" rel="nofollow noreferrer"><a href="http://us3.php.net/manual/en/function.ini-set.php" rel="nofollow noreferrer">http://us3.php.net/manual/en/function.ini-set.php</a></a></p> <p>The code would look something like this:</p> <pre><code>&lt;?php if(ini_set('error_reporting', 'ALL') === false) { // Perform failure handling logic } ?&gt; </code></pre>
30,697
<p>How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.</p>
<p>If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.</p>
<p>Use a higher-resolution timer.</p>
31,902
<p>I've got a project that was written in BASIC. I'm not sure of the exact reason, but the app will not function except when being run from a FAT-16 file system.</p> <p>I'd rather try to set up an environment that will support this app in a modern OS (Vista/XP) instead of rewriting it.</p> <p>Does anyone know how to get an app like this running in XP/Vista through some kind of code change (to the BASIC code) or FAT-16 &quot;emulator&quot; (if such a thing exists)?</p>
<p>You may try running it via a <a href="http://www.dosbox.com/" rel="nofollow noreferrer">DOSBOX</a>:</p> <blockquote> <p>DOSBox emulates an Intel x86 PC, complete with sound, graphics, mouse, joystick, modem, etc., necessary for running many old MS-DOS applications that simply cannot be run on modern PCs and operating systems, such as Microsoft Windows XP, Windows Vista, Linux and FreeBSD</p> </blockquote> <p>(from their <a href="http://www.dosbox.com/wiki/Main_Page" rel="nofollow noreferrer">Wiki</a>)</p> <p>I use it for several years now. It is good, stable and quite robust. It has several third-party GUIs as well, to make your life easier.</p>
<p>Depending on the Environment: It should still be possible to create Fat-16 Filesystems on modern OS, you may just need additional Tools like Acronis DiskDirector of even some Linux' fdisk Variant.</p> <p>Just keep in mind that FAT-16 is limited to a partition Size of 2 GB.</p> <p>But as said before: Best to find out WHY. Sounds like some sort of WTF-Copy-Protection.</p>
17,568
<p>I am actually developing and application that has around 15 modules, all of them using the same database.</p> <p>I am using Apache + Mongrel, I cannot use Passenger because I am working on Windows (please forgive me for this deadly sin!)</p> <p>Which of the following is a better approach?</p> <ol> <li>Deploy multiple small rails applications using a virtual server and a pair of mongrels for each application.</li> <li>Deploy only a big rails application</li> </ol> <p>I am worried about the number of running mongrels and the memory/cpu load.</p>
<p>I'd suggest deploying a monolithic Rails application.</p> <p>I use the <a href="http://agilewebdevelopment.com/plugins/request_routing" rel="nofollow noreferrer">request_routing</a> plugin to drive 3 domains sharing the same database from one, big Rails application.</p> <p>I'm running 4 mongrels, which seems to be enough for now, but YMMV.</p>
<p>It sounds like it would be a much better use of your hardware to integrate all modules into one comprehensive rails apps.</p> <p>IMHO the primary weakness of Rails is the amount of resources needed to run a low or very low traffic app. On the other hand a few mongrels go a long way to serve a whole lot of traffic.</p>
28,548
<p>I'd like to be able to see what registry keys are used for. A book on the registry would be fine as well. Info on Windows Vista changes would be great!</p>
<p>Oh, how I wish there was a single site where the registry was collectively documented by all who write values there! Keep in mind, any app can create its own set of registry keys and values, so it's not just MS who would be necessary to such an effort. Though they would be a key player!</p> <p>In the meantime, there are two MS sites I use as startng points when I need to know what a particular key/value pair do:</p> <p>Windows 2003 registry reference: <a href="http://technet.microsoft.com/en-us/library/cc778196.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc778196.aspx</a></p> <p>Windows 2000 Registry reference: <a href="http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/default.mspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc974061.aspx</a></p> <p>Keep in mind that since Windows is an evolving thing, even information about older versions can be very helpful. Also note that W2003 bears a lot of resemblance to XP. Sadly, I have not found a link to the Vista/Windows 2008 registries similar to the above.</p> <p>When you need to know what's up with a specific key, and it's not found in one of the above links, try a search of that key's full path at <a href="http://support.microsoft.com" rel="nofollow noreferrer">http://support.microsoft.com</a></p>
<p>I have used <a href="http://www.majorgeeks.com/Mystery_Behind_Windows_Registry_d415.html" rel="nofollow noreferrer">this help file</a> in the past. Very good resource</p>
8,230
<p>I've got a VS2008 deployment project that builds an installer for a couple of Windows services.</p> <p>Each service references several different projects:</p> <pre> CustomerName.MailSendingService -> CustomerName.Network -> CustomerName.Data -> CustomerName.Security CustomerName.ProductIntegrationService -> CustomerName.Core -> CustomerName.Security </pre> <p>The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.</p> <p>I've added the primary output from the Windows service projects in the deployment project's file system editor. </p> <p>My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (<code>CustomerName.ProductIntegrationService</code> is missing <code>CustomerName.Security</code>) </p> <p>Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.</p> <p>(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's <code>bin\Release</code> folder, but isn't packaged in the MSI file built for the deployment project.</p> <p>(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.</p> <p>Why would just one project's output be missing?</p>
<p>I have a couple more things to add after reproducing the same suspected msi defect.</p> <p>1) When I added the second project output sharing the same detected dependency to the installer it did not automatically add the dependency. I removed both project output's and added them back in reverse order. The second project output added never added the detected dependency. This excludes any configuration or code issue with the projects and how the references were added. It's always the second one that fails.</p> <p>2) My team actually hit a second problem after using the 'Manually add detected assembly' workaround. Initially we added the dependency from the location in '\Program Files\xxx' but ran into build problems on 64 bit machines where that same dependency was in the '\Program Files (x86)\xxx' folder even though VS is smart enough to handle this problem when picking up references.</p> <ul> <li>The proper way to manually add the assembly is by navigating to the bin folder and adding the assembly that is copied local. This ensures that the right assembly will be present on x86 or x64 machines.</li> </ul>
<p>I have not used Visual Studio 2008 yet, however in 2005 you have to verify that the missing reference on the project has the Copy Local property set to true.</p> <p>This will copy the missing file to the output directory.</p>
16,305
<p>I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":</p> <pre><code>value = ""; 8.times{value &lt;&lt; (65 + rand(25)).chr} </code></pre> <p>but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:</p> <pre><code>value = ""; 8.times{value &lt;&lt; ((rand(2)==1?65:97) + rand(25)).chr} </code></pre> <p>but it looks like trash.</p> <p>Does anyone have a better method?</p>
<pre><code>(0...8).map { (65 + rand(26)).chr }.join </code></pre> <p>I spend too much time golfing.</p> <pre><code>(0...50).map { ('a'..'z').to_a[rand(26)] }.join </code></pre> <p>And a last one that's even more confusing, but more flexible and wastes fewer cycles:</p> <pre><code>o = [('a'..'z'), ('A'..'Z')].map(&amp;:to_a).flatten string = (0...50).map { o[rand(o.length)] }.join </code></pre> <p>If you want to generate some random text then use the following:</p> <pre><code>50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(&quot; &quot;) </code></pre> <p>this code generates 50 random word string with words length less than 10 characters and then join with space</p>
<p>I don't know ruby, so I can't give you the exact syntax, but I would set a constant string with the list of acceptable characters, then use the substring operator to pick a random character out of it.</p> <p>The advantage here is that if the string is supposed to be user-enterable, then you can exclude easily confused characters like l and 1 and i, 0 and O, 5 and S, etc.</p>
11,391
<p>How do I read a file into a <code>std::string</code>, i.e., read the whole file at once?</p> <p>Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.</p> <p>One way to do this would be to stat the filesize, resize the <code>std::string</code> and <code>fread()</code> into the <code>std::string</code>'s <code>const_cast&lt;char*&gt;()</code>'ed <code>data()</code>. This requires the <code>std::string</code>'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the <code>std::string</code>'s size may not equal the file's size.</p> <p>A fully correct, standard-compliant and portable solutions could be constructed using <code>std::ifstream</code>'s <code>rdbuf()</code> into a <code>std::ostringstream</code> and from there into a <code>std::string</code>. However, this could copy the string data and/or needlessly reallocate memory. </p> <ul> <li>Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? </li> <li>Is there another way to do it? </li> <li>Did I miss some hidden Boost function that already provides the desired functionality?</li> </ul> <p><br></p> <pre><code>void slurp(std::string&amp; data, bool is_binary) </code></pre>
<p>One way is to flush the stream buffer into a separate memory stream, and then convert that to <code>std::string</code> (error handling omitted):</p> <pre><code>std::string slurp(std::ifstream&amp; in) { std::ostringstream sstr; sstr &lt;&lt; in.rdbuf(); return sstr.str(); } </code></pre> <p>This is nicely concise. However, as noted in the question this performs a redundant copy and unfortunately there is fundamentally no way of eliding this copy.</p> <p>The only real solution that avoids redundant copies is to do the reading manually in a loop, unfortunately. Since C++ now has guaranteed contiguous strings, one could write the following (≥C++17, error handling included):</p> <pre><code>auto read_file(std::string_view path) -&gt; std::string { constexpr auto read_size = std::size_t(4096); auto stream = std::ifstream(path.data()); stream.exceptions(std::ios_base::badbit); auto out = std::string(); auto buf = std::string(read_size, '\0'); while (stream.read(&amp; buf[0], read_size)) { out.append(buf, 0, stream.gcount()); } out.append(buf, 0, stream.gcount()); return out; } </code></pre>
<p>I know that I am late to the party, but now (2021) on my machine, this is the fastest implementation that I have tested:</p> <pre><code>#include &lt;fstream&gt; #include &lt;string&gt; bool fileRead( std::string &amp;contents, const std::string &amp;path ) { contents.clear(); if( path.empty()) { return false; } std::ifstream stream( path ); if( !stream ) { return false; } stream &gt;&gt; contents; return true; } </code></pre>
14,144
<p>My application is already developed and now we are going to change the connection string whatever stored in the session object (Bcoz of Distributed Database Management System (DDBMS))</p> <p>Problem is here.....</p> <blockquote> <pre><code>In that application There are so many **ObjectDataSource** which are </code></pre> <p>initialize with the using <strong>.XSD</strong> file. which is related to the <strong>TableAdapter</strong> and in which connection string of <strong>TableAdapter</strong> is assign from the Web.Config File. Now How to change the connection string to whatever stored in session object?</p> </blockquote> <p>Thanks in advance.</p>
<p>To change the connection of an XSD at runtime you'll need to set the ConnectionModifier property of the table adapter to Public. If they're created by the "wizard" they will be set to Friend/Internal (VB/C#) by default.</p> <p>I had trouble finding the ConnectionModifier property (it's not listed in my vs2005 documentation)! If you click the lower area of the XSD (where the queries are) then it should be visible in the properties window to change.</p> <p>Then you can set the Connection property (it takes an object not a string) where ever you declare your table adapter.</p>
<p>I have a winforms app that I had a similar problem. I created a static class that contained my settings (clsGlobal) and one of the properties was a connection string. In the page where I referenced the datatable, I set the connection string to clsGlobal.gstrConnectionString or the connection string property. May be better to do this in an app initialization phase. However, setting the tableadapter connection string upon app startup from a shared property should get you around this.</p> <pre><code>myTableAdapter.Connection.ConnectionString = clsGlobals.gstrConnectionString; </code></pre> <p>So, you would just <code>.ToString()</code> your session object and assign it to ta.Connection.ConnectionString.</p>
47,641
<p>Aloha</p> <p>I received a few nice xsd files which I want to convert to classes (using xsd.exe) All the xsd's have the same includes, like this:</p> <pre><code>&lt;xs:include schemaLocation="kstypes.xsd" /&gt; &lt;xs:include schemaLocation="ksparams.xsd" /&gt; </code></pre> <p>When I generate a class for each xsd the types declared in these files are duplicated for each original xsd. Is there any easy way to 1) only generate the types in the included xsd's once and 2) make sure all other classes use these types?</p> <p>-Edoode</p>
<p>Looking over the documentation, it would appear that the 'best' way (not an easy way!) would be to use the /element:<em>elementname</em> command line switch on the second and subsequent files to specify the types you want classes generated for.</p>
<p>Looking over the documentation, it would appear that the 'best' way (not an easy way!) would be to use the /element:<em>elementname</em> command line switch on the second and subsequent files to specify the types you want classes generated for.</p>
48,996
<p>Is there a (good) documentation about the format of the eclipse workspace files (.location, x.tree, ...)?</p> <p>I need this to programatically create a workspace for automated builds. Unfortunately I have to do this job from a .NET program, so I can't use any Eclipse classes to do this! (We manage our Linux C++ projects using Eclipse + CDT).</p>
<p>Not exactly a precise answer, but I just would point out the following sources for your question:</p> <ul> <li><a href="http://wiki.eclipse.org/Workspace" rel="nofollow noreferrer">Eclipse Wiki</a>, </li> <li><a href="http://polishineclipse.blogspot.com/" rel="nofollow noreferrer">Eclipse Workspace Team Blog</a></li> <li>Eclipse <a href="http://dev.eclipse.org/newslists/news.eclipse.platform/maillist.html" rel="nofollow noreferrer"><strong>platform mailing list</strong></a></li> </ul> <p>May between those three links you will find the actual documentation for workspace structure (if you do, post an answer here ;) )</p>
<p>This is a pretty good solution:</p> <p><a href="http://eclipseone.wordpress.com/2010/01/25/checkout-multiple-projects-automatically-into-your-eclipse-workspace/" rel="nofollow">http://eclipseone.wordpress.com/2010/01/25/checkout-multiple-projects-automatically-into-your-eclipse-workspace/</a></p>
45,225
<p>My normal IDE is Visual Studio, but I'm currently doing some development in Eclipse for the first time. If you press Ctrl-X with text selected in either program, it cuts the text and puts on the clipboard exactly as you'd expect. If press Ctrl-X with no text selected in Visual Studio, it cuts the current line. In Eclipse it is ignored. Is there a way to get Eclipse to use Studio's behavior?</p>
<p>I'm a big fan of naming my CSS classes by their contents or content types, for example a &lt;ul&gt; containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific. </p> <p>Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this: </p> <pre><code> ul.tabs { list-style-type: none; } ul.tabs li { float: left; } ul.tabs li img { border: none; } </code></pre> <p>That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me. </p> <p>Finally, a couple of tips: </p> <ol> <li>Make best use of cascades and don't "overclass" stuff. If you give a &lt;ul&gt; class="textNav" then you can access its &lt;li&gt;s and their children without having to add any additional class assignments. ul.textNav li a:hover {} </li> <li><p>Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:</p> <pre><code>&lt;style&gt; div.box { float: left; border: 1px solid blue; padding: 1em; } div.wide { width: 15em; } div.narrow { width: 8em; } div#oddOneOut { float: right; } &lt;/style&gt; &lt;div class="box wide"&gt;a wide box&lt;/div&gt; &lt;div class="box narrow"&gt;a narrow box&lt;/div&gt; &lt;div class="box wide" id="oddOneOut"&gt;an odd box&lt;/div&gt; </code></pre></li> <li><p>Giving a class to your document &lt;body&gt; tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }" </p></li> </ol> <p>I hope you find at least some of my ramblings useful and wish you the best with your projects! </p>
<p>Cop-out line of the year: it depends.</p> <p>How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?</p> <p>My favorite place to go for information like this is <a href="http://www.csszengarden.com/" rel="nofollow noreferrer">CSS Zen Garden</a> &amp; <a href="http://alistapart.com/" rel="nofollow noreferrer">A List Apart</a>.</p>
22,127
<p>I know Hostmonster allows Python. Has anyone successfully run Django on there? Any problems? </p>
<p>I know this is an old question, but here is the answer: <strong>yes, Hostmonster does support Django</strong></p> <p>There used to be <a href="http://helpdesk.hostmonster.com/index.php/kb/article/000531" rel="nofollow noreferrer">this Hostmonster KB article</a> for details, including instructions on how to set it up, but that link appears to be dead these days, and the only article about Hostmonster article about Django is about <a href="https://my.hostmonster.com/cgi/help/585" rel="nofollow noreferrer">troubleshooting</a>. You can find instructions on how to set up Django on Hostmonster <a href="http://www.calebmadrigal.com/django-on-hostmonster/" rel="nofollow noreferrer">elsewhere</a>.</p>
<p>Well, if it support Python, you might be able to run Django using a FastCGI setup, as described here: <a href="https://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/" rel="nofollow noreferrer">FastCGI Docs</a>. If it supports mod_python (which I guess it's what you mean), then sure, you can install it using the steps listed here: <a href="https://docs.djangoproject.com/en/1.1/howto/deployment/modpython/" rel="nofollow noreferrer">ModPython docs</a></p>
4,163
<p>My spring-context file is shown below.</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"&gt; &lt;bean id="cfaBeanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext"&gt; &lt;constructor-arg value="classpath:cfa-spring-core.xml" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>When I try to run my application, I get the following error:</p> <pre><code>Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:cfa-spring-context.xml], factory key [cfaBeanFactory]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:389) ... 56 more Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Line 16 in XML document from URL [file:/C:/.../cfa-spring-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:169) ... 59 more Caused by: org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) </code></pre> <p>Can someone tell me what I'm doing wrong?</p>
<p>Turns out this is because I'm using Hibernate 3 with Spring 1.x which means the DTDs are wrong. Updated the Spring JAR file in the project and that fixed the problem.</p>
<p>you are not closing the <code>&lt;beans&gt;</code> tag. Add <code>&lt;/beans&gt;</code> to the end of your config file.</p>
33,424
<p>What's the difference between:</p> <pre><code>class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() </code></pre> <p>and:</p> <pre><code>class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) </code></pre> <p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
<p>The benefits of <code>super()</code> in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.</p> <p>However, it's almost impossible to use multiple-inheritance without <code>super()</code>. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended <code>Child</code> and a mixin, their code would not work properly.</p>
<pre><code>class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) </code></pre> <p>This is fairly easy to understand.</p> <pre><code>class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() </code></pre> <p>Ok, what happens now if you use <code>super(Child,self)</code>?</p> <p>When a Child instance is created, its MRO(Method Resolution Order) is in the order of (Child, SomeBaseClass, object) based on the inheritance. (assume SomeBaseClass doesn't have other parents except for the default object)</p> <p>By passing <code>Child, self</code>, <code>super</code> searches in the MRO of the <code>self</code> instance, and return the proxy object next of Child, in this case it's SomeBaseClass, this object then invokes the <code>__init__</code> method of SomeBaseClass. In other word, if it's <code>super(SomeBaseClass,self)</code>, the proxy object that <code>super</code> returns would be <code>object</code> </p> <p>For multi inheritance, the MRO could contain many classes, so basically <code>super</code> lets you decide where you want to start searching in the MRO.</p>
27,506
<p>Does anyone know of any problems with using WCF to expose a SOAP interface for non .NET clients? For example incompatibilities with other SOAP libraries?</p> <p>This is so that the SOAP interface can be exposed for third parties to integrate with our software.</p>
<p>Some of the problem areas I've encountered with WCF:</p> <ul> <li>It generates WSDL that is split across multiple URLs. That is, one part of the schema is at one URL, another is at a different URL, etc. The "main" WSDL URL (the one with just "?WSDL" after the service name) references the others via <code>xsd:import</code> elements. Many SOAP clients (eg pre-.NET Delphi) have enormous difficulty with this idiom. So you really have to "flatten" your WSDL in order to achieve interoperability in practice. One solution is given <a href="http://blogs.thinktecture.com/cweyer/archive/2007/05/10/414840.aspx" rel="noreferrer">here</a>.</li> <li>WCF doesn't generate XML namespaces the same way as, say, ASMX web services. WCF has a tendency to place any service or data contract into a namespace of its own choosing. Again, some SOAP clients have difficulty with this. You can increase you interoperability level by adding an explicit namespace to your ServiceContract and DataContract attributes.</li> <li>Many SOAP clients won't handle faults as nicely as WCF clients. For example, the proxy generation code won't create client-side objects for the faults declared in the WSDL. The faults will still be transmitted to the client, of course, but the client then has to do more work to figure out what kind of fault it was.</li> </ul>
<p>Generally everything works fine. It will obviously depend on the client you're using - not everyone implement SOAP properly.</p> <p>P.S. Could you please rephrase your question if you hope for more specific answer?</p>
13,436
<p>I've noticed a lot of Microsoft sites have the *.MSPX extension. While I'm very familiar with ASP.NET, I've not seen this extension before.</p> <p>Does anyone know what this identifies?</p>
<p>A few internet searches led me to <a href="http://www.microsoft.com/backstage/bkst_column_46.mspx" rel="nofollow noreferrer">http://www.microsoft.com/backstage/bkst_column_46.mspx</a>, but it was a dead link. Fortunately, it was archived on the Wayback Machine and you can read it here:</p> <p><a href="http://web.archive.org/web/20040803120105/http://www.microsoft.com/backstage/bkst_column_46.mspx" rel="nofollow noreferrer">http://web.archive.org/web/20040803120105/http://www.microsoft.com/backstage/bkst_column_46.mspx</a></p> <p>The .MSPX extension is part of the &quot;Microsoft Network Project,&quot; which according to the article above, is designed to give Microsoft's sites a consistent look-and-feel worldwide, as well as keep the design of the site seperate from the content. Here's the gist of the article:</p> <blockquote> <p>The presentation framework includes a custom Web handler built in ASP.NET. Pages that use the presentation framework have the .mspx filename extension, which is registered in Microsoft Internet Information Services (IIS) on the Web servers. When one of the Microsoft.com Web servers receives a request for an .mspx page, this custom Web handler intercepts that call and passes it to the framework for processing.</p> <p>The framework first checks to see whether the result is cached. If it is, the page is rendered immediately. If the page is not cached, the handler looks up the URL for that page in the table of contents provided by the site owner (see below) to determine where the XML content for the page is stored. The framework then checks to see if the XML is cached, and either returns the cached content or retrieves the XML from the data store identified in the table of contents file.</p> <p>Within the file that holds the content for the page, XML tags identify the content template to be used. The framework retrieves the appropriate template and uses a series of XSLTs to assemble the page, including the masthead, the footer, and the primary navigational column, finally rendering the content within the content pane.</p> </blockquote>
<p>I love you guys, i was asking myself also many times, why MS uses .mspx and what it is at all?! :) </p> <p>That time i couldn´t find any informations quickly and assumed it would just be something on top of asp.net or maybe not even that, because you should be able to assign the same asp.net cgi dll to .mspx also easy too ;) </p> <p>But, surely, it can be anything.. also an "special" CGI itself (completely beside ASP.NET), which processes that request with much better / much more cache-use, easier editing and so on..</p> <p>The end of the story was, that i came accross the view, that maybe it´s not important to know, what .mspx exactly is :)</p>
6,945
<p>I've worked on several flash projects so far. I know my way around AS3 but I also started becoming curious about how other flash programs are written, so I decompiled a few swf files to see how they were made. (I have also read through open source projects, but I don't say that because I feel guilty about decompiling swf files or anything. ) And I learned a lot by looking into these projects. But there were some projects where I couldn't make any sense of the code at all. It looked like they couldn't have been written by human beings! </p> <p>Maybe they were obfuscated, right? And that got me thinking: there are more and more sites that offer a Flash/Flex application as their primary service. I'm thinking of Scribd, Sproutbuilder, but you could think of others. These sites have a great interest to protect the code in their Flash platforms.</p> <p>So that brings me to my question: what kind of tools or techniques do you, flash programmers, use to make your code decompile-proof? </p> <p>EDIT: after posting this, I came across <a href="https://stackoverflow.com/questions/29399/is-obfuscator-javascript-enough#29471">this interesting post by Charles Miller</a> about the futility of obfuscation. He makes a fair point. Software is an investment of time, and eventually someone will put enough time to reverse engineer even the most daunting project of software engineering. (Hint, hint: Mac OS, Windows, iPhone, you name it.) But that doesn't mean obfuscation doesn't provide a material benefit (for a short period of time) and competitive advantage to companies that were first in the market. Am I right or wrong?</p>
<p>SWFEncrypt is one that many guys on my team have used with some success. Apparently the support for AS3 was iffy until just recently but is confirmed to work in 5.0.4+</p> <p><a href="http://www.amayeta.com/software/swfencrypt/" rel="noreferrer">http://www.amayeta.com/software/swfencrypt/</a></p>
<p>There are several commercial and free action script obfuscators, a <a href="http://www.google.com/search?q=actionscript+obfuscator" rel="nofollow noreferrer">google search</a> turns up several. I can't vouch for any particular one, but I'm sure that they can all still be reverse-engineered to some extent.</p> <p>IMO, if the obfuscator makes your code unreadable by renaming the variables, functions and classes to meaningless/random characters, that is often is a whole heck of a lot of discouragement who wants to read your code or piece together anything more than a trivial program.</p>
44,545
<p>How do I make the computer's internal speaker beep in C# without external speakers?</p>
<p>In .Net 2.0, you can use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.console.beep" rel="nofollow noreferrer"><code>Console.Beep</code></a>.</p> <pre><code>// Default beep Console.Beep(); </code></pre> <p>You can also specify the frequency and length of the beep in milliseconds.</p> <pre><code>// Beep at 5000 Hz for 1 second Console.Beep(5000, 1000); </code></pre>
<p>It is confirmed that <strong>Windows 7 and newer versions</strong> (at least 64bit or both) <strong>do not use system speaker</strong> and instead they route the call to the default sound device.</p> <p>So, using <code>system.beep()</code> in win7/8/10 will not produce sound using internal system speaker. Instead, you'll get a beep sound from external speakers if they are available.</p>
41,553
<p>I'm looking for a lightweight way to make my program (written in C) be able to play audio files on either windows or linux. I am currently using windows native calls, which is essentially just a single call that is passed a filename. I would like something similar that works on linux. </p> <p>The audio files are Microsoft PCM, Single channel, 22Khz</p> <p>Any Suggestions?</p>
<p>Since I'm also looking for an answer for question I did a bit of research, and I haven't find any simple (simple like calling one function) way to play an audio file. But with some lines of code, it is possible even in a portable way using the already mentioned portaudio and libsndfile (LGPL).</p> <p>Here is a small test case I've written to test both libs:</p> <pre><code> #include &lt;portaudio.h&gt; #include &lt;sndfile.h&gt; static int output_cb(const void * input, void * output, unsigned long frames_per_buffer, const PaStreamCallbackTimeInfo *time_info, PaStreamCallbackFlags flags, void * data) { SNDFILE * file = data; /* this should not actually be done inside of the stream callback * but in an own working thread * * Note although I haven't tested it for stereo I think you have * to multiply frames_per_buffer with the channel count i.e. 2 for * stereo */ sf_read_short(file, output, frames_per_buffer); return paContinue; } static void end_cb(void * data) { printf("end!\n"); } #define error_check(err) \ do {\ if (err) { \ fprintf(stderr, "line %d ", __LINE__); \ fprintf(stderr, "error number: %d\n", err); \ fprintf(stderr, "\n\t%s\n\n", Pa_GetErrorText(err)); \ return err; \ } \ } while (0) int main(int argc, char ** argv) { PaStreamParameters out_param; PaStream * stream; PaError err; SNDFILE * file; SF_INFO sfinfo; if (argc &lt; 2) { fprintf(stderr, "Usage %s \n", argv[0]); return 1; } file = sf_open(argv[1], SFM_READ, &sfinfo); printf("%d frames %d samplerate %d channels\n", (int)sfinfo.frames, sfinfo.samplerate, sfinfo.channels); /* init portaudio */ err = Pa_Initialize(); error_check(err); /* we are using the default device */ out_param.device = Pa_GetDefaultOutputDevice(); if (out_param.device == paNoDevice) { fprintf(stderr, "Haven't found an audio device!\n"); return -1; } /* stero or mono */ out_param.channelCount = sfinfo.channels; out_param.sampleFormat = paInt16; out_param.suggestedLatency = Pa_GetDeviceInfo(out_param.device)->defaultLowOutputLatency; out_param.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream(&stream, NULL, &out_param, sfinfo.samplerate, paFramesPerBufferUnspecified, paClipOff, output_cb, file); error_check(err); err = Pa_SetStreamFinishedCallback(stream, &end_cb); error_check(err); err = Pa_StartStream(stream); error_check(err); printf("Play for 5 seconds.\n"); Pa_Sleep(5000); err = Pa_StopStream(stream); error_check(err); err = Pa_CloseStream(stream); error_check(err); sf_close(file); Pa_Terminate(); return 0; } </code></pre> <p>Some notes to the example. It is not good practice to do the data loading inside of the stream callback, but inside an own loading thread. If you need to play several audio files it becomes even more difficult, because not all portaudio backends support multiple streams for one device, for example the OSS backend doesn't, but the ALSA backend does. I don't know how the situation is on windows. Since all your input files are of the same type you could mix them on you own, which complicates the code a bit more, but then you'd have also support for OSS. If you would have also different sample rates or number of channels, it'd become very difficult.</p> <p>So If you don't want to play multiple files at the same time, this could be a solution or at least a start for you.</p>
<p>I like <a href="http://www.fmod.org/" rel="nofollow noreferrer">FMOD</a>. The <a href="http://www.fmod.org/index.php/sales" rel="nofollow noreferrer">license</a> is free for personal use, and very reasonable for small shareware or commercial projects</p>
49,700
<p>Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?</p> <p>How can I make this faster?</p> <p>Compiled with -O3 in g++</p> <pre><code>static const char _hex2asciiU_value[256][2] = { {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} }; std::string char_to_hex( const unsigned char* _pArray, unsigned int _len ) { std::string str; str.resize(_len*2); char* pszHex = &amp;str[0]; const unsigned char* pEnd = _pArray + _len; clock_t stick, etick; stick = clock(); for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) { pszHex[0] = _hex2asciiU_value[*pChar][0]; pszHex[1] = _hex2asciiU_value[*pChar][1]; } etick = clock(); std::cout &lt;&lt; "ticks to hexify " &lt;&lt; etick - stick &lt;&lt; std::endl; return str; } </code></pre> <p><strong>Updates</strong></p> <p>Added timing code</p> <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126">Brian R. Bondy</a>: replace the std::string with a heap alloc'd buffer and change ofs*16 to ofs &lt;&lt; 4 - however the heap allocated buffer seems to slow it down? - result ~11ms</p> <p><a href="https://stackoverflow.com/questions/69115/#69305">Antti Sykäri</a>:replace inner loop with </p> <pre><code> int upper = *pChar &gt;&gt; 4; int lower = *pChar &amp; 0x0f; pszHex[0] = pHex[upper]; pszHex[1] = pHex[lower]; </code></pre> <p>result ~8ms</p> <p><a href="https://stackoverflow.com/questions/69115?sort=votes#69218">Robert</a>: replace <code>_hex2asciiU_value</code> with a full 256-entry table, sacrificing memory space but result ~7ms!</p> <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254">HoyHoy</a>: Noted it was producing incorrect results</p>
<p>At the cost of more memory you can create a full 256-entry table of the hex codes:</p> <pre><code>static const char _hex2asciiU_value[256][2] = { {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} }; </code></pre> <p>Then direct index into the table, no bit fiddling required.</p> <pre><code>const char *pHexVal = pHex[*pChar]; pszHex[0] = pHexVal[0]; pszHex[1] = pHexVal[1]; </code></pre>
<p>Make sure your compiler optimization is turned on to the highest working level.</p> <p>You know, flags like '-O1' to '-03' in gcc.</p>
9,459
<p>All the examples that I can search online use the App.Config mode of specifying the context definition retrieved by </p> <pre><code>contextToGetSprungObjects = ContextRegistry.GetContext(contextname) </code></pre> <p>I want to use </p> <pre><code>contextToGetSprungObjects = new XmlApplicationContext(sXmlFileName) </code></pre> <p>(I'm calling into a DLL (that needs Spring.net) from another executable (MsWord) so app.config approach is out). I tried sneaking in MyDll.dll.config.. didn't fly. On using the XmlApplicationContext approach to read it from a specified xml file, I get the following error </p> <pre><code>{"Error registering object with name '' defined in 'file [D:\\Work\\Seven\\WordAutomation\\ContentControls\\WordDocument1\\bin\\debug\\MyWPFPlotPopup.dll.config]' : There is no parser registered for namespace ''\r\n&lt;configSections&gt;&lt;sectionGroup name=\"spring\"&gt;&lt;section name=\"context\" type=\"Spring.Context.Support.ContextHandler, Spring.Core\" /&gt;&lt;/sectionGroup&gt;&lt;section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" /&gt;&lt;/configSections&gt;"} </code></pre> <p>Which leads me to believe that the two approaches need their xml in a differently shaped bottle. I searched high and low but the schema for the xml that is needed eludes me.. everything I can find uses X.exe.config or Web.config. Can someone point me to a valid xml context defintion for Spring.net?</p> <pre><code>&lt;spring&gt; &lt;context&gt; &lt;context name="MyApplication"&gt; &lt;resource uri="file://Resources/MyApplicationContext.xml"/&gt; &lt;/context&gt; &lt;/context&gt; &lt;/spring&gt; </code></pre> <p>I think this is the relevant section of the app.config that I want Spring.net to readd</p>
<p>register_globals is the invention of the devil. Fortunately in PHP 6.0 it will be entirely disabled. It wasn't just a huge security problem, it makes people confuse. Please turn it off in your php.ini using register_globals = Off More information: <a href="http://us2.php.net/register_globals" rel="nofollow noreferrer">http://us2.php.net/register_globals</a> Also you can check the current settings with the command if (ini_get(register_globals)) echo "turn it off! :)';</p>
<p>After running this:</p> <pre><code>&lt;?php session_start(); $_GET['myvar'] = ''; $_SESSION['myvar'] = $_GET['myvar']; $myvar = 'a_new_string'; var_dump($_SESSION); ?&gt; </code></pre> <p>on PHP 5.2.6 I get this:</p> <pre><code>array(1) { ["myvar"]=&gt; string(0) "" } </code></pre>
38,733
<p>I have a winforms application that doesn't have a shared set of tools that I can provide on a toolbar. But I want to have a toolbar, so I was planning on using that space to provide quick links to the most popular portions of the product. I will eventually add knowledge to the product to know which screens the current user favors and provide those as quick links on the toolbar. But is this a reasonable use of a toolbar for a desktop product, from a design and usability point of view? </p>
<p>Do not automatically add knowledge about what a user prefers to generate a toolbar. Having a dynamically generated toolbar is confusing for users. It's fine if your configuration bar makes suggestions dynamically (i.e. suggesting buttons), but changing the layout itself is evil.</p>
<p>I think a toolbar makes a good aesthetic, but if you merely want to seperate parts of the app then a Tab bar makes more sense for usability.</p> <p>With the advent of tabbed browsing, every user understands the tab concept.</p>
43,014
<p>Is there a way to fall through multiple case statements without stating <code>case value:</code> repeatedly?</p> <p>I know this works:</p> <pre><code>switch (value) { case 1: case 2: case 3: // Do some stuff break; case 4: case 5: case 6: // Do some different stuff break; default: // Default stuff break; } </code></pre> <p>but I'd like to do something like this:</p> <pre><code>switch (value) { case 1,2,3: // Do something break; case 4,5,6: // Do something break; default: // Do the Default break; } </code></pre> <p>Is this syntax I'm thinking of from a different language, or am I missing something?</p>
<p>There is no syntax in C++ nor C# for the second method you mentioned. </p> <p>There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.</p>
<p>For this, you would use a goto statement. Such as:</p> <pre><code> switch(value){ case 1: goto case 3; case 2: goto case 3; case 3: DoCase123(); //This would work too, but I'm not sure if it's slower case 4: goto case 5; case 5: goto case 6; case 6: goto case 7; case 7: DoCase4567(); } </code></pre>
9,409
<p>im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?</p> <pre><code>int value = *min_element(v2.begin(), v2.end()); cout &lt;&lt; "min value at position " &lt;&lt; *find(v2.begin(), v2.end(), value); </code></pre>
<p><code>min_element</code> already gives you the iterator, no need to invoke <code>find</code> (additionally, it's inefficient because it's twice the work). Use <code>distance</code> or the <code>-</code> operator:</p> <pre><code>cout &lt;&lt; "min value at " &lt;&lt; min_element(v2.begin(), v2.end()) - v2.begin(); </code></pre>
<p>The short answer to what you think you asked with "How do I determine position in <code>std::vector&lt;&gt;</code> given an iterator from it?" is the function <code>std::distance</code>.</p> <p>What you probably meant to do, however, was to get the value for the iterator, which you get by dereferencing it:</p> <pre><code>using namespace std; vector&lt;int&gt;::const_iterator it = min_element(v2.begin(), v2.end()); cout &lt;&lt; "min value at position " &lt;&lt; distance(v2.begin(), it) &lt;&lt; " is " &lt;&lt; *it; </code></pre>
22,106
<p>I have a script that generates data in csv format which is sent to the user along with a set of headers that tell the browser it is a .csv file. Everything works great when users (left)click on the link to the script, they are presented with a download dialog with the filename ending in .csv and it suggests using excel, or calc, to open it. However, when users right-click and choose Save As it is being saved with the php script name.</p> <p>Here is the header code:</p> <pre><code>header("Pragma: public"); header("Expires: 0"); // set expiration time header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); $val = date("m_d_Y_g_i"); Header('Content-Disposition: attachment; filename="personal_information_'.$val.'.csv"'); </code></pre> <p>So again, when users left-click it saves the file as personal_information_date.csv; when they right click it saves as download.php. I'm using FF3. Oddly enough, IE7 does not have this problem.</p> <p>Any ideas?</p>
<p>Use mod_rewrite to alias the file from file.csv to file.php, this is a browser issue rather than PHP because by saving the file it isn't running it before it is saving it.</p> <p>So to summarise:</p> <ol> <li>Link to <code>personal_information_date.csv</code></li> <li>Create a <code>mod_rewrite</code> rule that forwards <code>personal_information_date.csv</code> to <code>download.php</code> (e.g.: <code>RewriteRule ^personal_information_date.csv$ download.php</code>).</li> </ol>
<ul> <li>I believe that setting three different mimetypes doesn't help</li> <li>what's $val ? Is this known content or user provided - e.g. could it contain nasty characters (like ") or even linebreaks, e.g. introduce new HTTP header lines?</li> <li>have a look at the HTTP-Headers that arrive at the client. Either the Firefox built-in information or use LiveHttpHeaders (plugin to be found at the Mozilla site - logs all HTTP-Headers) - I'm sure there are more/other plugins for FF available.</li> </ul> <p>Hope this helps.</p>
33,920
<p>Paragraph 6.7.3.8 of the C99 spec states</p> <blockquote>If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type. If the specification of a function type includes any type qualifiers, the behavior is undefined. </blockquote> <p>In the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf" rel="noreferrer">rationale</a> (logical page 87, physical page 94), an example of casting a flat pointer to a (variable length) array pointer is given.</p> <pre><code>void g(double *ap, int n) { double (*a)[n] = (double (*)[n]) ap; /* ... */ a[1][2] /* ... */ } </code></pre> <p>Certainly if the array <code>ap</code> is not modified within the function, it should be marked const, however the cast in</p> <pre><code>void g(const double *ap, int n) { const double (*a)[n] = (const double (*)[n]) ap; /* ... */ } </code></pre> <p>does not preserve the <code>const</code> qualifier since (per 6.7.3.8) it applies to the elements of the target instead of the target itself, which has array type <code>double[n]</code>. This means that compilers will rightly complain if given the appropriate flags (<code>-Wcast-qual</code> for GCC). There is no way to denote a <code>const</code> array type in C, but this cast is very useful and "correct". The <code>-Wcast-qual</code> flag is useful for identifying misuse of array parameters, but the false positives discourage its use. Note that indexing <code>a[i][j]</code> is both more readable and, with many compilers, produces better machine code than <code>ap[i*n+j]</code> since the former allows some integer arithmetic to be hoisted out of inner loops with less analysis.</p> <p>Should compilers just treat this as a special case, effectively lifting qualifiers from the elements to the array type to determine whether a given cast removes qualifiers or should the spec be amended? Assignment is not defined for array types, so would it hurt for qualifiers to always apply to the array type rather than just the elements, in contrast to 6.7.3.8?</p>
<p>This is a known issue that has been discussed several times over the last 10 years at comp.std.c. The bottom line is that the specific case you presented is not currently legal in Standard C; you need to either remove the qualifier or refrain from using a pointer to an array to refer to the qualified elements in the array.</p> <p>If you think you have a good idea to overcome the issue, you can post it to <code>news:comp.std.c</code> for discussion. If others agree that it is a good idea, you or someone else can file a defect report to have the behavior changed (there are several committee members that frequent comp.std.c so feedback from the people who would potentially be reviewing the DR would be useful to have prior to filing it). I think there may be some issues with your proposal to have qualifiers affect the array itself, but I'd have to give it some more thought.</p>
<p>The situation is awkward with pointers (ie, arrays), but here's my recollection of the details:</p> <p><code>const double *ap</code> is a pointer to a constant double;</p> <p><code>double *const ap</code> is a constant pointer to a double;</p> <p><code>const double *const ap</code> is a constant pointer to a constant double;</p> <p>So I believe it is possible to do what you're asking, although I've not tried this in years -- the <code>gcc</code> option you're using wasn't available the last time I did this!</p> <p>EDIT: This answer is not correct for the question - I'm leaving it to preserve the comments below, which clarify the problem for mere mortals (or rusty C developers...)</p>
39,259
<p>I have been hearing the podcast blog for a while, I hope I dont break this. The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p> <p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
<p>In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking:</p> <p><strong>How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?</strong></p> <p>A fairly straight forward solution that you already mentioned is the <em>sp_xml_preparedocument</em>, combined with <em>openxml</em>. </p> <p>Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on <a href="http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx" rel="nofollow noreferrer">Using OPENXML</a>.</p> <pre><code>declare @XmlDocumentHandle int declare @XmlDocument nvarchar(1000) set @XmlDocument = N'&lt;ROOT&gt; &lt;Customer&gt; &lt;FirstName&gt;Will&lt;/FirstName&gt; &lt;LastName&gt;Smith&lt;/LastName&gt; &lt;/Customer&gt; &lt;/ROOT&gt;' -- Create temp table to insert data into create table #Customer ( FirstName varchar(20), LastName varchar(20) ) -- Create an internal representation of the XML document. exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument -- Insert using openxml allows us to read the structure insert into #Customer select FirstName = XmlFirstName, LastName = XmlLastName from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 ) with ( XmlFirstName varchar(20) 'FirstName', XmlLastName varchar(20) 'LastName' ) where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' ) -- Cleanup xml document exec sp_xml_removedocument @XmlDocumentHandle -- Show the data select * from #Customer -- Drop tmp table drop table #Customer </code></pre> <p>If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a <em>string</em> should give you a fairly straight forward way of importing xml into your existing table(s).</p>
<p>If your XML conforms to a particular XSD schema, you can look into using the "xsd.exe" command line tool to generate C# object classes that you can bind the XML to, and then form your insert statements using the properties of those objects: <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx" rel="nofollow noreferrer">MSDN XSD Doc</a></p>
8,449
<p>I recently had a problem during the deployment of a windows service. Four computers did not cause any problems, but on the fifth any attempt to start the service failed due to an exception. The exception stack trace is written to the event log, so I though it should be easy to identify the cause:</p> <pre><code>protected override void OnStart(string[] args) { EventLog.WriteEntry("Starting service", EventLogEntryType.Information); try { //... base.OnStart(args); } catch (Exception ex) { EventLog.WriteEntry("Service can not start. Stack trace:" + ex.StackTrace, EventLogEntryType.Error); Stop(); return; } EventLog.WriteEntry("Service started", EventLogEntryType.Information); } </code></pre> <p>But alas, no information was ever written to the log. I finally traced it to the first log entry being written. It threw an exception because the application event log was full with recent entries, and configured to only overwrite entries older than 7 days.</p> <p>What are the best practices on writing to the event log, considering that I can not change the configuration of the application event log? </p> <p>Should I always put <code>EventLog.WriteEntry</code> in a try block, if yes, how should I handle the exception (writing it to the event log is probably a bad idea), should I check on the event log status in my <code>OnStart</code> method, or do you have any better suggestion?</p>
<p>Use log4net</p> <p>The advantage of using log4net is that you can check the logging and control it with far more flexibility than you will account for within your code.</p> <p>If you were logging to the event log, and seeing problems and no event log entries, you could always have switched to a file-appender log and have seen it working... which would have then told you that it was something to do with the event log.</p> <p>log4net is also defensive, it won't crash your program if it fails to write the log entry. So you wouldn't have seen this happen (so you wouldn't have your logs files, but your program would be running and again you could've specified a second logging method to get log files).</p> <p>The key bit in the log4net documentation is this:</p> <blockquote> <p>[log4net] is a best-effort and fail-stop logging system.</p> <p>By fail-stop, we mean that <strong>log4net will not throw unexpected exceptions at run-time potentially causing your application to crash</strong>. If for any reason, log4net throws an uncaught exception (except for ArgumentException and ArgumentNullException which may be thrown), please send an email to the log4net-user@logging.apache.org mailing list. Uncaught exceptions are handled as serious bugs requiring immediate attention.</p> <p>Moreover, log4net will not revert to System.Console.Out or System.Console.Error when its designated output stream is not opened, is not writable or becomes full. This avoids corrupting an otherwise working program by flooding the user's terminal because logging fails. However, log4net will output a single message to System.Console.Error and System.Diagnostics.Trace indicating that logging can not be performed.</p> </blockquote> <p>(my emphasis)</p> <p>For most things, there is a library that does it better than you will. The best thing is to never re-invent, log4net solves logging in .Net and will make your life easier.</p>
<p>Let's take a step back here:</p> <p>The system event log is there to alert the system administrator that there was a problem with something on the system. You should allow the service start to fail. This will show up in the system error log with a reported source of "Service Control Manager". This means that the sys admin will know about the failure.</p> <p>Next, if you need to troubleshoot then you should log exceptions to a file on disk at the top level of your program. You should also rethrow them so that the service start fails.</p> <p>You can then identify any problems in the system event logs and cross reference the time of the failure into your application logs.</p>
40,472
<p>I'll try to keep this short and simple. I haven't begun writing the code for this project yet, but I'm trying to work out the pre-coding logistics as of right now.</p> <p>What I am looking to do, is create a method of sending data from one/any site, to another remote server, which would generate a response for the user requesting the data be sent.</p> <p>Specifically, a web designer should be able to take a snippet of code I would have available on my website, implement it into their own page(s), and when a user browses their page(s), my service would be available.</p> <p>A specific example, a web designer with a website (<code>helloworld.com</code>) could implement my code into their page (<code>helloworld.com/index.html</code>). When a user is viewing the page (<code>/index.html</code>), the user hovers the mouse over a text word (lemonade) for a couple seconds, a small dialog box pops up beside it, providing the user with some options specific to the text (example of an option would be "Define 'lemonade' at Dictionary.com") that if selected, would be processed at, and a response would be returned from my remote server (<code>myremoteserver.com</code>)</p> <p>Obviously, I would want the code that designers would be using to be as lightweight and standalone as possible. Any ideas as to how I could execute this? Resources I should study, and methods I could implement?</p>
<p>Please do not create another one of those services that annoyingly double-underlines words in web site content and then pops up a ugly, slow-to-load ad over the content if I accidentally mouse over the word. Because that sounds like what you're doing.</p> <p>If you're going to do it anyway, then what the "remote server" will be will probably actually be a bit of client-side JavaScript, in which case <a href="http://json.org/" rel="nofollow noreferrer">JSON</a> is probably your best bet. XML could also work, but even when JavaScript isn't on the other side, I rather like JSON as a <a href="http://en.wikipedia.org/wiki/Serialization" rel="nofollow noreferrer">serialization</a> technique due to its compactness and readability.</p>
<p>I think you are talking about a hyperlink. </p> <p>The part that has you confused is the level of interactivity you want on the client site. Whatever sort of neat UI interface you want to wrap around the link will probably be done in javascript and need to be supplied to that site. The core of what you're asking for </p> <blockquote> <p>text ... that if selected, would be processed at, and a response would be returned from my remote server (myremoteserver.com)</p> </blockquote> <p>is just a hyperlink.</p> <p>There's probably more to it than that though. Explain and we'll try to help. </p>
47,097
<p>I'm going to running thousands of queries into SQL and I need to prevent the duplication of field 'domain'. Never had to do this before and any help would be appreciated.</p>
<p>You probably want to create a "UNIQUE" constraint on the field "Domain" - this constraint will raise an error if you create two rows that have the same domain in the database. For an explanation, see <a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">this tutorial in W3C school</a> -</p> <p><a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">http://www.w3schools.com/sql/sql_unique.asp</a></p> <p>If this doesn't solve your problem, please clarify the database you have chosen to use (MySql?).</p> <p>NOTE: This constraint is completely separate from your choice of PHP as a programming language, it is a SQL database definition thing. A huge advantage of expressing this constraint in SQL is that you can trust the database to preserve the constraint even when people import / export data from the database, your application is buggy or another application shares the database.</p>
<p>I'm not really sure I understood your question, but perhaps you are looking for SQL's <a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">"UNIQUE" constraint</a>. If the query tries to insert a pre-existing value to a field, you (PHP) will be notified about this constraint breach.</p>
34,876
<p>We are migrating our test report data (unit, regression, integration, etc..) from an XML format to a database format for better analysis. Right now the majority of our test analysis is done using the CruiseControl.NET dashboard, but this is limited to primarily the most recent test data. Older test data can be accessed but not easily compared to new test data. We want to pin point problem components and better narrow down bugs. With the onset of tons of information brought on by our newly implemented regression and integration testing I would like to see some better metrics generated (possibly performance and the like). Have you worked with any business intelligence systems that will provide a framework for accurately and easily implementing some sort of analysis and reporting? </p> <p>I have looked into JasperReports and Pentaho but I'm struggling with implemetation of Pentaho at the moment. Should I continue my fight with the system? Is this what I'm looking for? </p>
<p>You could always just use SQL Server Reporting Services and Report Builder (MS's web based designer) or Report Designer (component of Visual studio). It's pretty easy to get this set up too.</p> <ul> <li>Report Builder: <a href="http://msdn.microsoft.com/en-us/library/ms155933.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms155933.aspx</a></li> <li>Report Designer: <a href="http://msdn.microsoft.com/en-us/library/ms157166.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms157166.aspx</a></li> <li>Tutorial: <a href="http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/" rel="nofollow noreferrer">http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/</a></li> <li>How to add Reporting Services to an existing SQL Server: <a href="http://www.mssqltips.com/tip.asp?tip=1444" rel="nofollow noreferrer">http://www.mssqltips.com/tip.asp?tip=1444</a></li> </ul> <p>There are a few end user reporting solutions around as well that make it easier to dynamically create reports, if you're willing to invest a bit of cash.</p> <p>My company produce one: <a href="http://www.rsinteract.com" rel="nofollow noreferrer">http://www.rsinteract.com</a> has a very cheap standard edition with a limited number of reports (30 day free trial). It reports directly off SQL server with Reporting Services installed. It won best of TechEd 2006 - <a href="http://windowsitpro.com/article/articleid/53944/best-of-tech-ed-2006-winners.html" rel="nofollow noreferrer">http://windowsitpro.com/article/articleid/53944/best-of-tech-ed-2006-winners.html</a></p> <p>We actually use ours to analyse the support requests from clients i.e. which component is failing most, who reports the most bugs etc. Not tried it on test data.</p> <p>There's also Proclarity, ApexSQL Report, and Tableau all of which are good.</p>
<p>Which part of Pentaho? </p> <p>The Kettle project has stuff to convert your Cruise Control info and load it into a relational database. That's probably a good module to get working properly, especially if you're almost done figuring it out. I hope you'll share this stuff. I could use it too.</p> <p>The Platform will autoschedule stuff once Kettle has it loading.</p> <p>To make Mondrian really useful you'll need to work out a fact / dimension organization to your test data. That may or may not be worth your trouble at this point. </p> <p>Once you have your data loaded you'll probably be able to get a lot of benefit out of simple SQL queries like this...</p> <pre><code> select * from test where failed='yes' order by testno, date desc </code></pre> <p>and this...</p> <pre><code> select max(date), min(date), testno from test where failed='yes' group by testno order by testno </code></pre> <p>and stuff like that. You might consider creating views in your table server for your favorite queries.</p> <p>There are myriad ways to convert your sql queries into reports, including the pentaho reporting module, BIRT (an eclipse plugin), Crystal Reports, and all kinds of PHP or JSP stuff you could put together.</p>
21,712
<p>Is there anyway to determine if a ResourceManager contains a named resource? Currently I am catching the MissingManifestResourceException but I hate having to use Exceptions for non-exceptional situations. There must be some way to enumerate the name value pairs of a ResourceManager through reflection, or something?</p> <p><strong>EDIT</strong>: A little more detail. The resources are not in executing assembly, however the ResourceManager is working just fine. If I try <code>_resourceMan.GetResourceSet(_defaultCuture, false, true)</code> I get null, whereas if I try <code>_resourceMan.GetString("StringExists")</code> I get a string back.</p>
<p>You can use the ResourceSet to do that, only it loads all the data into memory if you enumerate it. Here y'go:</p> <pre><code> // At startup. ResourceManager mgr = Resources.ResourceManager; List&lt;string&gt; keys = new List&lt;string&gt;(); ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true); foreach (DictionaryEntry o in set) { keys.Add((string)o.Key); } mgr.ReleaseAllResources(); Console.WriteLine(Resources.A); </code></pre>
<p>I think you can use something like <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcenames(VS.80).aspx" rel="nofollow noreferrer">Assembly.GetManifestResourceNames</a> to enumerate the list of resources available in the Assembly's manifest. It isn't pretty and doesn't solve all of the corner cases, but works if required.</p>
19,352
<p>Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc?</p> <p>The goal is to create something like the following...</p> <pre><code>//defined like... public static T Get&lt;T&gt;(this IAnonymous obj, string prop) { return (T)obj.GetType().GetProperty(prop).GetValue(obj, null); } //... //And then used like... var something = new { name = "John", age = 25 }; int age = something.Get&lt;int&gt;("age"); </code></pre> <p>Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape?</p> <p><strong>Note</strong> - I realize that you can write an extension method for the <strong>object</strong> class, but that seems like a little overkill, in my opinion.</p>
<p>EDIT: The list below applies to C# anonymous types. VB.NET has different rules - in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile...</p> <p>You can't identify it in a generic constraint, but:</p> <ul> <li>It will be a class (rather than interface, enum, struct etc)</li> <li>It will have the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx" rel="noreferrer">CompilerGeneratedAttribute</a> applied to it</li> <li>It will override Equals, GetHashCode and ToString</li> <li>It will be in the global namespace</li> <li>It will not be nested in another type</li> <li>It will be internal</li> <li>It will be sealed</li> <li>It will derive directly from <code>object</code></li> <li>It will be generic with as many type parameters as properties. (You <em>can</em> have a non-generic anonymous type, with no properties. It's a bit pointless though.)</li> <li>Each property will have a type parameter with a name including the property name, and will be of that type parameter, e.g. the Name property becomes a property of type &lt;>_Name</li> <li>Each property will be public and read-only</li> <li>For each property there will be a corresponding readonly private field</li> <li>There will be no other properties or fields</li> <li>There will be a constructor taking one parameter corresponding to each type parameter, in the same order as the type parameters</li> <li>Each method and property will have the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx" rel="noreferrer">DebuggerHiddenAttribute</a> applied to it.</li> <li>The name of the type will start with "&lt;>" and contain "AnonymousType"</li> </ul> <p>Very little of this is guaranteed by the specification, however - so it could all change in the next version of the compiler, or if you use Mono etc.</p>
<p>For the purposes of extension methods there is no way to distinguish an anonymous type. Extension methods work by specifying a method for a compile time nameable type. Anonymous types are un-namable and therefore not visible at compile time. This makes them incompatible with extension methods. </p>
40,680
<p>Does anyone know of a JS-based terminal client? Either something that initiates an SSH connection with a remote host or even something that simply communicates with a remote PHP script to execute commands and retrieve output. Does such a thing exist?</p>
<p>Check <a href="http://anyterm.org/" rel="nofollow noreferrer">Anyterm</a>, it uses a XmlHttpRequest channel to communicate with a daemon that uses a pseudo-terminal to communicate with a shell or other application.</p>
<p>So far <a href="http://www.webessence.nl/projects/jsdom.ui.console/index.html" rel="nofollow noreferrer">JSDom Shell</a> is the only thing I have found, which seems relatively barebones but practical. If there are any other more substantial options, feel free to share!</p>
37,663
<p>I'm thinking of an application that would try to prove the "<a href="http://en.wikipedia.org/wiki/Six_degrees_of_separation" rel="nofollow noreferrer">Six degrees of separation</a>" theory with a set of users that are part of a social network.</p> <p>I would have those elements:</p> <ol> <li>A couple of users for which I'd like to prove the six degrees theory</li> <li>For each user, I know the list of friends in the social network</li> </ol> <p>Which is the best algorithm to see if the two users are connected, with which degree and show the eventual steps in the connection?</p>
<p>Finding the degree of separation between two people in a social network is just a special case of finding the shortest path between two points in a graph. The most common approach is <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="nofollow noreferrer">Dijkstra's algorithm</a>, but see also a longer discussion of the <a href="http://en.wikipedia.org/wiki/Shortest_path_problem" rel="nofollow noreferrer">Shortest path problem</a>.</p> <p>In addition, by running an All-pairs shortest path algorithm, you could find out the minimum, maximum, and average number of degrees of separation for the entire network.</p>
<p>Some additional background material:</p> <p>To solve this problem generally, you'd want to avoid web scraping and other ad-hoc techniques that are specific to one social network. Instead, you will probably want to look into <a href="http://gmpg.org/xfn/" rel="nofollow noreferrer">XHTML Friends Network (XFN)</a> which is a way to use the rel="" attribute of a hyperlink to indicate the relationship between the target of that hyperlink and you. There is also a competing standard called <a href="http://www.foaf-project.org/" rel="nofollow noreferrer">FOAF</a> which uses <a href="http://www.w3.org/RDF/" rel="nofollow noreferrer">RDF</a>.</p> <p>These <a href="http://www.microformats.org" rel="nofollow noreferrer">microformats</a> have been around for a while, but support for them has grown a great deal just recently. StackOverflow uses "me" in the link on your profile page. WordPress blogs provide an easy way in the editing interface for the blogroll to add these tags. Many social sites use these in links between friends to indicate relationships.</p> <p>Because of this, Google has gotten interested in this, and is starting to mine this data. They have a <a href="http://code.google.com/apis/socialgraph/" rel="nofollow noreferrer">Social Graph API</a> that can mine both XFN and FOAF data to do exactly some of the things you want to do. I suggest you start there. The nice thing about Google's API is since they are mining this all over the web, you can widen out your search beyond the specific social network you had in mind.</p>
29,312
<p>Even nowadays I often see underscores in Java variables and methods. An example are member variables (like &quot;m_count&quot; or &quot;_count&quot;). As far as I remember, to use underscores in these cases is called bad style by <a href="https://en.wikipedia.org/wiki/Sun_Microsystems" rel="nofollow noreferrer">Sun</a>.</p> <p>The only place they should be used is in constants (like in &quot;public final static int IS_OKAY = 1;&quot;), because constants should be all upper case and not <a href="https://en.wikipedia.org/wiki/Camel_case" rel="nofollow noreferrer">camel case</a>. Here, the underscore should make the code more readable.</p> <p>Do you think using underscores in Java is bad style? If so (or not), why?</p>
<p>If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that.</p> <p>The biggest thing about coding style is <em>consistency</em>. If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start.</p>
<p>It's just your own style, not a bad style code nor a good style code. It just differentiates our code with the others.</p>
18,102
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt" rel="noreferrer">timsort</a> used outside of CPython? Does it make sense?</p>
<p>Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general.</p> <p>There is currently an <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6804124" rel="noreferrer">effort underway</a> to replace Java's "modified merge sort" with timsort, and the initial results are quite positive.</p>
<p>The description you linked looks completely general.</p>
18,675
<p>Evidently hash keys are compared in a case-sensitive manner.</p> <pre><code>$ perl -e '%hash = ( FOO =&gt; 1 ); printf "%s\n", ( exists $hash{foo} ) ? "Yes" : "No";' No $ perl -e '%hash = ( FOO =&gt; 1 ); printf "%s\n", ( exists $hash{FOO} ) ? "Yes" : "No";' Yes </code></pre> <p>Is there a setting to change that for the current script?</p>
<p>You will have to use a tied hash. For example <a href="http://search.cpan.org/~markov/Hash-Case/lib/Hash/Case/Preserve.pod" rel="noreferrer">Hash::Case::Preserve</a>.</p>
<p><code>grep</code> should do the trick if you make the pattern match case insensitive:</p> <p><code>perl -e '%hash = ( FOO =&gt; 1 ); printf "%s\n", ( scalar(grep (/^foo$/i, keys %hash)) &gt; 0) ? "Yes" : "No";'</code></p> <p>If you have more then one key with various spelling you may need to check if the match is greater than 1 as well.</p>
39,949
<p>What is the best solution to build several CDT C++ projects from the command line? The projects have references and so it is not possible to just build single projects.</p>
<p>This feature has been added in CDT 6 (Final build due June 15th 2009). You can download the final release candidate from builds page: download.eclipse.org/tools/cdt/builds/6.0.0/.</p> <p>Using a release of Eclipse 3.5 + CDT 6, you can import, build and clean-build projects and the workspace using the following options sent to Eclipse at the command line:</p> <pre><code>eclipse -nosplash -application org.eclipse.cdt.managedbuilder.core.headlessbuild -import {[uri:/]/path/to/project} -build {project_name | all} -cleanBuild {projec_name | all} </code></pre> <p>On Windows, use <a href="https://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F" rel="noreferrer"><code>eclipsec.exe</code></a> instead of <code>eclipse.exe</code> to have build output written to stdout/stderr and so that the call blocks until completion.</p> <p>The '<em>-application</em>' switch instructs Eclipse to run the CDT headless builder rather than starting the workbench. The other switches can be used individually or together. This means you can checkout a project using a shell script of your own, '<em>-import</em>' it into a workspace, and '<em>-build</em>' it using the Managedbuilder's headless builder.</p> <p>Use the '<em>-data</em>' switch to specify the workspace to use, which can be an empty temporary directory, see the runtime documentation for other switches supported by the platform runtime: <a href="http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html" rel="noreferrer">help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html</a></p> <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186847#c24" rel="noreferrer">bug 186847 comment 24</a> and onwards for more detail on the committed functionality.</p>
<p>We do this in our existing build.</p> <p>Put a makefile in all your external references and your toplevel project. In your "all" rule, have it run: make -C ./externalref1 make -C ./externalref2 etc</p> <p>we actually define the external dependencies in a variable: EXT_DEP = externalref1 externalref2 then use the subst (substitute) command to kick off all the sub-makes using the correct call.</p>
44,856
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow noreferrer">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
<p>Please please please please please please please don't do this.</p> <p>urllib and urllib2 are your friends.</p> <p>Read <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow noreferrer">the "missing" urllib2 manual</a> if you are having trouble with it.</p>
<p>Use urllib2. Or <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">BeautifulSoup</a>.</p>
39,022
<p>How do you include a file that is more than 2 directories back. I know you can use <code>../index.php</code> to include a file that is 2 directories back, but how do you do it for 3 directories back? Does this make sense? I tried <code>.../index.php</code> but it isn't working.</p> <p>I have a file in <code>/game/forum/files/index.php</code> and it uses PHP include to include a file. Which is located in <code>/includes/boot.inc.php</code>; <code>/</code> being the root directory.</p>
<p><code>..</code> selects the parent directory from the current. Of course, this can be chained:</p> <pre><code>../../index.php </code></pre> <p>This would be two directories up.</p>
<p>I saw your answers and I used include path with syntax</p> <pre><code>require_once '../file.php'; // server internal error 500 </code></pre> <p>and http server (Apache 2.4.3) returned internal error 500.</p> <p>When I changed the path to</p> <pre><code>require_once '/../file.php'; // OK </code></pre> <p>everything is fine.</p>
19,693
<p>Here's the scenario:</p> <p>I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.</p> <p>Here is the code so far:</p> <pre><code>&lt;input type="textbox" id="tb" /&gt; &lt;input alt="Search.aspx?KeepThis=true&amp;TB_iframe=true&amp;height=500&amp;width=700" class="thickbox" title="Search" type="button" value="Search" /&gt; </code></pre> <p>Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set.</p>
<p>Just handle the onclick of your button to run a function that calls <code>tb_show()</code>, passing the value of the text box. Something like</p> <pre><code>... onclick = "doSearch()" ... function doSearch() { tb_show(caption, 'Search.aspx?KeepThis=true&amp;q=\"' + $('input#tb').val() + '\"&amp;TB_iframe=true&amp;height=500&amp;width=700'); } </code></pre>
<p>Here is an idea. I don't think it is very pretty but should work:</p> <pre><code>$('input#tb').blur(function(){ var url = $('input.thickbox').attr('alt'); var tbVal = $(this).val(); // add the textbox value into the query string here // url = .. $('input.thickbox').attr('alt', url); }); </code></pre> <p>Basically, you update the button alt tag every time the textbox loses focus. Instead, you could also listen to key strokes and update after every one. </p> <p>As far as updateing the query string, I'll let you figure out the best way. I can see putting a placeholder in there like: &amp;TB=TB_PLACEHOLDER. Then you can just do a string replace.</p>
32,173
<p>I have a client application that once in while notifies about its progress a service. The method call to the service is marked with IsOneWay=true, because the notification doesn't need any return value and I don't want to delay.</p> <p>The client may notify about errors to the service, and afterward it terminates.</p> <p>The question is: does a oneway method call returns to the caller code after it sent the message? or it queues the message and later on it is sent by another thread?</p> <p>The two processes (the client and the service) are on the same machine, and I noticed that sometimes (when the machine is overloaded) the service doesn't get the error notification. I suspect that the second option I mentioned happens, but I am not sure.</p> <p>If I am right, how can I make sure the notification is send and keep the method oneway?</p>
<p>Good question. Before client application calls a method it opens the channel. The channel is used for all data communication. There are two ways of sending: 1) reliable session - when your packets are deleveried reliably and cracked packets are resent, 2) ordering - when requests on the service are computed in the order they were transfered from client (not how they are delivered). If you have reliable ordered session and service host is getting some problems with data your after closing application, host will try to ask the client resent data and after no responce reject all you request. In other situation (unreliable) after opening channel you can send data and destroy communication, oneway method will compute you request, if there will not be exception.</p> <p>To test some possibilities with service problem (not exactly your client paroblem however is helpful) I create a solution:</p> <p>1) Library project "WcfContracts" with one file "IService1.cs":</p> <pre><code> [ServiceContract] public interface IService1 { [OperationContract] void ThrowException(); [OperationContract(IsOneWay=true)] void ThrowExceptionUseIsOneWay(); } </code></pre> <p>2) Console project "WcfConsoleHoster" which has reference two "WcfContracts", and consists of the three files:</p> <p>a) Service1.cs, which is service implementation</p> <pre><code>public class Service1 : WcfContracts.IService1 { public void ThrowException() { throw new Exception("Basic exception"); } public void ThrowExceptionUseIsOneWay() { throw new Exception("Basic exception using IsOneWay=true"); } } </code></pre> <p>b) Program.cs, which has default entry point and just starts the service</p> <pre><code>static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(Service1)); host.Open(); Console.WriteLine("host 1 opened"); Console.ReadKey(); } </code></pre> <p>c) Service "App.config"</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service behaviorConfiguration="behavourHttpGet" name="WcfConsoleHoster.Service1"&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8732/Design_Time_Addresses/WcfConsoleHoster/Service1/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;endpoint binding="wsHttpBinding" contract="WcfContracts.IService1" /&gt; &lt;endpoint address ="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="behavourHttpGet"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p>3) Console project "WcfConsoleClient", which simply calls the service</p> <p>a) In "Program.cs"</p> <pre><code>Console.WriteLine("Wcf client. Press any key to start"); Console.ReadKey(); ChannelFactory&lt;IService1&gt; factory = new ChannelFactory&lt;IService1&gt;("Service1_Endpoint"); IService1 channel = factory.CreateChannel(); //Call service method channel.ThrowException(); Console.WriteLine("Operation executed"); Console.ReadKey(); </code></pre> <p>b) Client "App.config"</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;client&gt; &lt;endpoint name="Service1_Endpoint" address="http://localhost:8732/Design_Time_Addresses/WcfConsoleHoster/Service1/" binding="wsHttpBinding" contract="WcfContracts.IService1"&gt; &lt;/endpoint&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <hr> <p><strong>1. Throwing exception.</strong> First, we call <em>two way method</em> wich throws exception in the server host. Then this exception goes back to the client and channel raises it on the client side, application is destroyed. Of course you can handle this with try()catch{} block.</p> <p>Let's look the same with <em>one way method</em> by calling <code>channel.ThrowExceptionUseIsOneWay();</code>. Exception is raised in the service host, but there is no exception on the client side and we get "Operation executed". It is important to realize that channel will be unavailable for the next use.</p> <p>So <code>IsOneWay=true</code> works as expected - it sends message only in one way. You cannot return any object from method(void is expected) and you cannot use FaultContract, or get InvalidOperationException after the service start up.</p> <p><strong>2. Thread.Sleep().</strong> Next test is on massive operation with <code>Thread.Sleep()</code>. <code>IService1</code> is extended to </p> <pre><code> [OperationContract] int ThreadSleep(); [OperationContract(IsOneWay=true)] </code></pre> <p>and the realization in Service1.cs is <em>waiting for 5 seconds</em></p> <pre><code>public int ThreadSleep() { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); return 1; } public void ThreadSleepUseIsOneWay() { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); } </code></pre> <p>Now a bit modification for the client for counting elapsed calling time</p> <pre><code>System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); //call methode channel.ThreadSleep(); stopwatch.Stop(); Console.WriteLine(string.Format("Operation executed in {0} seconds", stopwatch.Elapsed.Seconds)); Console.ReadKey(); </code></pre> <p>Calling <em>two way method</em> <code>ThreadSleep()</code> has the result "Operation executed in 7 seconds" (5 sec for thread sleep + 2 sec for channel initialization). </p> <p><code>One way method</code> with calling <code>channel.ThreadSleepUseIsOneWay()</code> has the result "0 seconds"! There is no waiting for the service response! </p> <p>It is best to use <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx" rel="nofollow">NetNamedPipeBinding</a>, which is reliable and fast connection on the same machine.</p>
<p>I agree with Timothy. I also want to add that the WCF service keeps a queue for incoming messages. That queue may become full if the service isn't able to process messages as fast as they are coming in. When the incoming queue becomes full, WCF will drop new messages.</p> <p>I'm not sure what happens on the client side if one-way messages are dropped though. I assume that no exception/fault is thrown but I don't know that for sure.</p>
45,097
<p>Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database. </p> <pre><code>public enum ORDERFIELDS { OrderID("Order_ID"); private String FieldName; private ORDERFIELDS(String fname) { this.FieldName = fname; } public String getFieldName() { return FieldName; } } </code></pre>
<p>All enums implicitly extend <code>java.lang.Enum</code>. Since Java does not support multiple inheritance, an enum cannot extend anything else.</p>
<p>For a throwback to the pre-Java 5 days, take a look at <a href="http://java.sun.com/developer/Books/effectivejava/Chapter5.pdf" rel="nofollow noreferrer">Item 21, Chapter 5,Effective Java by Josh Bloch</a>. He talks about extending "enums" by adding values, but perhaps you could use some of the techniques to add a new method? </p>
27,357
<p>I've been trying to add a swf over a swf on a html page, it's working fine in Firefox, but in IE, the one that's added first is always on top of the other one. I used z-index but it's not working, does anyone know how to solve this? Thanks.</p> <p>I already added wmode:transparent, it is working in firefox but not in IE 6.</p>
<p><strong><code>static_cast</code></strong> is the first cast you should attempt to use. It does things like implicit conversions between types (such as <code>int</code> to <code>float</code>, or pointer to <code>void*</code>), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating <code>static_cast</code> isn't necessary, but it's important to note that the <code>T(something)</code> syntax is equivalent to <code>(T)something</code> and should be avoided (more on that later). A <code>T(something, something_else)</code> is safe, however, and guaranteed to call the constructor.</p> <p><code>static_cast</code> can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through <code>virtual</code> inheritance. It does not do checking, however, and it is undefined behavior to <code>static_cast</code> down a hierarchy to a type that isn't actually the type of the object.</p> <hr> <p><strong><code>const_cast</code></strong> can be used to remove or add <code>const</code> to a variable; no other C++ cast is capable of removing it (not even <code>reinterpret_cast</code>). It is important to note that modifying a formerly <code>const</code> value is only undefined if the original variable is <code>const</code>; if you use it to take the <code>const</code> off a reference to something that wasn't declared with <code>const</code>, it is safe. This can be useful when overloading member functions based on <code>const</code>, for instance. It can also be used to add <code>const</code> to an object, such as to call a member function overload.</p> <p><code>const_cast</code> also works similarly on <code>volatile</code>, though that's less common.</p> <hr> <p><strong><code>dynamic_cast</code></strong> is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The <code>dynamic_cast</code> will seek out the desired object and return it if possible. If it can't, it will return <code>nullptr</code> in the case of a pointer, or throw <code>std::bad_cast</code> in the case of a reference.</p> <p><code>dynamic_cast</code> has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using <code>virtual</code> inheritance. It also can only go through public inheritance - it will always fail to travel through <code>protected</code> or <code>private</code> inheritance. This is rarely an issue, however, as such forms of inheritance are rare.</p> <hr> <p><strong><code>reinterpret_cast</code></strong> is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an <code>int</code>, or all sorts of other nasty things. Largely, the only guarantee you get with <code>reinterpret_cast</code> is that normally if you cast the result back to the original type, you will get the exact same value (but <strong><em>not</em></strong> if the intermediate type is smaller than the original type). There are a number of conversions that <strong><code>reinterpret_cast</code></strong> cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.</p> <hr> <p><strong>C-style cast</strong> and <strong>function-style cast</strong> are casts using <code>(type)object</code> or <code>type(object)</code>, respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:</p> <ul> <li><code>const_cast</code></li> <li><code>static_cast</code> (though ignoring access restrictions)</li> <li><code>static_cast</code> (see above), then <code>const_cast</code></li> <li><code>reinterpret_cast</code></li> <li><code>reinterpret_cast</code>, then <code>const_cast</code></li> </ul> <p>It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a <code>reinterpret_cast</code>, and the latter should be preferred when explicit casting is needed, unless you are sure <code>static_cast</code> will succeed or <code>reinterpret_cast</code> will fail. Even then, consider the longer, more explicit option.</p> <p>C-style casts also ignore access control when performing a <code>static_cast</code>, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.</p>
<p>Nice feature of <code>reinterpret_cast</code>, not mentioned in the other answers, is that it allows us to create a sort of <code>void*</code> pointer for function types. Normally, for object types one uses <code>static_cast</code> to retrieve the original type of a pointer stored in <code>void*</code>:</p> <pre><code> int i = 13; void *p = &amp;i; auto *pi = static_cast&lt;int*&gt;(p); </code></pre> <p>For functions, we must use <code>reinterpret_cast</code> twice:</p> <pre><code>#include&lt;iostream&gt; using any_fcn_ptr_t = void(*)(); void print(int i) { std::cout &lt;&lt; i &lt;&lt;std::endl; } int main() { //Create type-erased pointer to function: auto any_ptr = reinterpret_cast&lt;any_fcn_ptr_t&gt;(&amp;print); //Retrieve the original pointer: auto ptr = reinterpret_cast&lt; void(*)(int) &gt;(any_ptr); ptr(7); } </code></pre> <p>With <code>reinterpret_cast</code> we can even get a similar sort-of-void* pointer for pointers to member functions.</p> <p>As with plain <code>void*</code> and <code>static_cast</code>, C++ guarantees that <code>ptr</code> points to <code>print</code> function (as long as we pass the correct type to <code>reinterpret_cast</code>).</p>
43,013
<p>What is the best way to keep your configuration files (e.g httpd.conf, my.cnf, .bashrc ...) under version control? In adition to the versioning benefit, I want the solution to work as backup as well, so that I can bring a brand new server and checkout (or export) the config files out of SVN directly</p> <p>A good touch will be to store the config file`s original path as well.</p>
<p>I revision-control my configuration files, but I use <a href="http://git.or.cz/" rel="nofollow noreferrer">git</a> instead of svn (which is easier when you have multiple machines). I have a bash script (called <code>install.sh</code>), also under the repository, which either copies or symlinks the files to their appropriate location on a machine.</p> <p>So if I need to set up on a new machine, I just do a git clone of the repository (which is equivalent to an svn checkout) and run my <code>install.sh</code> to set up my config files in the appropriate locations. Having <code>install.sh</code> around means that I'm also storing the config files' original path, as you indicated you'd like.</p>
<p>I do this for several machines, ranging from old Solaris 8 boxes to Mac OS X, and I have a really simple layout:</p> <p>In my repository I have the following:</p> <pre><code>&lt;root&gt;/common /.emacs.d /.bash_common /scripts # platform-independent binary tools &lt;root&gt;/linux .bashrc .emacs ... &lt;root&gt;/solaris .bashrc .emacs ... &lt;root&gt;/osx .bashrc .emacs ... </code></pre> <p>Each of the OS homedirs has an svn:externals reference to .emacs.d, .bash_common, and scripts, so those are not duplicated.</p> <p>In addition, I have a .bash_hostconfig in the linux and solaris directories with host-specific path configuration and such, because I have a very different setup at work than I do at home (FC5-8 and RHEL3-5, depending on where I am).</p> <p>So, between these things, I have a pretty simple process for getting up and running on a new machine: I simply check out the /$platform into a temporary directory, and then overwrite everything in $HOME with those files. I don't need to store the original path, because it's always relative to $HOME this way.</p>
21,060
<p>I have a client and a server both written in .net 3.5 so I've got no interoperability issues.</p> <p>The server is fully accessible on port 443 (I'm hosting it so I can open other ports if needed)</p> <p>The client is however less accessible. It's often behind a corporate firewall, or behind a NAT, or uses an http/https proxy to connect to the internet.</p> <p>I need to establish an encrypted bi-directionnal communication between the client and the server.</p> <p>The two bidirectional channels provided in WCF don't seem to do the trick :</p> <ul> <li><p>NetTcpBinding doesn't seem to support http proxies (<a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/0900c7f0-948f-45f1-a53e-9434921af5ce" rel="nofollow noreferrer">source</a>)</p></li> <li><p>WSDualHttpBinding requires that the client has a public URI that provides a callback endpoint for the service, which is unfortunately not the case here (<a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.wsdualhttpbinding.aspx" rel="nofollow noreferrer">source</a>)</p></li> </ul> <p>Can WCF establish this kind of encrypted bi-directional connection (silently using https tunelling if needed), without tuning the firewall/proxy settings on the client side ?</p>
<p>You are looking for a technology called Comet. <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow noreferrer">Wikipedia entry</a> If you Google "comet wcf" you'll find articles that should point you in the right direction.</p>
<p>Yes. You can use WSDualHttpBinding or NetTcpBinding.</p>
49,462