qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
226,896
<p>I am currently trying to create an Exception handler built into my windows service that, on an unhandled exception, sends a message to another program. I have built the method and gotten the communication working, but it seems that every time my program throws the error, (I have a raise call in the code to force it.) windows catches it instead and the Handler isn't called. Can anyone explain what I am doing wrong?.</p> <p>Simplified Code to explain:</p> <pre><code>procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin WriteLn('Display: ' + Exception(ExceptObject).Message); //send Message Here end; </code></pre> <p>I call this code to run it:</p> <pre><code>WriteLn('Starting'); ExceptProc := @ExceptionHandler; unhandled(); </code></pre> <p>I would expect the output to be:</p> <blockquote> <p>Starting<br/> Display: Unhandled</p> </blockquote> <p>but all it does is display:</p> <blockquote> <p>Starting</p> </blockquote> <p>Then windows returns a command prompt after about 5 seconds.</p> <p>Why isn't the handler being properly called?</p> <p>P.S. I've been running these tests in a console app for testing.</p> <p>EDIT:</p> <p>Here's some more information:</p> <p>Apparently when you have an assigned ExceptProc, your program shouldn't throw the normal runtime 217 error. I'm guessing this is what windows is catching, From what I can see however, my program is throwing that runtime error, and I can't get an ErrorProc to catch it either.</p>
[ { "answer_id": 227079, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 0, "selected": false, "text": "<p>Interesting.</p>\n\n<p>Custom exception handler is called if you run the app in Delphi IDE (tried with 2007) but not if you run it from the command prompt.</p>\n\n<p>Another interesting thing - I changed the main program code to </p>\n\n<pre><code>begin\n WriteLn('Starting');\n try\n ExceptProc := @ExceptionHandler;\n Unhandled;\n finally Readln; end;\nend.\n</code></pre>\n\n<p>and noticed that exception message is only displayed AFTER I press the Enter key (to get some input to the Readln). Therefore, your handler is not called when exception occurs but when it is handled (in implicit try..except that wraps all your code). Make sense.</p>\n\n<p>Must be something with this implicit try..except then, but I lack a non-Delphi debugger on this machine and can't dig further. Maybe somebody else knows the answer ...</p>\n" }, { "answer_id": 227285, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<p>You are missing a call to <a href=\"http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx\" rel=\"noreferrer\">SetErrorMode()</a>:</p>\n\n<pre><code>SetErrorMode(SEM_NOGPFAULTERRORBOX);\n</code></pre>\n\n<p>This is needed to prevent the OS <a href=\"http://msdn.microsoft.com/en-us/library/ms681401(VS.85).aspx\" rel=\"noreferrer\">unhandled exception filter</a> from showing a dialog box / displaying the debugger attach dialog box. Here's a complete sample that behaves as expected on my machine:</p>\n\n<pre><code>{$apptype console}\n\nuses Windows, SysUtils;\n\nprocedure unhandled();\nbegin\n raise Exception.Create('Unhandled');\nend;\n\nprocedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer);\nbegin\n Writeln('here');\n WriteLn('Display: ' + Exception(ExceptObject).Message);\n Flush(Output);\n Halt(1);\nend;\n\nprocedure Go;\nbegin\n unhandled;\nend;\n\nbegin\n ExceptProc := @ExceptionHandler;\n SetErrorMode(SEM_NOGPFAULTERRORBOX);\n Go;\nend.\n</code></pre>\n\n<p>Note that the effect of SetErrorMode() is global across all threads in the running process.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16059/" ]
I am currently trying to create an Exception handler built into my windows service that, on an unhandled exception, sends a message to another program. I have built the method and gotten the communication working, but it seems that every time my program throws the error, (I have a raise call in the code to force it.) windows catches it instead and the Handler isn't called. Can anyone explain what I am doing wrong?. Simplified Code to explain: ``` procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin WriteLn('Display: ' + Exception(ExceptObject).Message); //send Message Here end; ``` I call this code to run it: ``` WriteLn('Starting'); ExceptProc := @ExceptionHandler; unhandled(); ``` I would expect the output to be: > > Starting > > Display: Unhandled > > > but all it does is display: > > Starting > > > Then windows returns a command prompt after about 5 seconds. Why isn't the handler being properly called? P.S. I've been running these tests in a console app for testing. EDIT: Here's some more information: Apparently when you have an assigned ExceptProc, your program shouldn't throw the normal runtime 217 error. I'm guessing this is what windows is catching, From what I can see however, my program is throwing that runtime error, and I can't get an ErrorProc to catch it either.
You are missing a call to [SetErrorMode()](http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx): ``` SetErrorMode(SEM_NOGPFAULTERRORBOX); ``` This is needed to prevent the OS [unhandled exception filter](http://msdn.microsoft.com/en-us/library/ms681401(VS.85).aspx) from showing a dialog box / displaying the debugger attach dialog box. Here's a complete sample that behaves as expected on my machine: ``` {$apptype console} uses Windows, SysUtils; procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin Writeln('here'); WriteLn('Display: ' + Exception(ExceptObject).Message); Flush(Output); Halt(1); end; procedure Go; begin unhandled; end; begin ExceptProc := @ExceptionHandler; SetErrorMode(SEM_NOGPFAULTERRORBOX); Go; end. ``` Note that the effect of SetErrorMode() is global across all threads in the running process.
226,910
<p>I find it curious that the most obvious way to create <code>Date</code> objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.</p> <p>How do you check that a date, given as a combination of day, month, and year, is a valid date?</p> <p>For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.</p>
[ { "answer_id": 226920, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 6, "selected": true, "text": "<p>The current way is to use the calendar class. It has the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setLenient%28boolean%29\" rel=\"noreferrer\">setLenient</a> method that will validate the date and throw and exception if it is out of range as in your example. </p>\n\n<p>Forgot to add:\nIf you get a calendar instance and set the time using your date, this is how you get the validation.</p>\n\n<pre><code>Calendar cal = Calendar.getInstance();\ncal.setLenient(false);\ncal.setTime(yourDate);\ntry {\n cal.getTime();\n}\ncatch (Exception e) {\n System.out.println(\"Invalid date\");\n}\n</code></pre>\n" }, { "answer_id": 227232, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 5, "selected": false, "text": "<p>You can use <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\">SimpleDateFormat</a></p>\n\n<p>For example something like:</p>\n\n<pre><code>boolean isLegalDate(String s) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n sdf.setLenient(false);\n return sdf.parse(s, new ParsePosition(0)) != null;\n}\n</code></pre>\n" }, { "answer_id": 892204, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 6, "selected": false, "text": "<p>As shown by @Maglob, the basic approach is to test the conversion from string to date using <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\">SimpleDateFormat.parse</a>. That will catch invalid day/month combinations like 2008-02-31.</p>\n\n<p>However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:</p>\n\n<p><strong>Invalid characters in the date string</strong>\nSurprisingly, 2008-02-2x will \"pass\" as a valid date with locale format = \"yyyy-MM-dd\" for example. Even when isLenient==false.</p>\n\n<p><strong>Years: 2, 3 or 4 digits?</strong>\nYou may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret \"12-02-31\" differently depending on whether your format was \"yyyy-MM-dd\" or \"yy-MM-dd\")</p>\n\n<h2>A Strict Solution with the Standard Library</h2>\n\n<p>So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.</p>\n\n<pre><code> Date parseDate(String maybeDate, String format, boolean lenient) {\n Date date = null;\n\n // test date string matches format structure using regex\n // - weed out illegal characters and enforce 4-digit year\n // - create the regex based on the local format string\n String reFormat = Pattern.compile(\"d+|M+\").matcher(Matcher.quoteReplacement(format)).replaceAll(\"\\\\\\\\d{1,2}\");\n reFormat = Pattern.compile(\"y+\").matcher(reFormat).replaceAll(\"\\\\\\\\d{4}\");\n if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {\n\n // date string matches format structure, \n // - now test it can be converted to a valid date\n SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();\n sdf.applyPattern(format);\n sdf.setLenient(lenient);\n try { date = sdf.parse(maybeDate); } catch (ParseException e) { }\n } \n return date;\n } \n\n // used like this:\n Date date = parseDate( \"21/5/2009\", \"d/M/yyyy\", false);\n</code></pre>\n\n<p>Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: \"d/MM/yy\", \"yyyy-MM-dd\", and so on. The format string for the current locale could be obtained like this:</p>\n\n<pre><code>Locale locale = Locale.getDefault();\nSimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );\nString format = sdf.toPattern();\n</code></pre>\n\n<h2>Joda Time - Better Alternative?</h2>\n\n<p>I've been hearing about <a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">joda time</a> recently and thought I'd compare. Two points:</p>\n\n<ol>\n<li>Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat</li>\n<li>Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own <a href=\"http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormatter.html\" rel=\"noreferrer\">DateTimeFormatter</a> for this purpose)</li>\n</ol>\n\n<p>It's quite simple to use:</p>\n\n<pre><code>import org.joda.time.format.*;\nimport org.joda.time.DateTime;\n\norg.joda.time.DateTime parseDate(String maybeDate, String format) {\n org.joda.time.DateTime date = null;\n try {\n DateTimeFormatter fmt = DateTimeFormat.forPattern(format);\n date = fmt.parseDateTime(maybeDate);\n } catch (Exception e) { }\n return date;\n}\n</code></pre>\n" }, { "answer_id": 893408, "author": "Tom", "author_id": 106320, "author_profile": "https://Stackoverflow.com/users/106320", "pm_score": 1, "selected": false, "text": "<p>Two comments on the use of SimpleDateFormat.</p>\n\n<blockquote>\n <p>it should be declared as a static instance\n if declared as static access should be synchronized as it is not thread safe</p>\n</blockquote>\n\n<p>IME that is better that instantiating an instance for each parse of a date.</p>\n" }, { "answer_id": 2622589, "author": "Ben", "author_id": 314577, "author_profile": "https://Stackoverflow.com/users/314577", "pm_score": 3, "selected": false, "text": "<p>An alternative strict solution using the standard library is to perform the following:</p>\n\n<p>1) Create a strict SimpleDateFormat using your pattern</p>\n\n<p>2) Attempt to parse the user entered value using the format object</p>\n\n<p>3) If successful, reformat the Date resulting from (2) using the same date format (from (1))</p>\n\n<p>4) Compare the reformatted date against the original, user-entered value. If they're equal then the value entered strictly matches your pattern.</p>\n\n<p>This way, you don't need to create complex regular expressions - in my case I needed to support all of SimpleDateFormat's pattern syntax, rather than be limited to certain types like just days, months and years.</p>\n" }, { "answer_id": 4528089, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 2, "selected": false, "text": "<p>Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:</p>\n\n<pre><code>package cruft;\n\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class DateValidator\n{\n private static final DateFormat DEFAULT_FORMATTER;\n\n static\n {\n DEFAULT_FORMATTER = new SimpleDateFormat(\"dd-MM-yyyy\");\n DEFAULT_FORMATTER.setLenient(false);\n }\n\n public static void main(String[] args)\n {\n for (String dateString : args)\n {\n try\n {\n System.out.println(\"arg: \" + dateString + \" date: \" + convertDateString(dateString));\n }\n catch (ParseException e)\n {\n System.out.println(\"could not parse \" + dateString);\n }\n }\n }\n\n public static Date convertDateString(String dateString) throws ParseException\n {\n return DEFAULT_FORMATTER.parse(dateString);\n }\n}\n</code></pre>\n\n<p>Here's the output I get:</p>\n\n<pre><code>java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011\ncould not parse 32-11-2010\ncould not parse 31-02-2010\narg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011\n\nProcess finished with exit code 0\n</code></pre>\n\n<p>As you can see, it does handle both of your cases nicely.</p>\n" }, { "answer_id": 4528094, "author": "Aravind Yarram", "author_id": 127320, "author_profile": "https://Stackoverflow.com/users/127320", "pm_score": 6, "selected": false, "text": "<p>Key is <strong>df.setLenient(false);</strong>. This is more than enough for simple cases. If you are looking for a more robust (I doubt) and/or alternate libraries like joda-time then look at the <a href=\"https://stackoverflow.com/a/892204/1076848\">answer by the user \"tardate\"</a></p>\n\n<pre><code>final static String DATE_FORMAT = \"dd-MM-yyyy\";\n\npublic static boolean isDateValid(String date) \n{\n try {\n DateFormat df = new SimpleDateFormat(DATE_FORMAT);\n df.setLenient(false);\n df.parse(date);\n return true;\n } catch (ParseException e) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 15382305, "author": "Imran", "author_id": 1412471, "author_profile": "https://Stackoverflow.com/users/1412471", "pm_score": 0, "selected": false, "text": "<p>Above methods of date parsing are nice , i just added new check in existing methods that double check the converted date with original date using formater, so it works for almost each case as i verified. e.g. 02/29/2013 is invalid date.\nGiven function parse the date according to current acceptable date formats. It returns true if date is not parsed successfully.</p>\n\n<pre><code> public final boolean validateDateFormat(final String date) {\n String[] formatStrings = {\"MM/dd/yyyy\"};\n boolean isInvalidFormat = false;\n Date dateObj;\n for (String formatString : formatStrings) {\n try {\n SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();\n sdf.applyPattern(formatString);\n sdf.setLenient(false);\n dateObj = sdf.parse(date);\n System.out.println(dateObj);\n if (date.equals(sdf.format(dateObj))) {\n isInvalidFormat = false;\n break;\n }\n } catch (ParseException e) {\n isInvalidFormat = true;\n }\n }\n return isInvalidFormat;\n }\n</code></pre>\n" }, { "answer_id": 17710658, "author": "Ziya", "author_id": 1325331, "author_profile": "https://Stackoverflow.com/users/1325331", "pm_score": 3, "selected": false, "text": "<p>I suggest you to use <code>org.apache.commons.validator.GenericValidator</code> class from apache.</p>\n\n<p><code>GenericValidator.isDate(String value, String datePattern, boolean strict);</code></p>\n\n<p>Note: strict - Whether or not to have an exact match of the datePattern.</p>\n" }, { "answer_id": 18666219, "author": "Dresden Sparrow", "author_id": 2084112, "author_profile": "https://Stackoverflow.com/users/2084112", "pm_score": 2, "selected": false, "text": "<p>This is working great for me. Approach suggested above by Ben. </p>\n\n<pre><code>private static boolean isDateValid(String s) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n try {\n Date d = asDate(s);\n if (sdf.format(d).equals(s)) {\n return true;\n } else {\n return false;\n }\n } catch (ParseException e) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 23438158, "author": "Matthias Braun", "author_id": 775954, "author_profile": "https://Stackoverflow.com/users/775954", "pm_score": 4, "selected": false, "text": "<h1>java.time</h1>\n<p>With the <a href=\"https://docs.oracle.com/javase/tutorial/datetime/\" rel=\"nofollow noreferrer\">Date and Time API</a> (<a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes) built into Java 8 and later, you can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"nofollow noreferrer\"><code>LocalDate</code></a> class.</p>\n<pre><code>public static boolean isDateValid(int year, int month, int day) {\n try {\n LocalDate.of(year, month, day);\n } catch (DateTimeException e) {\n return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 30528952, "author": "Sufian", "author_id": 1276636, "author_profile": "https://Stackoverflow.com/users/1276636", "pm_score": 3, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java/4528094#4528094\">Aravind's answer</a> to fix the problem pointed out by <a href=\"https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java/30528952#comment35086192_4528094\">ceklock in his comment</a>, I added a method to verify that the <code>dateString</code> doesn't contain any invalid character.</p>\n\n<p>Here is how I do:</p>\n\n<pre><code>private boolean isDateCorrect(String dateString) {\n try {\n Date date = mDateFormatter.parse(dateString);\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n return matchesOurDatePattern(dateString); //added my method\n }\n catch (ParseException e) {\n return false;\n }\n}\n\n/**\n * This will check if the provided string matches our date format\n * @param dateString\n * @return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)\n */\nprivate boolean matchesDatePattern(String dateString) {\n return dateString.matches(\"^\\\\d+\\\\-\\\\d+\\\\-\\\\d+\");\n}\n</code></pre>\n" }, { "answer_id": 35197612, "author": "mawa", "author_id": 5882412, "author_profile": "https://Stackoverflow.com/users/5882412", "pm_score": 3, "selected": false, "text": "<p>I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.</p>\n\n<pre><code>public boolean isDateValid(String dateString, String pattern)\n{ \n try\n {\n SimpleDateFormat sdf = new SimpleDateFormat(pattern);\n if (sdf.format(sdf.parse(dateString)).equals(dateString))\n return true;\n }\n catch (ParseException pe) {}\n\n return false;\n}\n</code></pre>\n" }, { "answer_id": 39276958, "author": "TennisVisuals", "author_id": 4483303, "author_profile": "https://Stackoverflow.com/users/4483303", "pm_score": 0, "selected": false, "text": "<p>Here's what I did for Node environment using no external libraries:</p>\n\n<pre><code>Date.prototype.yyyymmdd = function() {\n var yyyy = this.getFullYear().toString();\n var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based\n var dd = this.getDate().toString();\n return zeroPad([yyyy, mm, dd].join('-')); \n};\n\nfunction zeroPad(date_string) {\n var dt = date_string.split('-');\n return dt[0] + '-' + (dt[1][1]?dt[1]:\"0\"+dt[1][0]) + '-' + (dt[2][1]?dt[2]:\"0\"+dt[2][0]);\n}\n\nfunction isDateCorrect(in_string) {\n if (!matchesDatePattern) return false;\n in_string = zeroPad(in_string);\n try {\n var idate = new Date(in_string);\n var out_string = idate.yyyymmdd();\n return in_string == out_string;\n } catch(err) {\n return false;\n }\n\n function matchesDatePattern(date_string) {\n var dateFormat = /[0-9]+-[0-9]+-[0-9]+/;\n return dateFormat.test(date_string); \n }\n}\n</code></pre>\n\n<p>And here is how to use it:</p>\n\n<pre><code>isDateCorrect('2014-02-23')\ntrue\n</code></pre>\n" }, { "answer_id": 39649815, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 5, "selected": false, "text": "<h1>tl;dr</h1>\n\n<p>Use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html#STRICT\" rel=\"noreferrer\">strict mode</a> on <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html\" rel=\"noreferrer\"><code>java.time.DateTimeFormatter</code></a> to parse a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a>. Trap for the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeParseException.html\" rel=\"noreferrer\"><code>DateTimeParseException</code></a>.</p>\n\n<pre><code>LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.\n \"31/02/2000\" , // Input string.\n DateTimeFormatter // Define a formatting pattern to match your input string.\n .ofPattern ( \"dd/MM/uuuu\" )\n .withResolverStyle ( ResolverStyle.STRICT ) // Specify leniency in tolerating questionable inputs.\n)\n</code></pre>\n\n<p>After parsing, you might check for reasonable value. For example, a birth date within last one hundred years.</p>\n\n<pre><code>birthDate.isAfter( LocalDate.now().minusYears( 100 ) )\n</code></pre>\n\n<h1>Avoid legacy date-time classes</h1>\n\n<p>Avoid using the troublesome old date-time classes shipped with the earliest versions of Java. Now supplanted by the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> classes.</p>\n\n<h1><code>LocalDate</code> &amp; <code>DateTimeFormatter</code> &amp; <code>ResolverStyle</code></h1>\n\n<p>The <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone.</p>\n\n<pre><code>String input = \"31/02/2000\";\nDateTimeFormatter f = DateTimeFormatter.ofPattern ( \"dd/MM/uuuu\" );\ntry {\n LocalDate ld = LocalDate.parse ( input , f );\n System.out.println ( \"ld: \" + ld );\n} catch ( DateTimeParseException e ) {\n System.out.println ( \"ERROR: \" + e );\n}\n</code></pre>\n\n<p>The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html\" rel=\"noreferrer\"><code>java.time.DateTimeFormatter</code></a> class can be set to parse strings with any of three leniency modes defined in the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html\" rel=\"noreferrer\"><code>ResolverStyle</code></a> enum. We insert a line into the above code to try each of the modes.</p>\n\n<pre><code>f = f.withResolverStyle ( ResolverStyle.LENIENT );\n</code></pre>\n\n<p>The results:</p>\n\n<ul>\n<li><code>ResolverStyle.LENIENT</code><br />ld: 2000-03-02</li>\n<li><code>ResolverStyle.SMART</code><br />ld: 2000-02-29</li>\n<li><code>ResolverStyle.STRICT</code><br />ERROR: java.time.format.DateTimeParseException: Text '31/02/2000' could not be parsed: Invalid date 'FEBRUARY 31'</li>\n</ul>\n\n<p>We can see that in <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html#LENIENT\" rel=\"noreferrer\"><code>ResolverStyle.LENIENT</code></a> mode, the invalid date is moved forward an equivalent number of days. In <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html#SMART\" rel=\"noreferrer\"><code>ResolverStyle.SMART</code></a> mode (the default), a logical decision is made to keep the date within the month and going with the last possible day of the month, Feb 29 in a leap year, as there is no 31st day in that month. The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html#STRICT\" rel=\"noreferrer\"><code>ResolverStyle.STRICT</code></a> mode throws an exception complaining that there is no such date.</p>\n\n<p>All three of these are reasonable depending on your business problem and policies. Sounds like in your case you want the strict mode to reject the invalid date rather than adjust it.</p>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/bDIIx.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bDIIx.png\" alt=\"Table of all date-time types in Java, both modern and legacy.\"></a></p>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/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/en/java/javase/11/docs/api/java.base/java/util/Date.html\" rel=\"noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html\" rel=\"noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html\" rel=\"noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<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>\n\n<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=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> classes.</p>\n\n<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>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<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.\n\n<ul>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<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>\n\n<ul>\n<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>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li>\n<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>\n</ul></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/JV8ms.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JV8ms.png\" alt=\"Table of which java.time library to use with which version of Java or Android\"></a></p>\n\n<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>\n" }, { "answer_id": 44917419, "author": "ashishdhiman2007", "author_id": 2301721, "author_profile": "https://Stackoverflow.com/users/2301721", "pm_score": 0, "selected": false, "text": "<pre><code>// to return valid days of month, according to month and year\nint returnDaysofMonth(int month, int year) {\n int daysInMonth;\n boolean leapYear;\n leapYear = checkLeap(year);\n if (month == 4 || month == 6 || month == 9 || month == 11)\n daysInMonth = 30;\n else if (month == 2)\n daysInMonth = (leapYear) ? 29 : 28;\n else\n daysInMonth = 31;\n return daysInMonth;\n}\n\n// to check a year is leap or not\nprivate boolean checkLeap(int year) {\n Calendar cal = Calendar.getInstance();\n cal.set(Calendar.YEAR, year);\n return cal.getActualMaximum(Calendar.DAY_OF_YEAR) &gt; 365;\n}\n</code></pre>\n" }, { "answer_id": 53091974, "author": "db07", "author_id": 9177302, "author_profile": "https://Stackoverflow.com/users/9177302", "pm_score": 0, "selected": false, "text": "<p>Here is I would check the date format:</p>\n\n<pre><code> public static boolean checkFormat(String dateTimeString) {\n return dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\") || dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:\\\\d{2}:\\\\d{2}\")\n || dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}\") || dateTimeString\n .matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}Z\") ||\n dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:\\\\d{2}:\\\\d{2}Z\");\n}\n</code></pre>\n" }, { "answer_id": 56888385, "author": "Suheb Rafique", "author_id": 7785060, "author_profile": "https://Stackoverflow.com/users/7785060", "pm_score": 0, "selected": false, "text": "<pre><code> public static String detectDateFormat(String inputDate, String requiredFormat) {\n String tempDate = inputDate.replace(\"/\", \"\").replace(\"-\", \"\").replace(\" \", \"\");\n String dateFormat;\n\n if (tempDate.matches(\"([0-12]{2})([0-31]{2})([0-9]{4})\")) {\n dateFormat = \"MMddyyyy\";\n } else if (tempDate.matches(\"([0-31]{2})([0-12]{2})([0-9]{4})\")) {\n dateFormat = \"ddMMyyyy\";\n } else if (tempDate.matches(\"([0-9]{4})([0-12]{2})([0-31]{2})\")) {\n dateFormat = \"yyyyMMdd\";\n } else if (tempDate.matches(\"([0-9]{4})([0-31]{2})([0-12]{2})\")) {\n dateFormat = \"yyyyddMM\";\n } else if (tempDate.matches(\"([0-31]{2})([a-z]{3})([0-9]{4})\")) {\n dateFormat = \"ddMMMyyyy\";\n } else if (tempDate.matches(\"([a-z]{3})([0-31]{2})([0-9]{4})\")) {\n dateFormat = \"MMMddyyyy\";\n } else if (tempDate.matches(\"([0-9]{4})([a-z]{3})([0-31]{2})\")) {\n dateFormat = \"yyyyMMMdd\";\n } else if (tempDate.matches(\"([0-9]{4})([0-31]{2})([a-z]{3})\")) {\n dateFormat = \"yyyyddMMM\";\n } else {\n return \"Pattern Not Added\";\n//add your required regex\n }\n try {\n String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));\n\n return formattedDate;\n } catch (Exception e) {\n //\n return \"\";\n }\n\n }\n</code></pre>\n" }, { "answer_id": 56907180, "author": "Pravin Bansal", "author_id": 6095444, "author_profile": "https://Stackoverflow.com/users/6095444", "pm_score": 0, "selected": false, "text": "<p>setLenient to false if you like a strict validation</p>\n\n<pre><code>public boolean isThisDateValid(String dateToValidate, String dateFromat){\n\n if(dateToValidate == null){\n return false;\n }\n\n SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);\n sdf.setLenient(false);\n\n try {\n\n //if not valid, it will throw ParseException\n Date date = sdf.parse(dateToValidate);\n System.out.println(date);\n\n } catch (ParseException e) {\n\n e.printStackTrace();\n return false;\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 57268013, "author": "vijay", "author_id": 7682476, "author_profile": "https://Stackoverflow.com/users/7682476", "pm_score": 2, "selected": false, "text": "<p>looks like <strong><em>SimpleDateFormat</em></strong> is not checking the pattern strictly even after <em>setLenient(false);</em> method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.</p>\n\n<pre><code>import java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeParseException;\npublic boolean isValidFormat(String dateString, String pattern) {\n boolean valid = true;\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);\n try {\n formatter.parse(dateString);\n } catch (DateTimeParseException e) {\n valid = false;\n }\n return valid;\n}\n</code></pre>\n" }, { "answer_id": 58209655, "author": "skay", "author_id": 560410, "author_profile": "https://Stackoverflow.com/users/560410", "pm_score": 0, "selected": false, "text": "<p>With 'legacy' date format, we can format the result and compare it back to the source.</p>\n\n<pre><code> public boolean isValidFormat(String source, String pattern) {\n SimpleDateFormat sd = new SimpleDateFormat(pattern);\n sd.setLenient(false);\n try {\n Date date = sd.parse(source);\n return date != null &amp;&amp; sd.format(date).equals(source);\n } catch (Exception e) {\n return false;\n }\n}\n</code></pre>\n\n<p>This execerpt says 'false' to source=01.01.04 with pattern '01.01.2004'</p>\n" }, { "answer_id": 68069005, "author": "SANAT", "author_id": 2024527, "author_profile": "https://Stackoverflow.com/users/2024527", "pm_score": 0, "selected": false, "text": "<p>We can use the <code>org.apache.commons.validator.GenericValidator</code>'s method directly without adding the whole library:</p>\n<pre><code>public static boolean isValidDate(String value, String datePattern, boolean strict) {\n\n if (value == null\n || datePattern == null\n || datePattern.length() &lt;= 0) {\n\n return false;\n }\n\n SimpleDateFormat formatter = new SimpleDateFormat(datePattern, Locale.ENGLISH);\n formatter.setLenient(false);\n\n try {\n formatter.parse(value);\n } catch(ParseException e) {\n return false;\n }\n\n if (strict &amp;&amp; (datePattern.length() != value.length())) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 72899575, "author": "ucMedia", "author_id": 7756492, "author_profile": "https://Stackoverflow.com/users/7756492", "pm_score": 0, "selected": false, "text": "<p>A simple and elegant way for <strong>Android developers</strong> (Java 8 not required):</p>\n<pre><code>// month value is 1-based. e.g., 1 for January.\npublic static boolean isDateValid(int year, int month, int day) {\n Calendar calendar = Calendar.getInstance();\n try {\n calendar.setLenient(false);\n calendar.set(year, month-1, day);\n calendar.getTime();\n return true;\n } catch (Exception e) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 73434373, "author": "Nagendra Rao", "author_id": 19813614, "author_profile": "https://Stackoverflow.com/users/19813614", "pm_score": 0, "selected": false, "text": "<p>Below code works with dd/MM/yyyy format and can be used to check NotNull,NotEmpty as well.</p>\n<p>public static boolean validateJavaDate(String strDate) {</p>\n<pre><code> if (strDate != null &amp;&amp; !strDate.isEmpty() &amp;&amp; !strDate.equalsIgnoreCase(&quot; &quot;)) {\n {\n\n SimpleDateFormat date = new SimpleDateFormat(&quot;dd/MM/yyyy&quot;);\n date.setLenient(false);\n\n try {\n Date javaDate = date.parse(strDate);\n System.out.println(strDate + &quot; Valid Date format&quot;);\n }\n\n catch (ParseException e) {\n System.out.println(strDate + &quot; Invalid Date format&quot;);\n return false;\n }\n return true;\n }\n\n } else {\n System.out.println(strDate + &quot;----&gt; Date is Null/Empty&quot;);\n return false;\n }\n\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26595/" ]
I find it curious that the most obvious way to create `Date` objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar. How do you check that a date, given as a combination of day, month, and year, is a valid date? For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
The current way is to use the calendar class. It has the [setLenient](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setLenient%28boolean%29) method that will validate the date and throw and exception if it is out of range as in your example. Forgot to add: If you get a calendar instance and set the time using your date, this is how you get the validation. ``` Calendar cal = Calendar.getInstance(); cal.setLenient(false); cal.setTime(yourDate); try { cal.getTime(); } catch (Exception e) { System.out.println("Invalid date"); } ```
226,931
<p>I believe this is a common question / problem but have not been able to find a good clean concise answer.</p> <p><strong>The Problem</strong></p> <p>How to map entities that appear to have an inheritance relationship:</p> <pre><code>Company Supplier Manufacturer Customer </code></pre> <p>However, a Supplier can be a Manufacturer.</p> <p>or</p> <pre><code>Person Doctor Patient Employee </code></pre> <p>Where a Patient can be a Doctor or can be an Employee.</p> <p><strong>Suggestion: Use Roles</strong></p> <p>In discussions on the NHibernate forums, the response is often that this is multiple inheritance. </p> <p><a href="http://forum.hibernate.org/viewtopic.php?t=959076" rel="nofollow noreferrer">http://forum.hibernate.org/viewtopic.php?t=959076</a></p> <p>They solution suggested is to use composition or to use "Roles". However, I cannot find any examples or explanation on how exactly to do that.</p> <blockquote> <p>"Favor composition over inheritance." Remember that little goodie from class? In this instance I have to agree that you are trying multiple inheritance-- not possible in C# or Java (yet). I, personally, would encourage you to think about re-modeling so you have a Person object and a person has a one-to-many collection of Roles.</p> </blockquote>
[ { "answer_id": 227933, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": true, "text": "<p>You probably want to consider using the Roles. So a Role will have a set of Persons. Or a Person will have a set of Roles or both. This would probably imply that there is an Association class that maps persons to roles. </p>\n\n<p>Define a Person class with all properties that are common to people. Then define a Role super class and DoctorRole, PatientRole and EmployeeRole sub classes (Assuming that each role has different properties). </p>\n\n<p>The Person class can have a Collection of roles defined and the Role class can have a Collection of people defined. Or it might be easier to create an Association class, lets call it PeopleRole.</p>\n\n<p><a href=\"http://www.hibernate.org/hib_docs/nhibernate/html/example-mappings.html\" rel=\"nofollow noreferrer\">This</a> page explains how to do the mapping so that PeopleRole is a composite element. Look at the Order/Product/LineItem example. Your Person is like Order, PeopleRole is like LineItem and Role is like Product.</p>\n" }, { "answer_id": 229105, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 2, "selected": false, "text": "<p>It seems to me that this is more a question around how to model a domain well, rather than an NHibernate mapping issue.</p>\n\n<p>Once you've sorted out your domain modelling, I think you'll find the NHibernate mapping falls out relatively easily.</p>\n\n<p>One place to look to get your head around the idea of modeling Roles is to look for \"<a href=\"http://en.wikipedia.org/wiki/UML_colors\" rel=\"nofollow noreferrer\">Color Modeling</a>\" - <a href=\"http://www.nebulon.com/\" rel=\"nofollow noreferrer\">Jeff de Luca</a> has <a href=\"http://www.nebulon.com/articles/fdd/adsposters.html\" rel=\"nofollow noreferrer\">some resources</a>, though the idea originated with <a href=\"http://en.wikipedia.org/wiki/Peter_Coad\" rel=\"nofollow noreferrer\">Peter Coad</a></p>\n\n<p>The basic idea is to separate the identity of a participant from the role they play in an activity.</p>\n\n<p>For example, you might have a Person object that captures the identify of a particular person.</p>\n\n<p>Then, a completely separate object \"Student\" that captures the additional information to record the enrolment of a person as a student. Each instance of Student would have a reference to the person enrolled. A single person may be related to many \"Student\" records, one for each distinct enrolment.</p>\n\n<p>In parallel, you could have a distinct \"Tutor\" object that records employment details when someone is hired to teach students in one-on-one situations. The Tutor object captures the additional details around how someone is employed as a tutor.</p>\n\n<p>This structure gives you great flexibility - one person (Joe Bloggs) may just be a student, another person (Jane Doe) may just be a tutor, and a third (Chuck Norris) may be both.</p>\n\n<p>Also, introducing another role (Lecturer, Marker, Administrator) becomes easier because the additions don't require changes to existing objects.</p>\n" }, { "answer_id": 1577812, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 1, "selected": false, "text": "<p>I came across a bit more commentary you might find relevant:</p>\n\n<p>In a <a href=\"http://blog.nakedobjects.net/?p=60\" rel=\"nofollow noreferrer\">blog post on the Naked Objects blog</a> a few different approaches are outlined discussing the pros and cons of each.</p>\n\n<ul>\n<li>Using an 'Any' association mapping</li>\n<li>Modelling roles as classes</li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30469/" ]
I believe this is a common question / problem but have not been able to find a good clean concise answer. **The Problem** How to map entities that appear to have an inheritance relationship: ``` Company Supplier Manufacturer Customer ``` However, a Supplier can be a Manufacturer. or ``` Person Doctor Patient Employee ``` Where a Patient can be a Doctor or can be an Employee. **Suggestion: Use Roles** In discussions on the NHibernate forums, the response is often that this is multiple inheritance. <http://forum.hibernate.org/viewtopic.php?t=959076> They solution suggested is to use composition or to use "Roles". However, I cannot find any examples or explanation on how exactly to do that. > > "Favor composition over inheritance." > Remember that little goodie from > class? In this instance I have to > agree that you are trying multiple > inheritance-- not possible in C# or > Java (yet). I, personally, would > encourage you to think about > re-modeling so you have a Person > object and a person has a one-to-many > collection of Roles. > > >
You probably want to consider using the Roles. So a Role will have a set of Persons. Or a Person will have a set of Roles or both. This would probably imply that there is an Association class that maps persons to roles. Define a Person class with all properties that are common to people. Then define a Role super class and DoctorRole, PatientRole and EmployeeRole sub classes (Assuming that each role has different properties). The Person class can have a Collection of roles defined and the Role class can have a Collection of people defined. Or it might be easier to create an Association class, lets call it PeopleRole. [This](http://www.hibernate.org/hib_docs/nhibernate/html/example-mappings.html) page explains how to do the mapping so that PeopleRole is a composite element. Look at the Order/Product/LineItem example. Your Person is like Order, PeopleRole is like LineItem and Role is like Product.
226,953
<p>If I have hundreds/thousands of client computers WCP'ing to my server, should I respond with a '200 OK' type message stating that I received the data and stored it in the db successfully?</p> <p>Is this already built-into WCF?</p>
[ { "answer_id": 227011, "author": "Whisk", "author_id": 908, "author_profile": "https://Stackoverflow.com/users/908", "pm_score": 1, "selected": false, "text": "<p>There's 2 ways you could do this - return a value from your wcf call indicating success or failure, or assume success and use a callback to tell the client if there's a problem. </p>\n\n<p>My preference would be to use a <a href=\"http://msdn.microsoft.com/en-us/library/ms730149.aspx\" rel=\"nofollow noreferrer\">one-way</a> service call with a <a href=\"http://msdn.microsoft.com/en-us/library/ms731064.aspx\" rel=\"nofollow noreferrer\">duplex service</a> and use a callback contract for the service to notify the client of a failure. There's a good description of callback contracts <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163537.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://dotnetaddict.dotnetdevelopersjournal.com/wcf_alarmclock.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I think you get a nicer, more asynchronous architecture if you follow the second path, but for simple applications just returning success or failure may be easier.</p>\n" }, { "answer_id": 227027, "author": "James Bender", "author_id": 22848, "author_profile": "https://Stackoverflow.com/users/22848", "pm_score": 2, "selected": false, "text": "<p>Be default your service will return an \"OK\" message to the client (even if your service method specifies a void return type) unless an exception is thrown. The client will wait until it recieves this message before continuing on with it's life.</p>\n\n<p>So based on your question you are getting the behavior you want by default.</p>\n\n<p>If you don't want that, I would agree with Whisk and mark your operation as One Way (a setting in your operation contract).</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 228116, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 4, "selected": false, "text": "<p>There are three messaging patterns mentioned here:</p>\n\n<ol>\n<li>Synchronous request-response </li>\n<li>Asynchronous send (fire and forget with one-way service)</li>\n<li>Asynchronous request-response (duplex service call with one-way service)</li>\n</ol>\n\n<p>All three display different messaging behaviour, and the pattern to be used should be chosen based on your needs. </p>\n\n<p>For your requirement of returning a success to the client when the data has been persisted to the database, options 1 or 3 are appropriate.</p>\n\n<h3>Option 1</h3>\n\n<p>This is the default configuration.</p>\n\n<p>This returns a 200 response on the same http connection once the service has completed all its tasks. This means that calls to the service will block while waiting for the response - your client will hang until the service has written to the database and done anything else it needs.</p>\n\n<h3>Option 2</h3>\n\n<p>Returns a 202 response so long as the transport layer and messaging infrastructure layer succeeds. The 202 returned indicates that the message has been accepted. From the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\" rel=\"nofollow noreferrer\">http rfc</a>: </p>\n\n<blockquote>\n <p>The request has been accepted for processing, but the processing has not been completed. (...) The 202 response is intentionally non-committal.</p>\n</blockquote>\n\n<p>This means that your client will continue execution as soon as the service infrastructure has successfully started the service, and you will receive no information about whether the database call succeeds or not.</p>\n\n<h3>Option 3</h3>\n\n<p>Similar to option 2, the response is an http 202, not a 200, but now when you call the service from the client you provide an <code>InstanceContext</code> object that specifies an object to handle the call back. The client regains control and a new thread waits asynchronously for the service response informing you of success or failure. </p>\n\n<hr>\n\n<p>Below is some more info about implementing these patterns in WCF. After writing it, it is pretty long but there are a couple of useful comments as well as the code.</p>\n\n<p>As Whisk mentioned, Juval Lowy has an article covering a lot this detail (and more!) <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163537.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n\n<h3>Option 1</h3>\n\n<p>This is the default behaviour in WCF so you should not need to do anything - it works with lots of different bindings including wsHttpBinding and basicHttpBinding.</p>\n\n<p>One thing to note is that the behaviour described with your client hanging waiting for the 200 response occurrs even if you have a void Operation like so:</p>\n\n<pre><code>[ServiceContract]\ninterface IMyServiceContract\n{\n [OperationContract] \n void DoSomeThing(InputMessage Message);\n}\n</code></pre>\n\n<h3>Option 2</h3>\n\n<p>To set an operation as one-way you simply decorate it as so:</p>\n\n<pre><code>[ServiceContract]\ninterface IMyServiceContract\n{\n [OperationContract(IsOneWay = true)] \n void DoSomeThing(InputMessage Message);\n}\n</code></pre>\n\n<p>Methods decorated in this way must only have a return type of void. One gotcha is that the service will happily build and you won't get an exception saying the service config is invalid until you connect to it.</p>\n\n<h3>Option 3</h3>\n\n<p>The interface code for creating a duplex callback service is:</p>\n\n<pre><code>[ServiceContract(CallbackContract = typeof(IMyContractCallback))]\ninterface IMyContract\n{\n [OperationContract(IsOneWay=true)] \n void DoSomeThing(InputMessage Message);\n}\n\npublic interface IMyContractCallback\n{\n [OperationContract(IsOneWay = true)]\n void ServiceResponse(string result); \n}\n</code></pre>\n\n<p>And on the client side you need something like so to set up the callback:</p>\n\n<pre><code>public class CallbackHandler : IMyContractCallback \n{\n #region IEchoContractCallback Members\n\n public void ServiceResponse(string result)\n {\n //Do something with the response\n }\n\n #endregion\n}\n\n// And in the client when you set up the service call:\n\nInstanceContext instanceContext = new InstanceContext(new CallbackHandler());\nMyContractClient client = new MyContractClient(instanceContext);\n\nInputMessage msg = new InputMessage();\n\nclient.DoSomething(msg); \n</code></pre>\n\n<p>In the service you would perhaps have some code like:</p>\n\n<pre><code>class MyContractImplementation : IMyContract\n{\n public void DoSomeThing(MyMessage Message)\n {\n\n string responseMessage;\n\n try\n {\n //Write to the database\n responseMessage = \"The database call was good!\";\n }\n catch (Exception ex)\n {\n responseMessage = ex.Message;\n }\n\n Callback.ServiceResponse(responseMessage);\n }\n}\n</code></pre>\n\n<p>One important thing to note, that caught me out at first, is to be careful about exceptions. If you: </p>\n\n<ul>\n<li><p>Consume an exception, you will get no warning of the error (but the callback will happen)</p></li>\n<li><p>Throw an unhandled exception, the service will terminate and the client will not even get the callback.</p></li>\n</ul>\n\n<p>That is one big disadvantage of this method compared with Option 1, Option 1 will return the exception when an unhandled exception is thrown.</p>\n" }, { "answer_id": 228408, "author": "pettys", "author_id": 27846, "author_profile": "https://Stackoverflow.com/users/27846", "pm_score": 0, "selected": false, "text": "<p>I think the question could use a little more elaboration in order to answer correctly. Primary, which type of binding are you currently using?</p>\n\n<p>If you're using a binding that supports reliability, and you just want to be sure, from the client side, that server did indeed receive the message, then just turn reliability on and you're good. With this on, WCF will, under the hood automatically, have each side of the conversation say:\n \"You got it?\"\n \"I got it. You got it?\"\n \"I got it.\"</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I have hundreds/thousands of client computers WCP'ing to my server, should I respond with a '200 OK' type message stating that I received the data and stored it in the db successfully? Is this already built-into WCF?
There are three messaging patterns mentioned here: 1. Synchronous request-response 2. Asynchronous send (fire and forget with one-way service) 3. Asynchronous request-response (duplex service call with one-way service) All three display different messaging behaviour, and the pattern to be used should be chosen based on your needs. For your requirement of returning a success to the client when the data has been persisted to the database, options 1 or 3 are appropriate. ### Option 1 This is the default configuration. This returns a 200 response on the same http connection once the service has completed all its tasks. This means that calls to the service will block while waiting for the response - your client will hang until the service has written to the database and done anything else it needs. ### Option 2 Returns a 202 response so long as the transport layer and messaging infrastructure layer succeeds. The 202 returned indicates that the message has been accepted. From the [http rfc](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html): > > The request has been accepted for processing, but the processing has not been completed. (...) The 202 response is intentionally non-committal. > > > This means that your client will continue execution as soon as the service infrastructure has successfully started the service, and you will receive no information about whether the database call succeeds or not. ### Option 3 Similar to option 2, the response is an http 202, not a 200, but now when you call the service from the client you provide an `InstanceContext` object that specifies an object to handle the call back. The client regains control and a new thread waits asynchronously for the service response informing you of success or failure. --- Below is some more info about implementing these patterns in WCF. After writing it, it is pretty long but there are a couple of useful comments as well as the code. As Whisk mentioned, Juval Lowy has an article covering a lot this detail (and more!) [here](http://msdn.microsoft.com/en-us/magazine/cc163537.aspx) ### Option 1 This is the default behaviour in WCF so you should not need to do anything - it works with lots of different bindings including wsHttpBinding and basicHttpBinding. One thing to note is that the behaviour described with your client hanging waiting for the 200 response occurrs even if you have a void Operation like so: ``` [ServiceContract] interface IMyServiceContract { [OperationContract] void DoSomeThing(InputMessage Message); } ``` ### Option 2 To set an operation as one-way you simply decorate it as so: ``` [ServiceContract] interface IMyServiceContract { [OperationContract(IsOneWay = true)] void DoSomeThing(InputMessage Message); } ``` Methods decorated in this way must only have a return type of void. One gotcha is that the service will happily build and you won't get an exception saying the service config is invalid until you connect to it. ### Option 3 The interface code for creating a duplex callback service is: ``` [ServiceContract(CallbackContract = typeof(IMyContractCallback))] interface IMyContract { [OperationContract(IsOneWay=true)] void DoSomeThing(InputMessage Message); } public interface IMyContractCallback { [OperationContract(IsOneWay = true)] void ServiceResponse(string result); } ``` And on the client side you need something like so to set up the callback: ``` public class CallbackHandler : IMyContractCallback { #region IEchoContractCallback Members public void ServiceResponse(string result) { //Do something with the response } #endregion } // And in the client when you set up the service call: InstanceContext instanceContext = new InstanceContext(new CallbackHandler()); MyContractClient client = new MyContractClient(instanceContext); InputMessage msg = new InputMessage(); client.DoSomething(msg); ``` In the service you would perhaps have some code like: ``` class MyContractImplementation : IMyContract { public void DoSomeThing(MyMessage Message) { string responseMessage; try { //Write to the database responseMessage = "The database call was good!"; } catch (Exception ex) { responseMessage = ex.Message; } Callback.ServiceResponse(responseMessage); } } ``` One important thing to note, that caught me out at first, is to be careful about exceptions. If you: * Consume an exception, you will get no warning of the error (but the callback will happen) * Throw an unhandled exception, the service will terminate and the client will not even get the callback. That is one big disadvantage of this method compared with Option 1, Option 1 will return the exception when an unhandled exception is thrown.
226,977
<p>I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a <em>good</em> thing.</p> <p>Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?</p>
[ { "answer_id": 226995, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 4, "selected": false, "text": "<h2>Definition</h2>\n\n<p>Essentially, coupling is how much a given object or set of object relies on another object or another set of objects in order to accomplish its task.</p>\n\n<h2>High Coupling</h2>\n\n<p>Think of a car. In order for the engine to start, a key must be inserted into the ignition, turned, gasoline must be present, a spark must occur, pistons must fire, and the engine must come alive. You could say that a car engine is highly coupled to several other objects. This is high coupling, but it's not really a bad thing.</p>\n\n<h2>Loose Coupling</h2>\n\n<p>Think of a user control for a web page that is responsible for allowing users to post, edit, and view some type of information. The single control could be used to let a user post a new piece of information or edit a new piece of information. The control should be able to be shared between two different paths - new and edit. If the control is written in such a way that it needs some type of data from the pages that will contain it, then you could say it's too highly coupled. The control should not need anything from its container page.</p>\n" }, { "answer_id": 227002, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": -1, "selected": false, "text": "<p>Loose coupling, in general, is 2 actors working independently of each other on the same workload. So if you had 2 web servers using the same back-end database, then you would say that those web servers are loosely coupled. Tight coupling would be exemplified by having 2 processors on one web server... those processors are tightly coupled.</p>\n\n<p>Hope that's somewhat helpful.</p>\n" }, { "answer_id": 227016, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 5, "selected": false, "text": "<p>Sorry, but \"loose coupling\" is not a coding issue, it's a design issue. The term \"loose coupling\" is intimately related to the desirable state of \"high cohesion\", being opposite but complementary.</p>\n\n<p>Loose coupling simply means that individual design elements should be constructed so the amount of unnecessary information they need to know about other design elements are reduced.</p>\n\n<p>High cohesion is sort of like \"tight coupling\", but high cohesion is a state where design elements that really need to know about each other are designed so that they work together cleanly and elegantly.</p>\n\n<p>The point is, some design elements should know details about other design elements, so they should be designed that way, and not accidentally. Other design elements should not know details about other design elements, so they should be designed that way, purposefully, instead of randomly.</p>\n\n<p>Implementing this is left as an exercise for the reader :) .</p>\n" }, { "answer_id": 227023, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<p>Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)</p>\n\n<pre><code>ArrayList&lt;String&gt; myList = new ArrayList&lt;String&gt;();\n</code></pre>\n\n<p>then I'm dependent on the ArrayList implementation.</p>\n\n<p>If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.</p>\n\n<pre><code>List&lt;String&gt; myList = new ArrayList&lt;String&gt;();\n</code></pre>\n\n<p>This prevents me from calling <em>any</em> method on <code>myList</code> that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.</p>\n\n<p>Of course, you <em>can</em> instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.</p>\n" }, { "answer_id": 227032, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "<p>You can read more about the generic concept of <a href=\"http://en.wikipedia.org/wiki/Loose_coupling\" rel=\"nofollow noreferrer\">\"loose coupling\"</a>.</p>\n\n<p>In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.</p>\n" }, { "answer_id": 227036, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 6, "selected": false, "text": "<p>I'll use Java as an example. Let's say we have a class that looks like this:</p>\n\n<pre><code>public class ABC\n{\n public void doDiskAccess() {...}\n}\n</code></pre>\n\n<p>When I call the class, I'll need to do something like this:</p>\n\n<pre><code>ABC abc = new ABC();\n\nabc. doDiskAccess();\n</code></pre>\n\n<p>So far, so good. Now let's say I have another class that looks like this:</p>\n\n<pre><code>public class XYZ\n{\n public void doNetworkAccess() {...}\n}\n</code></pre>\n\n<p>It looks exactly the same as ABC, but let's say it works over the network instead of on disk. So now let's write a program like this:</p>\n\n<pre><code>if(config.isNetwork()) new XYZ().doNetworkAccess();\nelse new ABC().doDiskAccess();\n</code></pre>\n\n<p>That works, but it's a bit unwieldy. I could simplify this with an interface like this:</p>\n\n<pre><code>public interface Runnable\n{\n public void run();\n}\n\npublic class ABC implements Runnable\n{\n public void run() {...}\n}\n\npublic class XYZ implements Runnable\n{\n public void run() {...}\n}\n</code></pre>\n\n<p>Now my code can look like this:</p>\n\n<pre><code>Runnable obj = config.isNetwork() ? new XYZ() : new ABC();\n\nobj.run();\n</code></pre>\n\n<p>See how much cleaner and simpler to understand that is? We've just understood the first basic tenet of loose coupling: abstraction. The key from here is to ensure that ABC and XYZ do not depend on any methods or variables of the classes that call them. That allows ABC and XYZ to be completely independent APIs. Or in other words, they are \"decoupled\" or \"loosely coupled\" from the parent classes.</p>\n\n<p>But what if we need communication between the two? Well, then we can use further abstractions like an <a href=\"http://en.wikipedia.org/wiki/Event_model\" rel=\"noreferrer\">Event Model</a> to ensure that the parent code never needs to couple with the APIs you have created.</p>\n" }, { "answer_id": 227038, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 5, "selected": false, "text": "<p>You can think of (tight or loose) coupling as being literally the amount of effort it would take you to separate a particular class from its reliance on another class. For example, if every method in your class had a little finally block at the bottom where you made a call to Log4Net to log something, then you would say your class was tightly coupled to Log4Net. If your class instead contained a private method named LogSomething which was the only place that called the Log4Net component (and the other methods all called LogSomething instead), then you would say your class was loosely coupled to Log4Net (because it wouldn't take much effort to pull Log4Net out and replace it with something else).</p>\n" }, { "answer_id": 227046, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "<p>Consider a Windows app with FormA and FormB. FormA is the primary form and it displays FormB. Imagine FormB needing to pass data back to its parent.</p>\n\n<p>If you did this:</p>\n\n<pre><code>class FormA \n{\n FormB fb = new FormB( this );\n\n ...\n fb.Show();\n}\n\nclass FormB \n{\n FormA parent;\n\n public FormB( FormA parent )\n {\n this.parent = parent;\n } \n}\n</code></pre>\n\n<p>FormB is tightly coupled to FormA. FormB can have no other parent than that of type FormA. </p>\n\n<p>If, on the other hand, you had FormB publish an event and have FormA subscribe to that event, then FormB could push data back through that event to whatever subscriber that event has. In this case then, FormB doesn't even know its talking back to its parent; through the loose coupling the event provides it's simply talking to subscribers. Any type can now be a parent to FormA.</p>\n\n<p>rp </p>\n" }, { "answer_id": 227051, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": 3, "selected": false, "text": "<p>It's a pretty general concept, so code examples are not going to give the whole picture.</p>\n\n<p>One guy here at work said to me, \"patterns are like fractals, you can see them when you zoom in really close, and when you zoom way out to the architecture level.\"</p>\n\n<p>Reading the brief wikipedia page can give you a sense of this generalness:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Loose_coupling\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Loose_coupling</a></p>\n\n<p>As far as a specific code example...</p>\n\n<p>Here's one loose coupling I've worked with recently, from the Microsoft.Practices.CompositeUI stuff.</p>\n\n<pre><code> [ServiceDependency]\n public ICustomizableGridService CustomizableGridService\n {\n protected get { return _customizableGridService; }\n set { _customizableGridService = value; }\n }\n</code></pre>\n\n<p>This code is declaring that this class has a dependency on a CustomizableGridService. Instead of just directly referencing the exact implementation of the service, it simply states that it requires SOME implementation of that service. Then at runtime, the system resolves that dependency.</p>\n\n<p>If that's not clear, you can read a more detailed explanation here:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Dependency_injection</a></p>\n\n<p>Imagine that ABCCustomizableGridService is the imlpementation I intend to hook up here.</p>\n\n<p>If I choose to, I can yank that out and replace it with XYZCustomizableGridService, or StubCustomizableGridService with no change at all to the class with this dependency.</p>\n\n<p>If I had directly referenced ABCCustomizableGridService, then I would need to make changes to that/those reference/s in order to swap in another service implementation.</p>\n" }, { "answer_id": 227334, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 8, "selected": false, "text": "<p>Consider a simple shopping cart application that uses a <code>CartContents</code> class to keep track of the items in the shopping cart and an <code>Order</code> class for processing a purchase. The <code>Order</code> needs to determine the total value of the contents in the cart, it might do that like so:</p>\n<p><strong>Tightly Coupled Example:</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class CartEntry\n{\n public float Price;\n public int Quantity;\n}\n\npublic class CartContents\n{\n public CartEntry[] items;\n}\n\npublic class Order\n{\n private CartContents cart;\n private float salesTax;\n\n public Order(CartContents cart, float salesTax)\n {\n this.cart = cart;\n this.salesTax = salesTax;\n }\n\n public float OrderTotal()\n {\n float cartTotal = 0;\n for (int i = 0; i &lt; cart.items.Length; i++)\n {\n cartTotal += cart.items[i].Price * cart.items[i].Quantity;\n }\n cartTotal += cartTotal*salesTax;\n return cartTotal;\n }\n}\n</code></pre>\n<p>Notice how the <code>OrderTotal</code> method (and thus the Order class) depends on the implementation details of the <code>CartContents</code> and the <code>CartEntry</code> classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a <code>List&lt;CartEntry&gt;</code> collection to keep track of the items we'd have to change the <code>Order</code> class as well.</p>\n<p>Now here's a slightly better way to do the same thing:</p>\n<p><strong>Less Coupled Example:</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class CartEntry\n{\n public float Price;\n public int Quantity;\n\n public float GetLineItemTotal()\n {\n return Price * Quantity;\n }\n}\n\npublic class CartContents\n{\n public CartEntry[] items;\n\n public float GetCartItemsTotal()\n {\n float cartTotal = 0;\n foreach (CartEntry item in items)\n {\n cartTotal += item.GetLineItemTotal();\n }\n return cartTotal;\n }\n}\n\npublic class Order\n{\n private CartContents cart;\n private float salesTax;\n\n public Order(CartContents cart, float salesTax)\n {\n this.cart = cart;\n this.salesTax = salesTax;\n }\n\n public float OrderTotal()\n {\n return cart.GetCartItemsTotal() * (1.0f + salesTax);\n }\n}\n</code></pre>\n<p>The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.</p>\n" }, { "answer_id": 227892, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 3, "selected": false, "text": "<p>Coupling has to do with dependencies between systems, which could be modules of code (functions, files, or classes), tools in a pipeline, server-client processes, and so forth. The less general the dependencies are, the more \"tightly coupled\" they become, since changing one system required changing the other systems that rely on it. The ideal situation is \"loose coupling\" where one system can be changed and the systems depending on it will continue to work without modification.</p>\n\n<p>The general way to achieve loose coupling is through well defined interfaces. If the interaction between two systems is well defined and adhered to on both sides, then it becomes easier to modify one system while ensuring that the conventions are not broken. It commonly occurs in practice that no well-defined interface is established, resulting in a sloppy design and tight coupling.</p>\n\n<p>Some examples:</p>\n\n<ul>\n<li><p>Application depends on a library. Under tight coupling, app breaks on newer versions of the lib. Google for \"DLL Hell\".</p></li>\n<li><p>Client app reads data from a server. Under tight coupling, changes to the server require fixes on the client side.</p></li>\n<li><p>Two classes interact in an Object-Oriented hierarchy. Under tight coupling, changes to one class require the other class to be updated to match.</p></li>\n<li><p>Multiple command-line tools communicate in a pipe. If they are tightly coupled, changes to the version of one command-line tool will cause errors in the tools that read its output.</p></li>\n</ul>\n" }, { "answer_id": 227957, "author": "Owen", "author_id": 425, "author_profile": "https://Stackoverflow.com/users/425", "pm_score": 5, "selected": false, "text": "<p>The degree of difference between answers here shows why it would be a difficult concept to grasp but to put it as simply as I can describe it:</p>\n<p>In order for me to know that if I throw a ball to you, then you can catch it I really dont need to know how old you are. I dont need to know what you ate for breakfast, and I really dont care who your first crush was. All I need to know is that you can catch. If I know this, then I dont care if its you I am throwing a ball to you or your brother.</p>\n<p>With non-dynamic languages like c# or Java etc, we accomplish this via Interfaces. So lets say we have the following interface:</p>\n<pre><code>public ICatcher\n{\n public void Catch();\n}\n</code></pre>\n<p>And now lets say we have the following classes:</p>\n<pre><code>public CatcherA : ICatcher\n{\n public void Catch()\n {\n console.writeline(&quot;You Caught it&quot;);\n }\n\n}\npublic CatcherB : ICatcher\n{\n public void Catch()\n {\n console.writeline(&quot;Your brother Caught it&quot;);\n }\n\n}\n</code></pre>\n<p>Now both <code>CatcherA</code> and <code>CatcherB</code> implement the <code>Catch</code> method, so the service that requires a Catcher can use either of these and not really give a damn which one it is. So a tightly coupled service might directly instantiate a catched i.e.</p>\n<pre><code>public CatchService\n{\n private CatcherA catcher = new CatcherA();\n\n public void CatchService()\n {\n catcher.Catch();\n }\n\n}\n</code></pre>\n<p>So the <code>CatchService</code> may do exactly what it has set out to do, but it uses <code>CatcherA</code> and will always user <code>CatcherA</code>. Its hard coded in, so its staying there until someone comes along and refactors it.</p>\n<p>Now lets take another option, called dependency injection:</p>\n<pre><code>public CatchService\n{\n private ICatcher catcher;\n\n public void CatchService(ICatcher catcher)\n {\n this.catcher = catcher;\n catcher.Catch();\n }\n}\n</code></pre>\n<p>So the calls that instantiate <code>CatchService</code> may do the following:</p>\n<pre><code>CatchService catchService = new CatchService(new CatcherA());\n</code></pre>\n<p>or</p>\n<pre><code>CatchService catchService = new CatchService(new CatcherB());\n</code></pre>\n<p>This means that the <code>Catch</code> service is not tightly coupled to either <code>CatcherA</code> or <code>CatcherB</code>.</p>\n<p>There are several other strategies for loosely coupling services like this such as the use of an IoC framework etc.</p>\n" }, { "answer_id": 228747, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p>Two components are higly coupled when they depend on concrete implementation of each other.</p>\n\n<p>Suppose I have this code somewhere in a method in my class:</p>\n\n<pre><code>this.some_object = new SomeObject();\n</code></pre>\n\n<p>Now my class depends on SomeObject, and they're highly coupled. On the other hand, let's say I have a method InjectSomeObject:</p>\n\n<pre><code>void InjectSomeObject(ISomeObject so) { // note we require an interface, not concrete implementation\n this.some_object = so;\n}\n</code></pre>\n\n<p>Then the first example can just use injected SomeObject. <strong>This is useful during testing.</strong> With normal operation you can use heavy, database-using, network-using classes etc. while for tests passing a lightweight, mock implementation. <strong>With tightly coupled code you can't do that.</strong></p>\n\n<p>You can make some parts of this work easer by using dependency injection containers. You can read more about DI at Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Dependency_injection</a>.</p>\n\n<p><strong>It is sometimes easy to take this too far.</strong> At some point you have to make things concrete, or your program will be less readable and understandable. So use this techniques mainly at components boundary, and know what you are doing. Make sure you are taking advantage of loose coupling. If not, you probably don't need it in that place. DI may make your program more complex. Make sure you make a good tradeoff. In other words, maintain good balance. <em>As always when designing systems.</em> Good luck!</p>\n" }, { "answer_id": 230734, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 2, "selected": false, "text": "<p>In computer science there is another meaning for \"loose coupling\" that no one else has posted about here, so... Here goes - hopefully you'll give me some votes up so this isn't lost at the bottom of the heap! SURELY the subject of my answer belongs in any comprehensive answer to the question... To wit:</p>\n\n<p>The term \"Loose Coupling\" first entered computing as a term used as an adjective regarding CPU architecture in a multi-CPU configuration. Its counterpart term is \"tight coupling\". Loose Coupling is when CPUs do not share many resources in common and Tight Coupling is when they do.</p>\n\n<p>The term \"system\" can be confusing here so please parse the situation carefully.</p>\n\n<p>Usually, but not always, multiple CPUs in a hardware configuration in which they exist within one system (as in individual \"PC\" boxes) would be tightly coupled. With the exception of some super-high-performance systems that have subsystems that actually share main memory across \"systems\", all divisible systems are loosely coupled.</p>\n\n<p>The terms Tightly Coupled and Loosely Coupled were introduced <em>before</em> multi-threaded and multi-core CPUs were invented, so these terms may need some companions to fully articulate the situation today. And, indeed, today one may very well have a system that encompases both types in one overall system. Regarding current software systems, there are two common architectures, one of each variety, that are common enough these should be familliar.</p>\n\n<p>First, since it was what the question was about, some examples of Loosely Coupled systems:</p>\n\n<ul>\n<li>VaxClusters</li>\n<li>Linux Clusters</li>\n</ul>\n\n<p>In contrast, some Tightly Coupled examples:</p>\n\n<ul>\n<li>Semetrical-Multi-Processing (SMP) Operating systems - e.g. Fedora 9</li>\n<li>Multi-threaded CPUs</li>\n<li>Multi-Core CPUs</li>\n</ul>\n\n<p>In today's computing, examples of both operating in a single overall system is not uncommon. For example, take modern Pentium dual or quad core CPUs running Fedora 9 - these are tightly-coupled computing systems. Then, combine several of them in a loosely coupled Linux Cluster and you now have both loosely and tightly coupled computing going on! Oh, isn't modern hardware wonderful! </p>\n" }, { "answer_id": 402941, "author": "Ben Aston", "author_id": 38522, "author_profile": "https://Stackoverflow.com/users/38522", "pm_score": 2, "selected": false, "text": "<p>Some long answers here. The principle is very simple though. I submit the opening statement from <a href=\"http://en.wikipedia.org/wiki/Loose_coupling\" rel=\"nofollow noreferrer\">wikipedia</a>:</p>\n\n<p>\"Loose coupling describes a resilient relationship between two or more systems or organizations with some kind of exchange relationship. </p>\n\n<p>Each end of the transaction makes its requirements explicit and makes few assumptions about the other end.\"</p>\n" }, { "answer_id": 402970, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "<p>Many integrated products (especially by Apple) such as <strong>iPods</strong>, <strong>iPads</strong> are a good example of tight coupling: once the battery dies you might as well buy a new device because the battery is soldered fixed and won't come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.</p>\n\n<p><em>The same</em> goes for software development: it is generally (much) better to have loosely coupled code to facilitate extension and replacement (and to make individual parts easier to understand). But, very rarely, under special circumstances tight coupling can be advantageous because the tight integration of several modules allows for better optimisation.</p>\n" }, { "answer_id": 13387971, "author": "Marek Dec", "author_id": 987856, "author_profile": "https://Stackoverflow.com/users/987856", "pm_score": 2, "selected": false, "text": "<p>I propose a very simple <strong>Test of Code Coupling</strong>:</p>\n\n<ol>\n<li><p>Piece A of code is tightly coupled to Piece B of code if there exists any possible modification to the Piece B that would force changes in Piece A in order to keep correctness.</p></li>\n<li><p>Piece A of code is not tightly coupled to Piece B of code if there is no possible modification to the Piece B that would make a change to Piece A necessary.</p></li>\n</ol>\n\n<p>This will help you to verify how much coupling there is between the pieces of your code.\nfor reasoning on that see this blog post: <a href=\"http://marekdec.wordpress.com/2012/11/14/loose-coupling-tight-coupling-decoupling-what-is-that-all-about/\" rel=\"nofollow\">http://marekdec.wordpress.com/2012/11/14/loose-coupling-tight-coupling-decoupling-what-is-that-all-about/</a></p>\n" }, { "answer_id": 22524255, "author": "Ravindra Miyani", "author_id": 3354432, "author_profile": "https://Stackoverflow.com/users/3354432", "pm_score": 2, "selected": false, "text": "<p>In simple language, loosely coupled means it doesn’t depend on other event to occur. It executes independently.</p>\n" }, { "answer_id": 27795160, "author": "Abhishek Aggarwal", "author_id": 1074100, "author_profile": "https://Stackoverflow.com/users/1074100", "pm_score": 2, "selected": false, "text": "<p>When you create an object of a class using the <code>new</code> keyword in some other class, you are actually doing tight coupling (bad practice) instead you should use loose coupling which is a good practice</p>\n<p>---A.java---</p>\n<pre><code>package interface_package.loose_coupling;\n\npublic class A {\n\nvoid display(InterfaceClass obji)\n{\n obji.display();\n System.out.println(obji.getVar());\n}\n}\n</code></pre>\n<p>---B.java---</p>\n<pre><code>package interface_package.loose_coupling;\n\npublic class B implements InterfaceClass{\n\nprivate String var=&quot;variable Interface&quot;;\n\npublic String getVar() {\n return var;\n}\n\npublic void setVar(String var) {\n this.var = var;\n}\n\n@Override\npublic void display() {\n // TODO Auto-generated method stub\n System.out.println(&quot;Display Method Called&quot;);\n}\n}\n</code></pre>\n<p>---InterfaceClass---</p>\n<pre><code>package interface_package.loose_coupling;\n\npublic interface InterfaceClass {\n\nvoid display();\nString getVar();\n}\n</code></pre>\n<p>---MainClass---</p>\n<pre><code>package interface_package.loose_coupling;\n\npublic class MainClass {\n\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n\n A obja=new A();\n B objb=new B();\n obja.display(objb); //Calling display of A class with object of B class \n \n}\n}\n</code></pre>\n<p>Explanation:</p>\n<p>In the above example, we have two classes A and B</p>\n<p>Class B implements Interface i.e. InterfaceClass.</p>\n<p>InterfaceClass defines a Contract for B class as InterfaceClass has abstract methods of B class that can be accessed by any other class for example A.</p>\n<p>In Class A we have a display method which can except object of class that implements InterfaceClass (in our case it is B class). And on that object method of class A is calling display() and getVar() of class B</p>\n<p>In MainClass we have created object of Class A and B. And calling display method of A by passing object of B class i.e. objb. Display method of A will be called with object of B class.</p>\n<p>Now talking about loose coupling. Suppose in the future you have to change the name of Class B to ABC then you do not have to change its name in the display method of class B, just make the object of new (ABC class) and pass it to the display method in MailClass. You do not have to change anything in Class A</p>\n<p>ref: <a href=\"https://speckyfox.com/blog/5-steps-to-loose-coupling-in-java-using-interfaces\" rel=\"nofollow noreferrer\">https://speckyfox.com/blog/5-steps-to-loose-coupling-in-java-using-interfaces</a></p>\n" }, { "answer_id": 39831064, "author": "user1263981", "author_id": 1263981, "author_profile": "https://Stackoverflow.com/users/1263981", "pm_score": 3, "selected": false, "text": "<p>Coupling refers to how tightly different classes are connected to one another. Tightly coupled classes contain a high number of interactions and dependencies. </p>\n\n<p>Loosely coupled classes are the opposite in that their dependencies on one another are kept to a minimum and instead rely on the well-defined public interfaces of each other.</p>\n\n<p><em>Legos, the toys that SNAP together would be considered loosely coupled because you can just snap the pieces together and build whatever system you want to. However, a jigsaw puzzle has pieces that are TIGHTLY coupled. You can’t take a piece from one jigsaw puzzle (system) and snap it into a different puzzle, because the system (puzzle) is very dependent on the very specific pieces that were built specific to that particular “design”. The legos are built in a more generic fashion so that they can be used in your Lego House, or in my Lego Alien Man.</em> </p>\n\n<p>Reference: <a href=\"https://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/\" rel=\"noreferrer\">https://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30454/" ]
I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a *good* thing. Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?
Consider a simple shopping cart application that uses a `CartContents` class to keep track of the items in the shopping cart and an `Order` class for processing a purchase. The `Order` needs to determine the total value of the contents in the cart, it might do that like so: **Tightly Coupled Example:** ```cs public class CartEntry { public float Price; public int Quantity; } public class CartContents { public CartEntry[] items; } public class Order { private CartContents cart; private float salesTax; public Order(CartContents cart, float salesTax) { this.cart = cart; this.salesTax = salesTax; } public float OrderTotal() { float cartTotal = 0; for (int i = 0; i < cart.items.Length; i++) { cartTotal += cart.items[i].Price * cart.items[i].Quantity; } cartTotal += cartTotal*salesTax; return cartTotal; } } ``` Notice how the `OrderTotal` method (and thus the Order class) depends on the implementation details of the `CartContents` and the `CartEntry` classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a `List<CartEntry>` collection to keep track of the items we'd have to change the `Order` class as well. Now here's a slightly better way to do the same thing: **Less Coupled Example:** ```cs public class CartEntry { public float Price; public int Quantity; public float GetLineItemTotal() { return Price * Quantity; } } public class CartContents { public CartEntry[] items; public float GetCartItemsTotal() { float cartTotal = 0; foreach (CartEntry item in items) { cartTotal += item.GetLineItemTotal(); } return cartTotal; } } public class Order { private CartContents cart; private float salesTax; public Order(CartContents cart, float salesTax) { this.cart = cart; this.salesTax = salesTax; } public float OrderTotal() { return cart.GetCartItemsTotal() * (1.0f + salesTax); } } ``` The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.
226,978
<p>What is the best way to sync up two lists each of which may contain items not in the other? As shown the lists are not sorted - although if necessary sorting them first would not be an issue.</p> <pre><code>List 1 = a,b,c,e List 2 = b,e,c,d </code></pre> <p>Using the lists above, I'm looking for a solution that will write out to a spreadsheet in two columns:</p> <pre><code>a b b c c d e e </code></pre>
[ { "answer_id": 227292, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "<p>Here are some notes on using a disconnected recordset.</p>\n\n<pre><code>Const adVarChar = 200 'the SQL datatype is varchar\n\n'Create arrays fron the lists\nasL1 = Split(\"a,b,c,\", \",\")\nasL2 = Split(\"b,e,c,d\", \",\")\n\n'Create a disconnected recordset\nSet rs = CreateObject(\"ADODB.RECORDSET\")\nrs.Fields.append \"Srt\", adVarChar, 25\nrs.Fields.append \"L1\", adVarChar, 25\nrs.Fields.append \"L2\", adVarChar, 25\n\nrs.CursorType = adOpenStatic\nrs.Open\n\n'Add list 1 to the recordset\nFor i = 0 To UBound(asL1)\n rs.AddNew Array(\"Srt\", \"L1\"), Array(asL1(i), asL1(i))\n rs.Update\nNext\n\n'Add list 2\nFor i = 0 To UBound(asL2)\n rs.MoveFirst\n rs.Find \"L1='\" &amp; asL2(i) &amp; \"'\"\n\n If rs.EOF Then\n rs.AddNew Array(\"Srt\", \"L2\"), Array(asL2(i), asL2(i))\n Else\n rs.Fields(\"L2\") = asL2(i)\n End If\n\n rs.Update\nNext\n\nrs.Sort = \"Srt\"\n\n'Add the data to the active sheet\nSet wks = Application.ActiveWorkbook.ActiveSheet\n\nrs.MoveFirst\n\nintRow = 1\nDo\n For intField = 1 To rs.Fields.Count - 1\n wks.Cells(intRow, intField + 1) = rs.Fields(intField).Value\n Next intField\n\n rs.MoveNext\n intRow = intRow + 1\nLoop Until rs.EOF = True\n</code></pre>\n" }, { "answer_id": 227464, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "<p>Here's another option, this time using Dictionaries (add a reference to Microsoft Scripting Runtime, which also has several other hugely useful objects - don't start VBA coding without it!)</p>\n\n<p>As written, the output isn't sorted - that could be a bit of a showstopper. Anyway, there are a couple of nice little tricks here:</p>\n\n<pre><code>Option Explicit\n\nPublic Sub OutputLists()\n\nDim list1, list2\nDim dict1 As Dictionary, dict2 As Dictionary\nDim ky\nDim cel As Range\n\n Set dict1 = DictionaryFromArray(Array(\"a\", \"b\", \"c\", \"e\"))\n Set dict2 = DictionaryFromArray(Array(\"b\", \"e\", \"c\", \"d\"))\n\n Set cel = ActiveSheet.Range(\"A1\")\n\n For Each ky In dict1.Keys\n PutRow cel, ky, True, dict2.Exists(ky)\n If dict2.Exists(ky) Then\n dict2.Remove ky\n End If\n Set cel = cel.Offset(1, 0)\n Next\n\n For Each ky In dict2\n PutRow cel, ky, False, True\n Set cel = cel.Offset(1, 0)\n Next\n\nEnd Sub\n\nPrivate Sub PutRow(cel As Range, val As Variant, in1 As Boolean, in2 As Boolean)\n\nDim arr(1 To 2)\n\n If in1 Then arr(1) = val\n If in2 Then arr(2) = val\n cel.Resize(1, 2) = arr\n\nEnd Sub\n\nPrivate Function DictionaryFromArray(arr) As Dictionary\n\nDim val\n\n Set DictionaryFromArray = New Dictionary\n For Each val In arr\n DictionaryFromArray.Add val, Nothing\n Next\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 227932, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>Another option is Collections. This doesn't sort the output alphabetically, but you can sort the lists first if you need to. Note this will also give you a unique list,stripping out duplicates. The code assumes your lists are in string arrays L1 and L2.</p>\n\n<pre><code>Dim C As New Collection,i As Long, j As Long\nReDim LL(UBound(L1) + UBound(L2), 2) As String 'output array\n\nFor i = 1 To UBound(L1)\n On Error Resume Next 'try adding to collection\n C.Add C.Count + 1, L1(i) 'store sequence number,ie 1,2,3,4,...\n On Error GoTo 0\n j = C(L1(i)) 'look up sequence number\n LL(j, 1) = L1(i)\nNext i\n\nFor i = 1 To UBound(L2) 'same for L2\n On Error Resume Next\n C.Add C.Count + 1, L2(i)\n On Error GoTo 0\n j = C(L2(i))\n LL(j, 2) = L2(i)\nNext i\n\n'Result is in LL, number of rows is C.Count\nRange(\"Results\").Resize(UBound(LL, 1), 2) = LL\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30473/" ]
What is the best way to sync up two lists each of which may contain items not in the other? As shown the lists are not sorted - although if necessary sorting them first would not be an issue. ``` List 1 = a,b,c,e List 2 = b,e,c,d ``` Using the lists above, I'm looking for a solution that will write out to a spreadsheet in two columns: ``` a b b c c d e e ```
Here are some notes on using a disconnected recordset. ``` Const adVarChar = 200 'the SQL datatype is varchar 'Create arrays fron the lists asL1 = Split("a,b,c,", ",") asL2 = Split("b,e,c,d", ",") 'Create a disconnected recordset Set rs = CreateObject("ADODB.RECORDSET") rs.Fields.append "Srt", adVarChar, 25 rs.Fields.append "L1", adVarChar, 25 rs.Fields.append "L2", adVarChar, 25 rs.CursorType = adOpenStatic rs.Open 'Add list 1 to the recordset For i = 0 To UBound(asL1) rs.AddNew Array("Srt", "L1"), Array(asL1(i), asL1(i)) rs.Update Next 'Add list 2 For i = 0 To UBound(asL2) rs.MoveFirst rs.Find "L1='" & asL2(i) & "'" If rs.EOF Then rs.AddNew Array("Srt", "L2"), Array(asL2(i), asL2(i)) Else rs.Fields("L2") = asL2(i) End If rs.Update Next rs.Sort = "Srt" 'Add the data to the active sheet Set wks = Application.ActiveWorkbook.ActiveSheet rs.MoveFirst intRow = 1 Do For intField = 1 To rs.Fields.Count - 1 wks.Cells(intRow, intField + 1) = rs.Fields(intField).Value Next intField rs.MoveNext intRow = intRow + 1 Loop Until rs.EOF = True ```
226,980
<p>I have a Google Map that suddenly stopped working for no apparent reason (I hadn't touched the code for months, but the wrapper code from our CMS may have changed without Corporate telling me).</p> <p><a href="http://www.democratandchronicle.com/section/builder" rel="nofollow noreferrer">http://www.democratandchronicle.com/section/builder</a></p> <p>(sorry about the nasty HTML outside the map, most of that comes from our corporate parent...)</p> <p>I've narrowed it down to this part of my <code>drawMarker</code> function:</p> <pre><code>GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html, { maxWidth: 500 }); }); </code></pre> <p>Of note:</p> <ul> <li><code>alert(html);</code> displays the correct HTML for the infowindow.</li> <li>The HTML in the html variable is indeed valid.</li> <li>The click event is firing (confirmed by <code>alert('test');</code> within it)</li> <li>Another map I host on the same site <a href="http://www.democratandchronicle.com/garagesales" rel="nofollow noreferrer">works fine</a>, despite similar code.</li> <li>No JavaScript errors in Firebug or IE that I can see.</li> </ul> <p>I've been bashing my head against this for a while. What am I missing?</p>
[ { "answer_id": 227397, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Try forcing JavaScript to make a new variable out of your HTML:</p>\n\n<pre><code>GEvent.addListener(marker, 'click', function() {\nmarker.openInfoWindowHtml(html+'', { maxWidth: 500 });\n});\n</code></pre>\n" }, { "answer_id": 228719, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "<p>I've had random problems with Google Maps API at times and more than once it has been fixed by going back one API version. i.e. if your google maps API javascript inclusion string is like this <code>http://maps.google.com/maps?file=api&amp;v=2.xd&amp;key=XXXXX</code>\nchange the <strong>2.x</strong> to something a few versions back (back when it was working) like <strong>2.132</strong> or something</p>\n" }, { "answer_id": 444853, "author": "Keith Fitzgerald", "author_id": 49611, "author_profile": "https://Stackoverflow.com/users/49611", "pm_score": 1, "selected": false, "text": "<p>try:</p>\n\n<pre><code>GEvent.addListener(marker, 'click', function() {\n this.openInfoWindowHtml(html, { maxWidth: 500 });\n});\n</code></pre>\n\n<p>remember the scope of the object \"marker\" is outside your function</p>\n" }, { "answer_id": 447309, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": true, "text": "<p>This resolved itself. I suspect an update to the API broke something for a version or two.</p>\n" }, { "answer_id": 8294919, "author": "Stu", "author_id": 1069207, "author_profile": "https://Stackoverflow.com/users/1069207", "pm_score": 1, "selected": false, "text": "<p>I recently had this issue, event handlers definitely ran, etc. Turned out there were two instances of the Google Maps &lt;script&gt; tag on the page. Removing one fixed it.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902010/" ]
I have a Google Map that suddenly stopped working for no apparent reason (I hadn't touched the code for months, but the wrapper code from our CMS may have changed without Corporate telling me). <http://www.democratandchronicle.com/section/builder> (sorry about the nasty HTML outside the map, most of that comes from our corporate parent...) I've narrowed it down to this part of my `drawMarker` function: ``` GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html, { maxWidth: 500 }); }); ``` Of note: * `alert(html);` displays the correct HTML for the infowindow. * The HTML in the html variable is indeed valid. * The click event is firing (confirmed by `alert('test');` within it) * Another map I host on the same site [works fine](http://www.democratandchronicle.com/garagesales), despite similar code. * No JavaScript errors in Firebug or IE that I can see. I've been bashing my head against this for a while. What am I missing?
This resolved itself. I suspect an update to the API broke something for a version or two.
226,981
<p>I have an <code>IList&lt;T&gt;</code> that I need to sort, and I would rather not copy the list if possible. I've noticed that <code>ArrayList</code> has an <code>Adapter</code> static method that wraps the passed list without copying it, but this takes an <code>IList</code> and I have an <code>IList&lt;T&gt;</code>. Is it safe to cast from a <code>System.Collections.Generic.IList&lt;T&gt;</code> to a <code>System.Collections.IList</code> and just use the <code>Adapter</code> method?</p> <p>Note that this is .Net 2.0, so LINQ is not an option.</p>
[ { "answer_id": 226992, "author": "Mike C.", "author_id": 3799, "author_profile": "https://Stackoverflow.com/users/3799", "pm_score": 5, "selected": true, "text": "<p>From the blog of Paul Fox, I recommend the post \"How to sort an IList\": <a href=\"http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html\" rel=\"nofollow noreferrer\">http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html</a></p>\n\n<p>Just in case that blog goes away in the future, I'll copy the post here:</p>\n\n<hr>\n\n<p><strong>How to sort a generic IList</strong></p>\n\n<p>Update</p>\n\n<p>You can read and updated post about <a href=\"http://foxsys.blogspot.com/2008/05/how-to-sort-generic-list-sorting-list.html\" rel=\"nofollow noreferrer\">sorting generic IList and List</a>. Many people will prefer the methods mentioned in the updated post.</p>\n\n<p>Sorting a generic IList</p>\n\n<p>I was trying to sort a generic IList&lt;> and found a fairly simple way of doing it.</p>\n\n<p>Step 1</p>\n\n<p>You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.</p>\n\n<pre><code>public class LanguageDto : IComparable {\n private String name;\n public string Name { get { return name; } set { name = value; } }\n\n public LanguageDto(string name) {\n this.name = name;\n }\n\n #region IComparable Members\n public int CompareTo(object obj) {\n if (obj is LanguageDto) {\n LanguageDto language = (LanguageDto)obj;\n return this.name.CompareTo(language.name);\n }\n throw new ArgumentException(string.Format(\"Cannot compare a LanguageDto to an {0}\", obj.GetType().ToString()));\n }\n #endregion\n}\n</code></pre>\n\n<p>STEP 2</p>\n\n<p>Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so...</p>\n\n<pre><code>ArrayList.Adapter((IList)languages).Sort();\n</code></pre>\n\n<p>Note: languages is of type \"IList\"</p>\n\n<p>Languages should then be a sorted list of your type!</p>\n" }, { "answer_id": 227013, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "<p>You cannot cast IList(T) to IList.</p>\n\n<p>After some sniffing with Reflector, it seems like ArrayList.Adapter(IList).Sort() will first copy the list to an object array, sort the array and then copy the array back to a list:</p>\n\n<pre><code>object[] array = new object[count];\nthis.CopyTo(index, array, 0, count);\nArray.Sort(array, 0, count, comparer);\nfor (int i = 0; i &lt; count; i++)\n{\n this._list[i + index] = array[i];\n}\n</code></pre>\n\n<p>You might get boxing overhead if T in your List(T) a value type. </p>\n\n<p>If you need to alter the sequence of the objects in the list that you have, you can do it similarly:</p>\n\n<pre><code>IList&lt;object&gt; unsorted = ...\nList&lt;object&gt; sorted = new List&lt;object&gt;(unsorted);\nsorted.Sort(); \nfor (int i = 0; i &lt; unsorted.Countt; i++)\n{\n unsorted[i] = sorted[i];\n}\n</code></pre>\n\n<p>If the list is so huge (as in hundreds of million items) that you cannot make an extra copy in memory, I suggest using a List(T) in the first place or implement your favorite in-place sorting algorithm.</p>\n" }, { "answer_id": 227065, "author": "Gord", "author_id": 12560, "author_profile": "https://Stackoverflow.com/users/12560", "pm_score": 0, "selected": false, "text": "<p>I know it isn't .NET 2.0 but I love LINQ so much and will endorse it every chance I get :)</p>\n\n<p><strong>Simple Sort:</strong></p>\n\n<pre><code>var sortedProducts =\n from p in products\n orderby p.ProductName\n select p;\n\nObjectDumper.Write(sortedProducts);\n</code></pre>\n\n<p><strong>Sort by multiple conditions:</strong></p>\n\n<pre><code>string[] digits = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" };\n\nvar sortedDigits =\n from d in digits \n orderby d.Length, d\n select d;\n</code></pre>\n\n<p>Both examples are from <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336756.aspx\" rel=\"nofollow noreferrer\">101 Linq Samples</a></p>\n" }, { "answer_id": 227443, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 1, "selected": false, "text": "<p>Since the Sort method isn't on the IList interface you might consider creating your own:</p>\n\n<pre><code>interface ISortableList&lt;T&gt; : IList&lt;T&gt;\n{\n void Sort();\n void Sort(IComparer&lt;T&gt; comparer);\n}\n\nclass SortableList&lt;T&gt; : List&lt;T&gt;, ISortableList&lt;T&gt; { }\n\n/* usage */\nvoid Example(ISortedList&lt;T&gt; list)\n{\n list.Sort();\n list.Sort(new MyCustomerComparer());\n}\n</code></pre>\n\n<p>In general the parameter type you specify in your method should be the lowest common denominator of members you actually need to call. If you really need to call the Sort() method then your parameter should have that member defined. Otherwise you should probably load it into another object that can do what you want such as:</p>\n\n<pre><code>void Example(IList&lt;T&gt; list)\n{\n list = new List&lt;T&gt;(list).Sort();\n}\n</code></pre>\n\n<p>This should actually be pretty fast, almost certainly faster still than writing your own custom inline sort algorithm.</p>\n" }, { "answer_id": 5311258, "author": "Rohit", "author_id": 660495, "author_profile": "https://Stackoverflow.com/users/660495", "pm_score": -1, "selected": false, "text": "<pre><code>IList&lt;object&gt; unsorted = ...\nIList&lt;object&gt; sortedList = unsorted.Orderby(x =&gt; x.Tostring()).Tolist();\n</code></pre>\n\n<p>this will give the sorted list on the particular field of the object.</p>\n" }, { "answer_id": 32208526, "author": "Nullius", "author_id": 1302710, "author_profile": "https://Stackoverflow.com/users/1302710", "pm_score": 0, "selected": false, "text": "<p>If you need to sort Lists (not ILists) of different classes without the need to create a seperate comparer class for all of them and still keep your entity classes clean (you don't want to implement IComparable), you can use the following (compatible with .NET 2.0):</p>\n\n<pre><code>public class DynamicComparer&lt;T&gt; : IComparer&lt;T&gt;\n{\n\n private Func&lt;T, int&gt; calculateFunc;\n private int calculateMultiplier;\n\n private Func&lt;T, T, int&gt; compareFunc;\n public DynamicComparer(Func&lt;T, int&gt; calculateFunc, bool reverse = false)\n {\n if (calculateFunc == null)\n {\n throw new Exception(\"Delegate function 'calculateFunc' cannot be null.\");\n }\n\n this.calculateFunc = calculateFunc;\n this.calculateMultiplier = reverse ? -1 : 1;\n this.compareFunc = null;\n }\n\n public DynamicComparer(Func&lt;T, T, int&gt; compareFunc)\n {\n if (calculateFunc == null)\n {\n throw new Exception(\"Delegate function 'compareFunc' cannot be null.\");\n }\n\n this.calculateFunc = null;\n this.compareFunc = compareFunc;\n }\n\n public int Compare(T x, T y)\n {\n if (calculateFunc != null)\n {\n return (calculateFunc(x) - calculateFunc(y)) * this.calculateMultiplier;\n }\n if (compareFunc != null)\n {\n return compareFunc(x, y);\n }\n\n throw new Exception(\"Compare not possible because neither a Compare or a Calculate function was specified.\");\n }\n}\n</code></pre>\n\n<p>You'll also need the Func delegates if you're using .NET 2.0 (found on <a href=\"https://stackoverflow.com/questions/16982220/replacing-func-with-delegates-c-sharp\">Replacing Func with delegates C#</a>):</p>\n\n<pre><code>public delegate TResult Func&lt;T, TResult&gt;(T t);\npublic delegate TResult Func&lt;T, U, TResult&gt;(T t, U u);\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>myList.Sort(new DynamicComparer&lt;MyClass&gt;(x =&gt; x.MyIntProperty) // Ascending\nmyList.Sort(new DynamicComparer&lt;MyClass&gt;(x =&gt; x.MyIntProperty, true) // Descending\n</code></pre>\n\n<p>Some simple unit testing:</p>\n\n<pre><code>[TestClass()]\npublic class DynamicComparerTU\n{\n [TestMethod()]\n public void SortIntList()\n {\n // Arrange\n dynamic myIntArray = new int[] {\n 4,\n 1,\n 9,\n 0,\n 4,\n 7\n };\n dynamic myIntList = new List&lt;int&gt;(myIntArray);\n\n // Act\n int temp = 0;\n for (int write = 0; write &lt;= myIntArray.Length - 1; write++)\n {\n for (int sort = 0; sort &lt;= myIntArray.Length - 2; sort++)\n {\n if (myIntArray(sort) &gt; myIntArray(sort + 1))\n {\n temp = myIntArray(sort + 1);\n myIntArray(sort + 1) = myIntArray(sort);\n myIntArray(sort) = temp;\n }\n }\n }\n\n myIntList.Sort(new DynamicComparer&lt;int&gt;(x =&gt; x));\n\n // Assert\n Assert.IsNotNull(myIntList);\n Assert.AreEqual(myIntArray.Length, myIntList.Count);\n for (int i = 0; i &lt;= myIntArray.Length - 1; i++)\n {\n Assert.AreEqual(myIntArray(i), myIntList(i));\n }\n }\n\n [TestMethod()]\n public void SortStringListByLength()\n {\n // Arrange\n dynamic myStringArray = new string[] {\n \"abcd\",\n \"ab\",\n \"abcde\",\n \"a\",\n \"abc\"\n };\n dynamic myStringList = new List&lt;string&gt;(myStringArray);\n\n // Act\n myStringList.Sort(new DynamicComparer&lt;string&gt;(x =&gt; x.Length));\n\n // Assert\n Assert.IsNotNull(myStringList);\n Assert.AreEqual(5, myStringList.Count);\n Assert.AreEqual(\"a\", myStringList(0));\n Assert.AreEqual(\"ab\", myStringList(1));\n Assert.AreEqual(\"abc\", myStringList(2));\n Assert.AreEqual(\"abcd\", myStringList(3));\n Assert.AreEqual(\"abcde\", myStringList(4));\n }\n\n [TestMethod()]\n public void SortStringListByLengthDescending()\n {\n // Arrange\n dynamic myStringArray = new string[] {\n \"abcd\",\n \"ab\",\n \"abcde\",\n \"a\",\n \"abc\"\n };\n dynamic myStringList = new List&lt;string&gt;(myStringArray);\n\n // Act\n myStringList.Sort(new DynamicComparer&lt;string&gt;(x =&gt; x.Length, true));\n\n // Assert\n Assert.IsNotNull(myStringList);\n Assert.AreEqual(5, myStringList.Count);\n Assert.AreEqual(\"abcde\", myStringList(0));\n Assert.AreEqual(\"abcd\", myStringList(1));\n Assert.AreEqual(\"abc\", myStringList(2));\n Assert.AreEqual(\"ab\", myStringList(3));\n Assert.AreEqual(\"a\", myStringList(4));\n }\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9323/" ]
I have an `IList<T>` that I need to sort, and I would rather not copy the list if possible. I've noticed that `ArrayList` has an `Adapter` static method that wraps the passed list without copying it, but this takes an `IList` and I have an `IList<T>`. Is it safe to cast from a `System.Collections.Generic.IList<T>` to a `System.Collections.IList` and just use the `Adapter` method? Note that this is .Net 2.0, so LINQ is not an option.
From the blog of Paul Fox, I recommend the post "How to sort an IList": <http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html> Just in case that blog goes away in the future, I'll copy the post here: --- **How to sort a generic IList** Update You can read and updated post about [sorting generic IList and List](http://foxsys.blogspot.com/2008/05/how-to-sort-generic-list-sorting-list.html). Many people will prefer the methods mentioned in the updated post. Sorting a generic IList I was trying to sort a generic IList<> and found a fairly simple way of doing it. Step 1 You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class. ``` public class LanguageDto : IComparable { private String name; public string Name { get { return name; } set { name = value; } } public LanguageDto(string name) { this.name = name; } #region IComparable Members public int CompareTo(object obj) { if (obj is LanguageDto) { LanguageDto language = (LanguageDto)obj; return this.name.CompareTo(language.name); } throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString())); } #endregion } ``` STEP 2 Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so... ``` ArrayList.Adapter((IList)languages).Sort(); ``` Note: languages is of type "IList" Languages should then be a sorted list of your type!
227,007
<p>In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?</p> <p>In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.</p> <p><code>SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';</code></p>
[ { "answer_id": 227044, "author": "thoroughly", "author_id": 8943, "author_profile": "https://Stackoverflow.com/users/8943", "pm_score": 3, "selected": false, "text": "<p>Assuming your \"timestamp\" is a java.util.Date, which is represented as the number of milliseconds since the beginning of the epoch (Jan 1, 1970), you can perform the following arithmetic:</p>\n\n<pre><code>public static Date stripTimePortion(Date timestamp) {\n long msInDay = 1000 * 60 * 60 * 24; // Number of milliseconds in a day\n long msPortion = timestamp.getTime() % msInDay;\n return new Date(timestamp.getTime() - msPortion);\n}\n</code></pre>\n" }, { "answer_id": 227049, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 7, "selected": true, "text": "<p>You can go Date->Calendar->set->Date:</p>\n\n<pre><code>Date date = new Date(); // timestamp now\nCalendar cal = Calendar.getInstance(); // get calendar instance\ncal.setTime(date); // set cal to date\ncal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight\ncal.set(Calendar.MINUTE, 0); // set minute in hour\ncal.set(Calendar.SECOND, 0); // set second in minute\ncal.set(Calendar.MILLISECOND, 0); // set millis in second\nDate zeroedDate = cal.getTime(); // actually computes the new Date\n</code></pre>\n\n<p>I love Java dates.</p>\n\n<p>Note that if you're using actual java.sql.Timestamps, they have an extra nanos field. Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object.</p>\n\n<p>I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.</p>\n" }, { "answer_id": 227050, "author": "Jan Gressmann", "author_id": 6200, "author_profile": "https://Stackoverflow.com/users/6200", "pm_score": 1, "selected": false, "text": "<p>Since I don't do much DateTime manipulation, this might not be the best way to do it. I would spawn a Calendar and use the Date as source. Then set hours, minutes and seconds to 0 and convert back to Date. Would be nice to see a better way, though.</p>\n" }, { "answer_id": 227186, "author": "Domchi", "author_id": 29192, "author_profile": "https://Stackoverflow.com/users/29192", "pm_score": 0, "selected": false, "text": "<p>Using Calendar.set() would certanly be \"by the book\" solution, but you might also use java.sql.Date:</p>\n\n<pre><code>java.util.Date originalDate = new java.util.Date();\njava.sql.Date wantedDate = new java.sql.Date(originalDate.getTime());\n</code></pre>\n\n<p>That would do exactly what you want since:</p>\n\n<blockquote>\n <p>To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated. </p>\n</blockquote>\n\n<p>Since java.sql.Date extends java.util.Date, you can freely use it as such. Be aware that wantedDate.getTime() will retrieve original timestamp though - that's why you don't want to create another java.util.Date from java.sql.Date!</p>\n" }, { "answer_id": 227595, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 4, "selected": false, "text": "<p>If you're using commons lang you can call <code>DateUtils.truncate</code>. Here's the <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/time/DateUtils.html#truncate(java.util.Date,%20int)\" rel=\"noreferrer\">javadoc documentation</a>.</p>\n\n<p>It does the same thing @Alex Miller said to do.</p>\n" }, { "answer_id": 13462986, "author": "Torben Kohlmeier", "author_id": 1836528, "author_profile": "https://Stackoverflow.com/users/1836528", "pm_score": 2, "selected": false, "text": "<p>I prefer this solution:</p>\n\n<pre><code>GregorianCalendar now = new GregorianCalendar();\nGregorianCalendar calendar = new GregorianCalendar(\n now.get(GregorianCalendar.YEAR), now.get(GregorianCalendar.MONTH), \n now.get(GregorianCalendar.DAY_OF_MONTH));\n</code></pre>\n" }, { "answer_id": 22518375, "author": "Ziya", "author_id": 1325331, "author_profile": "https://Stackoverflow.com/users/1325331", "pm_score": 2, "selected": false, "text": "<p>Do this</p>\n\n<pre><code>import org.apache.commons.lang.time.DateUtils;\n\nDate myDate = new Date();\nSystem.out.println(myDate); \nSystem.out.println(DateUtils.truncate(myDate, Calendar.DATE));\n</code></pre>\n\n<p>and the output is</p>\n\n<p>Wed Mar 19 14:16:47 PDT 2014<br>\nWed Mar 19 00:00:00 PDT 2014</p>\n" }, { "answer_id": 31340625, "author": "Richard Gomes", "author_id": 62131, "author_profile": "https://Stackoverflow.com/users/62131", "pm_score": 0, "selected": false, "text": "<p>Find below a solution which employs Joda Time and supports time zones.\nSo, you will obtain the current date and time (into <code>currentDate</code> and <code>currentTime</code>) or some date and time you inform (into <code>informedDate</code> and <code>informedTime</code>) in the currently configured timezone in the JVM.</p>\n\n<p>The code below also informs if the informed date/time is in future (variable <code>schedulable</code>).</p>\n\n<p>Please notice that Joda Time does not support <em>leap seconds</em>. So, you can be some 26 or 27 seconds off the true value. This probably will only be solved in the next 50 years, when the accumulated error will be closer to 1 min and people will start to care about it.</p>\n\n<p>See also: <a href=\"https://en.wikipedia.org/wiki/Leap_second\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Leap_second</a></p>\n\n<pre><code>/**\n * This class splits the current date/time (now!) and an informed date/time into their components:\n * &lt;lu&gt;\n * &lt;li&gt;schedulable: if the informed date/time is in the present (now!) or in future.&lt;/li&gt;\n * &lt;li&gt;informedDate: the date (only) part of the informed date/time&lt;/li&gt;\n * &lt;li&gt;informedTime: the time (only) part of the informed date/time&lt;/li&gt;\n * &lt;li&gt;currentDate: the date (only) part of the current date/time (now!)&lt;/li&gt;\n * &lt;li&gt;currentTime: the time (only) part of the current date/time (now!)&lt;/li&gt;\n * &lt;/lu&gt;\n */\npublic class ScheduleDateTime {\n public final boolean schedulable;\n public final long millis;\n public final java.util.Date informedDate;\n public final java.util.Date informedTime;\n public final java.util.Date currentDate;\n public final java.util.Date currentTime;\n\n public ScheduleDateTime(long millis) {\n final long now = System.currentTimeMillis();\n this.schedulable = (millis &gt; -1L) &amp;&amp; (millis &gt;= now);\n\n final TimeZoneUtils tz = new TimeZoneUtils();\n\n final java.util.Date dmillis = new java.util.Date( (millis &gt; -1L) ? millis : now );\n final java.time.ZonedDateTime zdtmillis = java.time.ZonedDateTime.ofInstant(dmillis.toInstant(), java.time.ZoneId.systemDefault());\n final java.util.Date zdmillis = java.util.Date.from(tz.tzdate(zdtmillis));\n final java.util.Date ztmillis = new java.util.Date(tz.tztime(zdtmillis));\n\n final java.util.Date dnow = new java.util.Date(now);\n final java.time.ZonedDateTime zdtnow = java.time.ZonedDateTime.ofInstant(dnow.toInstant(), java.time.ZoneId.systemDefault());\n final java.util.Date zdnow = java.util.Date.from(tz.tzdate(zdtnow));\n final java.util.Date ztnow = new java.util.Date(tz.tztime(zdtnow));\n\n this.millis = millis;\n this.informedDate = zdmillis;\n this.informedTime = ztmillis;\n this.currentDate = zdnow;\n this.currentTime = ztnow;\n }\n}\n\n\n\npublic class TimeZoneUtils {\n\n public java.time.Instant tzdate() {\n final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();\n return tzdate(zdtime);\n }\n public java.time.Instant tzdate(java.time.ZonedDateTime zdtime) {\n final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);\n final java.time.Instant instant = zddate.toInstant();\n return instant;\n }\n\n public long tztime() {\n final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();\n return tztime(zdtime);\n }\n public long tztime(java.time.ZonedDateTime zdtime) {\n final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);\n final long millis = zddate.until(zdtime, java.time.temporal.ChronoUnit.MILLIS);\n return millis;\n }\n}\n</code></pre>\n" }, { "answer_id": 41723114, "author": "MAbraham1", "author_id": 212950, "author_profile": "https://Stackoverflow.com/users/212950", "pm_score": 0, "selected": false, "text": "<p>Here's a simple function with a main example:</p>\n\n<pre><code>import java.util.Calendar;\nimport java.util.Date;\npublic class Util {\n/**\n * Returns an imprecise date/timestamp. \n * @param date\n * @return the timestamp with zeroized seconds/milliseconds\n */\npublic static Date getImpreciseDate(Date date) {\n Calendar cal = Calendar.getInstance(); // get calendar instance\n cal.setTime(date);// set cal to date\n cal.set(Calendar.SECOND, 0); // zeroize seconds \n cal.set(Calendar.MILLISECOND, 0); // zeroize milliseconds\n return cal.getTime();\n}\n\npublic static void main(String[] args){\n Date now = new Date();\n now.setTime(System.currentTimeMillis()); // set time to now\n System.out.println(\"Precise date: \" + Util.getImpreciseDate(now));\n System.out.println(\"Imprecise date: \" + Util.getImpreciseDate(now));\n}\n}\n</code></pre>\n" }, { "answer_id": 57574338, "author": "Sabir Khan", "author_id": 3850730, "author_profile": "https://Stackoverflow.com/users/3850730", "pm_score": 0, "selected": false, "text": "<p>Just trying to put an answer for Java-8 , though answers using <code>Calendar</code> are valid too but lots of folks are not using that class anymore. </p>\n\n<p>Refer SO Answers <a href=\"https://stackoverflow.com/questions/51368395/convert-java-sql-timestamp-to-java-8-zoneddatetime\">this</a> &amp; <a href=\"https://stackoverflow.com/questions/44002104/localdatetime-zoneddatetime-and-timestamp\">this</a> to understand conversions between <code>java.time.ZonedDateTime</code> &amp; <code>java.sql.Timestamp</code></p>\n\n<p>then you can simply truncate <code>ZonedDateTime</code> on days &amp; reconvert back to <code>Timestamp</code></p>\n\n<pre><code>Timestamp.valueOf(ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).toLocalDateTime())\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ? In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java. `SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';`
You can go Date->Calendar->set->Date: ``` Date date = new Date(); // timestamp now Calendar cal = Calendar.getInstance(); // get calendar instance cal.setTime(date); // set cal to date cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight cal.set(Calendar.MINUTE, 0); // set minute in hour cal.set(Calendar.SECOND, 0); // set second in minute cal.set(Calendar.MILLISECOND, 0); // set millis in second Date zeroedDate = cal.getTime(); // actually computes the new Date ``` I love Java dates. Note that if you're using actual java.sql.Timestamps, they have an extra nanos field. Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object. I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.
227,030
<p>I'm writing a class that renders some content in WPF, and I want to give the user control over how the content is rendered. The rendering is mostly stroking lines, so I decided to look to the System.Windows.Forms.Shapes.Line class to get an idea of what properties I might want to implement. This led me to implement most of the <code>StrokeXXXX</code> properties, and it's a lot of drudgework since each requires metadata to affect the rendering.</p> <p>A colleague suggested that I just "borrow" the properties from Shape like this:</p> <pre><code>Shape.StrokeThicknessProperty.AddOwner(typeof(MyType)); </code></pre> <p>This seems like a pretty good idea. I thought that by doing this I'd lose the ability to set coercion and property changed callbacks, but it looks like the overload that takes a PropertyMetadata allows this. The only downside I can see is if the implementation of Shape changes, it will affect our class, but I'm uncertain how often I expect the .NET interfaces to change significantly.</p> <p>What do you think? Is this a decent shortcut to defining properties when a well-known class has the behavior you want and a stable interface, or a sure-fire way to play with fire while in a gasoline bath?</p>
[ { "answer_id": 228704, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 3, "selected": true, "text": "<p>It is very safe and useful to borrow DPs... Read the <a href=\"http://www.drwpf.com/blog/Home/tabid/36/EntryID/20/Default.aspx\" rel=\"nofollow noreferrer\">following</a> post by Dr WPF about the subject!</p>\n\n<p>Here is a few of the \"tips\" he provide:</p>\n\n<ul>\n<li>You should always know what the owner class does with any property you borrow. </li>\n<li>You should pay attention to default values and inheritance. Sometimes you need a bool property with a default value of true... other times you may want a default value of false. Sometimes you need a property that inherits... other times you explicitly don't want inheritance. (Borrowing a property like TextElement.FontSize could really screw up things lower in the tree.)</li>\n<li>The owner class may sometimes define a PropertyChangedCallback that will interfere with your ability to use the property as you wish. Always know what the owner class does with the property.</li>\n<li>The owner class may provide a validation routine for the property that prevents you from entering the value you want to specify. Again, always know what the owner class does with the property.\nThe property may be registered in a manner that makes it costly perf-wise, such as FixedPage.Bottom which invalidates the parent's arrange anytime the property changes on an object. Sometimes you may explicitly want this behavior... other times it will just unnecessarily cause layout passes. Again, always know what the owner class does with the property.</li>\n<li>If you use a property in a scenario where the framework itself is trying to use the property (such as TextSearch.TextPath on an ItemsControl), you are liable to find yourself in contention with the framework.</li>\n</ul>\n" }, { "answer_id": 235029, "author": "Ed Ball", "author_id": 23818, "author_profile": "https://Stackoverflow.com/users/23818", "pm_score": 1, "selected": false, "text": "<p>I'd just keep creating my own dependency properties, personally. It really isn't much extra work, and then you don't have to worry about any of the possible caveats.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
I'm writing a class that renders some content in WPF, and I want to give the user control over how the content is rendered. The rendering is mostly stroking lines, so I decided to look to the System.Windows.Forms.Shapes.Line class to get an idea of what properties I might want to implement. This led me to implement most of the `StrokeXXXX` properties, and it's a lot of drudgework since each requires metadata to affect the rendering. A colleague suggested that I just "borrow" the properties from Shape like this: ``` Shape.StrokeThicknessProperty.AddOwner(typeof(MyType)); ``` This seems like a pretty good idea. I thought that by doing this I'd lose the ability to set coercion and property changed callbacks, but it looks like the overload that takes a PropertyMetadata allows this. The only downside I can see is if the implementation of Shape changes, it will affect our class, but I'm uncertain how often I expect the .NET interfaces to change significantly. What do you think? Is this a decent shortcut to defining properties when a well-known class has the behavior you want and a stable interface, or a sure-fire way to play with fire while in a gasoline bath?
It is very safe and useful to borrow DPs... Read the [following](http://www.drwpf.com/blog/Home/tabid/36/EntryID/20/Default.aspx) post by Dr WPF about the subject! Here is a few of the "tips" he provide: * You should always know what the owner class does with any property you borrow. * You should pay attention to default values and inheritance. Sometimes you need a bool property with a default value of true... other times you may want a default value of false. Sometimes you need a property that inherits... other times you explicitly don't want inheritance. (Borrowing a property like TextElement.FontSize could really screw up things lower in the tree.) * The owner class may sometimes define a PropertyChangedCallback that will interfere with your ability to use the property as you wish. Always know what the owner class does with the property. * The owner class may provide a validation routine for the property that prevents you from entering the value you want to specify. Again, always know what the owner class does with the property. The property may be registered in a manner that makes it costly perf-wise, such as FixedPage.Bottom which invalidates the parent's arrange anytime the property changes on an object. Sometimes you may explicitly want this behavior... other times it will just unnecessarily cause layout passes. Again, always know what the owner class does with the property. * If you use a property in a scenario where the framework itself is trying to use the property (such as TextSearch.TextPath on an ItemsControl), you are liable to find yourself in contention with the framework.
227,066
<p>I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why.</p> <p>For example, the second CaselessIs method calls the first:</p> <pre><code>public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable&lt;string&gt; compareTo) { foreach(string comparison in compareTo) { if (s.CaselessIs(comparison)) { return true; } } return false; } </code></pre> <p>Would it be more appropriate to not do this? The downside would be that it violates DRY.</p> <pre><code>public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable&lt;string&gt; compareTo) { foreach(string comparison in compareTo) { if (string.Compare(s, comparison, true) == 0) { return true; } } return false; } </code></pre>
[ { "answer_id": 227103, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>I personally don't see a problem with it, the second scenario I think feels more wrong....</p>\n" }, { "answer_id": 227106, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 4, "selected": true, "text": "<p>I would have to say that DRY controls here. Personally, I see nothing wrong with an extension method calling another extension method, especially if that other extension is contained within the same assembly. All-in-all, the method calls are just translated by the compiler from:</p>\n\n<pre><code>extended.ExtensionMethod(foo);\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>StaticType.ExtensionMethod(extended, foo);\n</code></pre>\n\n<p>I don't see any problem chaining two static methods together, so transitively, I don't see a problem with chaining two extension methods.</p>\n" }, { "answer_id": 227107, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>I have no problem with it, myself - though, if it makes you feel better, you could certainly use the static version instead:</p>\n\n<pre><code>public static bool CaselessIs(this string s, IEnumerable&lt;string&gt; compareTo)\n{\n foreach(string comparison in compareTo)\n {\n if (Extensions.CaselessIs(s, comparison))\n {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>Personally, in this example, I would've called it CaselessMatches, and had the singular call the plural...but that's just nitpicky, I suppose.</p>\n" }, { "answer_id": 227108, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 2, "selected": false, "text": "<p>Perfectly right. Why should it be wrong?</p>\n\n<p>As you're defining an extension method you're implictily targeting the 3.0 framework (actually the compiler extensions of the new languages) so there's nothing wrong about using just another extension to do the work.</p>\n\n<p>Reviewing the comments there's nothing wrong with any version, not even if the \"other\" extension was in another library, at least not in the sense of \"using\" an extension from another one. Extensions are just a syntax feature which helps to better understand the underlying logic between the code, adding some usual operations to a class... in reality they are just masked calls to methods and in that way you should apply exactly the same restriction you use with method calls.</p>\n" }, { "answer_id": 227110, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 1, "selected": false, "text": "<p>I see nothing wrong with it. Let's say you create a someClass.ToMySpecialString(). Why shouldn't you be able to overload it if someClass.ToString() already has multiple overloads?</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why. For example, the second CaselessIs method calls the first: ``` public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable<string> compareTo) { foreach(string comparison in compareTo) { if (s.CaselessIs(comparison)) { return true; } } return false; } ``` Would it be more appropriate to not do this? The downside would be that it violates DRY. ``` public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable<string> compareTo) { foreach(string comparison in compareTo) { if (string.Compare(s, comparison, true) == 0) { return true; } } return false; } ```
I would have to say that DRY controls here. Personally, I see nothing wrong with an extension method calling another extension method, especially if that other extension is contained within the same assembly. All-in-all, the method calls are just translated by the compiler from: ``` extended.ExtensionMethod(foo); ``` to: ``` StaticType.ExtensionMethod(extended, foo); ``` I don't see any problem chaining two static methods together, so transitively, I don't see a problem with chaining two extension methods.
227,078
<p>I'd love to create a "back" left-arrow-bezel button in a <code>UIToolbar</code>.</p> <p>As far as I can tell, the only way to get one of these is to leave <code>UINavigationController</code> at default settings and it uses one for the left bar item. But there's no way I can find to create one as a <code>UIBarButtonItem</code>, so I can't make one in a standard <code>UIToolbar</code>, even though they're very similar to <code>UINavigationBar</code>s.</p> <p>I could manually create it with button images, but I can't find the source images anywhere. They have alpha-channel edges, so screenshotting and cutting won't get very versatile results.</p> <p>Any ideas beyond screenshotting for every size and color scheme I intend to use?</p> <p><strong>Update:</strong> PLEASE STOP dodging the question and suggesting that I shouldn't be asking this and should be using <code>UINavigationBar</code>. My app is Instapaper Pro. It shows only a bottom toolbar (to save space and maximize readable content area), and I wish to put a left-arrow-shaped Back button in the bottom.</p> <p>Telling me that I shouldn't need to do this <strong>is not an answer</strong> and certainly doesn't deserve a bounty.</p>
[ { "answer_id": 227135, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 0, "selected": false, "text": "<p>Well, you don't have to have a different button for every size, you can use <code>[UIImage stretchableImageWithLeftCapWidth:topCapHeight:]</code>, but the only thing I've found is custom images.</p>\n" }, { "answer_id": 228208, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": -1, "selected": false, "text": "<p>Why are you doing this? If you want something that looks like a navigation bar, use UINavigationBar.</p>\n\n<p>Toolbars have specific visual style associated with them. The Human Interface Guidelines for the iPhone state:</p>\n\n<blockquote>\n <p>A toolbar appears at the bottom edge of the screen and contains buttons that perform actions related to objects in the current view.</p>\n</blockquote>\n\n<p>It then gives several visual examples of roughly square icons with no text. I would urge you to follow the HIG on this.</p>\n" }, { "answer_id": 574863, "author": "PyjamaSam", "author_id": 55453, "author_profile": "https://Stackoverflow.com/users/55453", "pm_score": 8, "selected": true, "text": "<p>I used the following psd that I derived from <a href=\"http://www.teehanlax.com/blog/?p=447\" rel=\"noreferrer\">http://www.teehanlax.com/blog/?p=447</a></p>\n\n<p><a href=\"http://www.chrisandtennille.com/pictures/backbutton.psd\" rel=\"noreferrer\">http://www.chrisandtennille.com/pictures/backbutton.psd</a></p>\n\n<p>I then just created a custom UIView that I use in the customView property of the toolbar item.</p>\n\n<p>Works well for me.</p>\n\n<hr>\n\n<p><em>Edit:</em> <a href=\"https://stackoverflow.com/questions/227078/creating-a-left-arrow-button-like-uinavigationbars-back-style-on-a-uitoolba/3985773#comment12106974_3985773\">As pointed out by <em>PrairieHippo</em></a>, <em>maralbjo</em> found that using the following, simple code did the trick (requires custom image in bundle) should be combined with this answer. So here is additional code:</p>\n\n<pre><code>// Creates a back button instead of default behaviour (displaying title of previous screen)\nUIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"back_arrow.png\"]\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(backAction)];\n\ntipsDetailViewController.navigationItem.leftBarButtonItem = backButton;\n[backButton release];\n</code></pre>\n" }, { "answer_id": 577237, "author": "John Lane", "author_id": 53930, "author_profile": "https://Stackoverflow.com/users/53930", "pm_score": 0, "selected": false, "text": "<p>If you want to avoid drawing it yourself, you could use the undocumented class: UINavigationButton with style 1. This could, of course, stop your application from being approved...\n/John</p>\n" }, { "answer_id": 580322, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "<p>You can find the source images by extracting them from Other.artwork in UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork. The modding community has some tools for extracting them, <a href=\"http://www.modmyi.com/forums/skinning-themes-discussion/425091-new-iphoneshop-1-22-supports-all-2-2-artwork.html\" rel=\"nofollow noreferrer\">here</a>. Once you extract the image you can write some code to recolor it as necessary and set it as the button image. Whether or not you can actually ship such a thing (since you are embedding derived artwork) might be a little dicey, so maybe you want to talk to a lawyer.</p>\n" }, { "answer_id": 580341, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "<p>I'm not sure if this would work, but you could try creating a <code>UINavigationController</code> with the default settings to create the button, find the button in the navigation controller's subview hierarchy, call <code>removeFromSuperview</code> on it, destroy the navigation controller, and then add the button as a subview of your toolbar. You may also need to <code>retain</code> and the button before calling <code>removeFromSuperview</code> (and then <code>release</code> it after adding it as subview of your toolbar) to avoid it being deallocated during the process.</p>\n" }, { "answer_id": 583947, "author": "Domness", "author_id": 53677, "author_profile": "https://Stackoverflow.com/users/53677", "pm_score": 1, "selected": false, "text": "<p>To create an image for the UIToolbar, make a png in photoshop and WHERE EVER there is ANY colour it puts it white, and where it's alpha = 0 then it leaves it alone.</p>\n\n<p>The SDK actually put's the border around the icon you have made and turns it white without you having to do anything.</p>\n\n<p>See, this is what I made in Photoshop for my forward button (obviously swap it around for back button):</p>\n\n<p><a href=\"http://twitpic.com/1oanv\" rel=\"nofollow noreferrer\">http://twitpic.com/1oanv</a></p>\n\n<p>and this is what it appeared like in Interface Builder</p>\n\n<p><a href=\"http://twitpic.com/1oaoa\" rel=\"nofollow noreferrer\">http://twitpic.com/1oaoa</a></p>\n" }, { "answer_id": 1766704, "author": "Andrew Arrow", "author_id": 148736, "author_profile": "https://Stackoverflow.com/users/148736", "pm_score": 2, "selected": false, "text": "<p>The Three20 library has a way to do this:</p>\n\n<pre><code> UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @\"Title\" style:UIBarButtonItemStylePlain \n target:self action:@selector(foo)];\n\n UIColor* darkBlue = RGBCOLOR(109, 132, 162);\n\n TTShapeStyle* style = [TTShapeStyle styleWithShape:[TTRoundedLeftArrowShape shapeWithRadius:4.5] next:\n [TTShadowStyle styleWithColor:RGBCOLOR(255,255,255) blur:1 offset:CGSizeMake(0, 1) next:\n [TTReflectiveFillStyle styleWithColor:darkBlue next:\n [TTBevelBorderStyle styleWithHighlight:[darkBlue shadow]\n shadow:[darkBlue multiplyHue:1 saturation:0.5 value:0.5]\n width:1 lightSource:270 next:\n [TTInsetStyle styleWithInset:UIEdgeInsetsMake(0, -1, 0, -1) next:\n [TTBevelBorderStyle styleWithHighlight:nil shadow:RGBACOLOR(0,0,0,0.15)\n width:1 lightSource:270 next:nil]]]]]];\n\n TTView* view = [[[TTView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)] autorelease];\n view.backgroundColor = [UIColor clearColor];\n view.style = style;\n backButton.customView = view;\n\n\n self.navigationItem.leftBarButtonItem = backButton;\n</code></pre>\n" }, { "answer_id": 3406308, "author": "Cameron Lowell Palmer", "author_id": 410867, "author_profile": "https://Stackoverflow.com/users/410867", "pm_score": 6, "selected": false, "text": "<h2>The Unicode Method</h2>\n\n<p>I think it is much easier to just use a unicode character to get the job done. You can look through arrows by googling either <a href=\"http://www.fileformat.info/info/unicode/block/geometric_shapes/list.htm\" rel=\"nofollow noreferrer\">Unicode Triangles</a> or <a href=\"http://www.fileformat.info/info/unicode/block/arrows/list.htm\" rel=\"nofollow noreferrer\">Unicode Arrows</a>. Starting with iOS6 Apple changed the character to be an emoji character with a border. To disable the border I add the 0xFE0E <a href=\"https://stackoverflow.com/questions/4974668/what-is-the-unicode-variation-selector\">Unicode Variation Selector</a>. </p>\n\n<pre><code>NSString *backArrowString = @\"\\U000025C0\\U0000FE0E\"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR\n\nUIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:nil action:nil];\nself.navigationItem.leftButtonItem = backBarButtonItem;\n</code></pre>\n\n<p>The code block is just for the demo. It would work in any button that accepts an NSString.</p>\n\n<p>For a full list of characters search Google for Unicode character and what you want. Here is the entry for <a href=\"http://www.fileformat.info/info/unicode/char/25c0/index.htm\" rel=\"nofollow noreferrer\">Black Left-Pointing Triangle</a>.</p>\n\n<h2>Result</h2>\n\n<p><img src=\"https://i.stack.imgur.com/C2IPg.png\" alt=\"The result\"></p>\n" }, { "answer_id": 3426793, "author": "AndrewS", "author_id": 173964, "author_profile": "https://Stackoverflow.com/users/173964", "pm_score": 5, "selected": false, "text": "<p><strong>WARNING:</strong> There are reports that this will not work on iOS 6. This might only work on older versions of the OS. Evidently at least one dev has had their app rejected for using this trick (see the comments). Use at your own risk. Using an image (see answer above) might be a safer solution.</p>\n\n<p>This can be done without adding in your own image files using sekr1t button type 101 to get the correct shape. For me the trick was figuring out that I could use <code>initWithCustomView</code> to create the <code>BarButtonItem</code>. I personally needed this for a dynamic navbar rather than a <code>toolbar</code>, but I tested it with a toolbar and the code is nearly the same:</p>\n\n<pre><code>// create button\nUIButton* backButton = [UIButton buttonWithType:101]; // left-pointing shape!\n[backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];\n[backButton setTitle:@\"Back\" forState:UIControlStateNormal];\n\n// create button item -- possible because UIButton subclasses UIView!\nUIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];\n\n// add to toolbar, or to a navbar (you should only have one of these!)\n[toolbar setItems:[NSArray arrayWithObject:backItem]];\nnavItem.leftBarButtonItem = backItem;\n</code></pre>\n\n<p>If you're doing this on a toolbar you'll have to tweak how you set the items, but that depends on the rest of your code and I leave that as an exercise for the reader. :P This sample worked for me (compiled &amp; run).</p>\n\n<p>Blah blah, read the HIG, don't use undocumented features, and all that. There's only six supported button types and this isn't one of them.</p>\n" }, { "answer_id": 3639703, "author": "marikaner", "author_id": 433926, "author_profile": "https://Stackoverflow.com/users/433926", "pm_score": 2, "selected": false, "text": "<p>I was trying to do the same thing, but I wanted the back button to be in the navigation bar. (I actually needed a back button, that would do more than only going back, so I had to use the leftBarButtonItem property). I tried what AndrewS suggested, but in the navigation bar it wouldn't look the way it should, as the UIButton was kind of casted to a UIBarButtonItem.</p>\n\n<p>But I found a way to work around this. I actually just put a UIView under the UIButton and set the customView for the UIBarButtonItem. Here is the code, if somebody needs it:</p>\n\n<pre><code>// initialize button and button view\nUIButton *backButton = [UIButton buttonWithType:101];\nUIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backButton.frame.size.width, backButton.frame.size.height)];\n\n[backButton addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside];\n[backButton setTitle:@\"Back\" forState:UIControlStateNormal];\n[backButtonView addSubview:backButton];\n\n// set buttonview as custom view for bar button item\nUIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];\nself.navigationItem.leftBarButtonItem = backButtonItem;\n\n// push item to navigationbar items\n[self.navigationController.navigationBar setItems:[NSArray arrayWithObject:backButtonItem]];\n</code></pre>\n" }, { "answer_id": 3985773, "author": "maralbjo", "author_id": 156395, "author_profile": "https://Stackoverflow.com/users/156395", "pm_score": 2, "selected": false, "text": "<p>I found that using the following, simple code did the trick (requires custom image in bundle): </p>\n\n<pre><code>// Creates a back button instead of default behaviour (displaying title of previous screen)\n UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"back_arrow.png\"]\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(backAction)];\n\n tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;\n [backButton release];\n</code></pre>\n" }, { "answer_id": 4854786, "author": "quantumpotato", "author_id": 172232, "author_profile": "https://Stackoverflow.com/users/172232", "pm_score": 3, "selected": false, "text": "<pre><code> self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;\n</code></pre>\n\n<p>Works for me. I used this when I had more tabs then could fit on the tab bar, and a view controller pushed from the \"More\" overrode the leftBarButtonItem in its viewDidLoad.</p>\n" }, { "answer_id": 10748447, "author": "Steve", "author_id": 1043343, "author_profile": "https://Stackoverflow.com/users/1043343", "pm_score": 2, "selected": false, "text": "<p>Here's what I ended up doing after searching through all these solutions and others. It uses a stretchable png's extracted from the UIKit stock images. This way you can set the text to whatever you liek</p>\n\n<pre><code>// Generate the background images\nUIImage *stretchableBackButton = [[UIImage imageNamed:@\"UINavigationBarDefaultBack.png\"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];\nUIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@\"UINavigationBarDefaultBackPressed.png\"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];\n// Setup the UIButton\nUIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];\n[backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];\n[backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];\nNSString *buttonTitle = NSLocalizedString(@\"Back\", @\"Back\");\n[backButton setTitle:buttonTitle forState:UIControlStateNormal];\n[backButton setTitle:buttonTitle forState:UIControlStateSelected];\nbackButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position\nNSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);\n[backButton setFrame:CGRectMake(0, 0, width, 29)];\nbackButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];\n[backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];\n// Now add the button as a custom UIBarButtonItem\nUIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];\nself.navigationItem.leftBarButtonItem = backButtonItem;\n</code></pre>\n" }, { "answer_id": 12072890, "author": "Mj.B", "author_id": 1556934, "author_profile": "https://Stackoverflow.com/users/1556934", "pm_score": -1, "selected": false, "text": "<p>Try this. I am sure you do not need a back button image to create one such.</p>\n\n<pre><code>UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@\"Back\"\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(yourSelectorGoesHere:)];\nself.navigationItem.backBarButtonItem = backButton;\n</code></pre>\n\n<p>That's all you have to do :)</p>\n" }, { "answer_id": 17941917, "author": "Shuo", "author_id": 334999, "author_profile": "https://Stackoverflow.com/users/334999", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem, and come out one library <a href=\"https://github.com/shuoli84/PButton\" rel=\"nofollow noreferrer\">PButton</a>. And the sample is the back navigation button like button, which can be used anywhere just like a customized button. </p>\n\n<p>Something like this:\n<img src=\"https://i.stack.imgur.com/sNAXZ.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 18874211, "author": "Alexey", "author_id": 744015, "author_profile": "https://Stackoverflow.com/users/744015", "pm_score": 5, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/8mPcu.png\" alt=\"enter image description here\"></p>\n\n<p>First of all you have to find an image of the back button. I used a nice app called <a href=\"https://github.com/0xced/iOS-Artwork-Extractor\" rel=\"nofollow noreferrer\">Extractor</a> that extracts all the graphics from iPhone.\nIn <strong>iOS7</strong> I managed to retrieve the image called <code>UINavigationBarBackIndicatorDefault</code> and it was in black colour, since I needed a red tint <strike>I change the colour to red using Gimp.</strike></p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>As was mentioned by <a href=\"https://stackoverflow.com/users/450847/btate\">btate</a> in his comment, there is no need to change the color with the image editor. The following code should do the trick:</p>\n\n<pre><code>imageView.tint = [UIColor redColor];\nimageView.image = [[UIImage imageNamed:@\"UINavigationBarBackIndicatorDefault\"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];\n</code></pre>\n\n<p>Then I created a view that contains an imageView with that arrow, a label with the custom text and on top of the view I have a button with an action. Then I added a simple animation (fading and translation).</p>\n\n<p>The following code simulates the behaviour of the back button including animation.</p>\n\n<pre><code>-(void)viewWillAppear:(BOOL)animated{\n UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"UINavigationBarBackIndicatorDefault\"]];\n [imageView setTintColor:[UIColor redColor]];\n UILabel *label=[[UILabel alloc] init];\n [label setTextColor:[UIColor redColor]];\n [label setText:@\"Blog\"];\n [label sizeToFit];\n\n int space=6;\n label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);\n UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];\n\n view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);\n [view addSubview:imageView];\n [view addSubview:label];\n\n UIButton *button=[[UIButton alloc] initWithFrame:view.frame];\n [button addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];\n [view addSubview:button];\n\n [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{\n label.alpha = 0.0;\n CGRect orig=label.frame;\n label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);\n label.alpha = 1.0;\n label.frame=orig;\n } completion:nil];\n\n UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];\n}\n\n- (void) handleBack:(id)sender{\n}\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Instead of adding the button, in my opinion the better approach is to use a gesture recognizer. </p>\n\n<pre><code>UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBack:)];\n[view addGestureRecognizer:tap];\n[view setUserInteractionEnabled:YES];\n</code></pre>\n" }, { "answer_id": 21453802, "author": "Anton Gaenko", "author_id": 440465, "author_profile": "https://Stackoverflow.com/users/440465", "pm_score": 2, "selected": false, "text": "<p>It's easy to do with <strong><em>Interface Builder</em></strong> in <strong>Xcode 5.x</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/z4pQO.png\" alt=\"Result\"> </p>\n\n<ul>\n<li><p>use <strong>Toolbar</strong> and <strong>Bar Button Item</strong> from <strong><em>Object library</em></strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/lXTrL.png\" alt=\"Components\"> </p></li>\n<li><p>in button's <strong><em>Attributes inspector</em></strong> edit <strong>Image</strong> section \nwith <em>your</em> back button image</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZR9uh.png\" alt=\"Attributes inspector\"></p></li>\n</ul>\n\n<p><strong>Done!</strong></p>\n" }, { "answer_id": 25419321, "author": "Bjørn Egil", "author_id": 455225, "author_profile": "https://Stackoverflow.com/users/455225", "pm_score": 4, "selected": false, "text": "<p>To make a UIButton with an arrow pretty close (I'm not a designer ;) to the iOS 7 system back arrow:</p>\n\n<p>Standard: </p>\n\n<p><img src=\"https://i.stack.imgur.com/UJ0uL.png\" alt=\"Standard system back arrow\"> </p>\n\n<p>Apple SD Gothic Neo</p>\n\n<p><img src=\"https://i.stack.imgur.com/FNJ1W.png\" alt=\"Apple SD Gothic Neo &lt; character\"></p>\n\n<p>In Xcode:</p>\n\n<ul>\n<li>Focus on the title value field of the button (or any other view/control with text content)</li>\n<li>Open Edit -> Special Characters</li>\n<li>Select the Parentheses group and double click the '&lt;' character</li>\n<li>Change font to: Apple SD Gothic Neo, Regular with desired size (e.g. 20)</li>\n<li>Change colour as you like</li>\n</ul>\n\n<p>Ref <a href=\"https://stackoverflow.com/a/20688668/455225\">@staticVoidMan's answer</a> to Back-like arrow on iOS 7</p>\n" }, { "answer_id": 25557645, "author": "Gabriel Jensen", "author_id": 416618, "author_profile": "https://Stackoverflow.com/users/416618", "pm_score": 1, "selected": false, "text": "<p>Solution WITHOUT using a png. Based on this SO answer: <a href=\"https://stackoverflow.com/questions/6322798/adding-the-little-arrow-to-the-right-side-of-a-cell-in-an-iphone-tableview-cell\">Adding the little arrow to the right side of a cell in an iPhone TableView Cell</a></p>\n\n<p>Just flipping the UITableViewCell horizontally!</p>\n\n<pre><code>UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 70, 20)];\n\n// Add the disclosure\nCGRect frm;\nUITableViewCell *disclosure = [[UITableViewCell alloc] init];\ndisclosure.transform = CGAffineTransformScale(CGAffineTransformIdentity, -1, 1);\nfrm = self.btnBack.bounds;\ndisclosure.frame = CGRectMake(frm.origin.x, frm.origin.y, frm.size.width-25, frm.size.height);\ndisclosure.accessoryType = UITableViewCellAccessoryDisclosureIndicator;\ndisclosure.userInteractionEnabled = NO;\n[self.btnBack addSubview:disclosure];\n\n// Add the label\nUILabel *lbl = [[UILabel alloc] init];\nfrm = CGRectOffset(self.btnBack.bounds, 15, 0);\nlbl.frame = frm;\nlbl.textAlignment = NSTextAlignmentCenter;\nlbl.text = @\"BACK\";\n[self addSubview:lbl];\n</code></pre>\n" }, { "answer_id": 34803540, "author": "machoota", "author_id": 1822154, "author_profile": "https://Stackoverflow.com/users/1822154", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/4ByUK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4ByUK.png\" alt=\"back arrow\"></a></p>\n\n<p>If you don't want to bother with image files, the arrow shape can be drawn in a UIView subclass with the following code:</p>\n\n<pre><code>- (void)drawRect:(CGRect)rect {\n float width = rect.size.width;\n float height = rect.size.height;\n CGContextRef context = UIGraphicsGetCurrentContext();\n\n CGContextBeginPath(context);\n CGContextMoveToPoint(context, width * 5.0/6.0, height * 0.0/10.0);\n CGContextAddLineToPoint(context, width * 0.0/6.0, height * 5.0/10.0);\n CGContextAddLineToPoint(context, width * 5.0/6.0, height * 10.0/10.0);\n CGContextAddLineToPoint(context, width * 6.0/6.0, height * 9.0/10.0);\n CGContextAddLineToPoint(context, width * 2.0/6.0, height * 5.0/10.0);\n CGContextAddLineToPoint(context, width * 6.0/6.0, height * 1.0/10.0);\n CGContextClosePath(context);\n\n CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);\n CGContextFillPath(context);\n}\n</code></pre>\n\n<p>where the arrow view is proportional to a width of 6.0 and a height of 10.0</p>\n" }, { "answer_id": 41550133, "author": "Bart van Kuik", "author_id": 1085556, "author_profile": "https://Stackoverflow.com/users/1085556", "pm_score": 0, "selected": false, "text": "<p>Example in Swift 3, with a previous and a next button in the top right.</p>\n\n<pre><code>let prevButtonItem = UIBarButtonItem(title: \"\\u{25C0}\", style: .plain, target: self, action: #selector(prevButtonTapped))\nlet nextButtonItem = UIBarButtonItem(title: \"\\u{25B6}\", style: .plain, target: self, action: #selector(nextButtonTapped))\nself.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]\n</code></pre>\n" }, { "answer_id": 42454113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Swift </p>\n\n<pre><code>// create button\n var backButton = UIButton(type: 101)\n\n // left-pointing shape!\n backButton.addTarget(self, action: #selector(self.backAction), for: .touchUpInside)\n backButton.setTitle(\"Back\", for: .normal)\n\n // create button item -- possible because UIButton subclasses UIView!\n var backItem = UIBarButtonItem(customView: backButton)\n\n // add to toolbar, or to a navbar (you should only have one of these!)\n toolbar.items = [backItem]\n navItem.leftBarButtonItem = backItem\n</code></pre>\n" }, { "answer_id": 61438985, "author": "rbaldwin", "author_id": 8197946, "author_profile": "https://Stackoverflow.com/users/8197946", "pm_score": 1, "selected": false, "text": "<p><strong>Swift 5.2 Xcode 11.4</strong></p>\n\n<p>The Apple Symbol <strong>chevron.left</strong> now allows a more elegant solution to make a custom button. I have matched the size and spacing as close as possible.</p>\n\n<p><a href=\"https://i.stack.imgur.com/X8VpJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/X8VpJ.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>import UIKit\n\nclass CustomBackButton: UIBarButtonItem {\n\n convenience init(target: Any, selector: Selector) {\n\n // Create UIButton\n let button = UIButton(frame: .zero)\n\n // Customise Title\n button.setTitle(\"Back\", for: .normal)\n button.setTitleColor(.systemBlue, for: .normal)\n button.titleLabel?.font = UIFont.systemFont(ofSize: 17)\n\n // Customise Image\n let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)\n let image = UIImage(systemName: \"chevron.left\", withConfiguration: config)\n button.setImage(image, for: .normal)\n\n // Add Target\n button.addTarget(target, action: selector, for: .touchUpInside)\n\n // Customise Spacing to match system Back button\n button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)\n button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)\n\n self.init(customView: button)\n }\n}\n</code></pre>\n\n<p>This can be implemented either as a <code>UIToolbarItem</code>, or a <code>UINavigationItem</code></p>\n\n<pre><code>override func viewDidLoad() {\n super.viewDidLoad()\n\n // UIToolbar Item\n let barBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))\n let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)\n navigationController?.setToolbarHidden(false, animated: false)\n toolbarItems = [barBackButton, flexSpace]\n\n // Navigation Item\n let navBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))\n navigationItem.leftBarButtonItem = navBackButton\n}\n\n@objc func backButtonTapped() {\n print(\"Back tapped\")\n}\n</code></pre>\n\n<p>If you want to flip the button and have the arrow pointing to the Right:</p>\n\n<p><a href=\"https://i.stack.imgur.com/I1JQ3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I1JQ3.png\" alt=\"enter image description here\"></a></p>\n\n<p>Use Apple Symbol named <strong>\"chevron.right\"</strong></p>\n\n<p>Add the following code to the <code>CustomBackButton</code> class:</p>\n\n<pre><code> // Put the image of the right side of the button\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30480/" ]
I'd love to create a "back" left-arrow-bezel button in a `UIToolbar`. As far as I can tell, the only way to get one of these is to leave `UINavigationController` at default settings and it uses one for the left bar item. But there's no way I can find to create one as a `UIBarButtonItem`, so I can't make one in a standard `UIToolbar`, even though they're very similar to `UINavigationBar`s. I could manually create it with button images, but I can't find the source images anywhere. They have alpha-channel edges, so screenshotting and cutting won't get very versatile results. Any ideas beyond screenshotting for every size and color scheme I intend to use? **Update:** PLEASE STOP dodging the question and suggesting that I shouldn't be asking this and should be using `UINavigationBar`. My app is Instapaper Pro. It shows only a bottom toolbar (to save space and maximize readable content area), and I wish to put a left-arrow-shaped Back button in the bottom. Telling me that I shouldn't need to do this **is not an answer** and certainly doesn't deserve a bounty.
I used the following psd that I derived from <http://www.teehanlax.com/blog/?p=447> <http://www.chrisandtennille.com/pictures/backbutton.psd> I then just created a custom UIView that I use in the customView property of the toolbar item. Works well for me. --- *Edit:* [As pointed out by *PrairieHippo*](https://stackoverflow.com/questions/227078/creating-a-left-arrow-button-like-uinavigationbars-back-style-on-a-uitoolba/3985773#comment12106974_3985773), *maralbjo* found that using the following, simple code did the trick (requires custom image in bundle) should be combined with this answer. So here is additional code: ``` // Creates a back button instead of default behaviour (displaying title of previous screen) UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(backAction)]; tipsDetailViewController.navigationItem.leftBarButtonItem = backButton; [backButton release]; ```
227,081
<p>I have ListView with Grouping Items. Grouping uses custom GroupStyle (Expander). I would like to have check box which will Expand and collapse all groups when. It works fine untill I click manually on the group header and expand or collapse that group. After clicking that particular group stops to respond on check box selection. Looks like binding is broken after user manually clicks on the group.</p> <p>Please advise what I am doing wrong.</p> <p>Thanks a lot.</p> <p>Sincerely, Vlad.</p> <pre><code>&lt;Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'&gt; &lt;Window.Resources&gt; &lt;XmlDataProvider x:Key="MyData" XPath="/Info"&gt; &lt;x:XData&gt; &lt;Info xmlns=""&gt; &lt;Item Name="Item 1" Category="Cat1" /&gt; &lt;Item Name="Item 2" Category="Cat1" /&gt; &lt;Item Name="Item 3" Category="Cat2" /&gt; &lt;Item Name="Item 4" Category="Cat2" /&gt; &lt;Item Name="Item 5" Category="Cat2" /&gt; &lt;Item Name="Item 6" Category="Cat3" /&gt; &lt;/Info&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}"&gt; &lt;CollectionViewSource.GroupDescriptions&gt; &lt;PropertyGroupDescription PropertyName="@Category" /&gt; &lt;/CollectionViewSource.GroupDescriptions&gt; &lt;/CollectionViewSource&gt; &lt;ControlTemplate x:Key="ListTemplate" TargetType="ListView"&gt; &lt;ListView BorderThickness="0" ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}' DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"&gt; &lt;ListView.GroupStyle&gt; &lt;GroupStyle&gt; &lt;GroupStyle.ContainerStyle&gt; &lt;Style TargetType="{x:Type GroupItem}"&gt; &lt;Setter Property="Margin" Value="0,0,0,5" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type GroupItem}"&gt; &lt;Expander IsExpanded="{Binding IsChecked, ElementName=chkExpandAll, Mode=OneWay}"&gt; &lt;Expander.Header&gt; &lt;DockPanel&gt; &lt;TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100" /&gt; &lt;TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}" /&gt; &lt;/DockPanel&gt; &lt;/Expander.Header&gt; &lt;Expander.Content&gt; &lt;ItemsPresenter /&gt; &lt;/Expander.Content&gt; &lt;/Expander&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/GroupStyle.ContainerStyle&gt; &lt;/GroupStyle&gt; &lt;/ListView.GroupStyle&gt; &lt;/ListView&gt; &lt;/ControlTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel&gt; &lt;CheckBox Name="chkExpandAll" IsChecked="True" Content="Expand All" /&gt; &lt;ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath="@Name" BorderThickness="1" Template="{StaticResource ListTemplate}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre>
[ { "answer_id": 227580, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 0, "selected": false, "text": "<p>It looks like the binding is broken since it's set to be OneWay with the checkbox, then if you click any of the expanders it will then break the binding. Setting it to be TwoWay will cause it to always work but expanding one item will cause them all to expand, which isn't very useful.</p>\n\n<p>I believe the solution to this will be to not use Bindings but instead to use Storyboards. You could fire a storyboard which will cause all of the expanders to be set to true/false, regardless of their current state. Updating the checkbox might be trickier though, since there is some logic required to see if all checkboxes or only some are checked.</p>\n" }, { "answer_id": 230107, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": true, "text": "<p>I found solution for the problem. What needs to be done is specify Mode=TwoWay and UpdateSourceTrigger=Explicit, so this way it is not breaking Binding and everything works fine. Bellow is an example of working code.</p>\n\n<pre><code>&lt;Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'\n xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'&gt;\n &lt;Window.Resources&gt;\n &lt;XmlDataProvider x:Key=\"MyData\" XPath=\"/Info\"&gt;\n &lt;x:XData&gt;\n &lt;Info xmlns=\"\"&gt;\n &lt;Item Name=\"Item 1\" Category=\"Cat1\" /&gt;\n &lt;Item Name=\"Item 2\" Category=\"Cat1\" /&gt;\n &lt;Item Name=\"Item 3\" Category=\"Cat2\" /&gt;\n &lt;Item Name=\"Item 4\" Category=\"Cat2\" /&gt;\n &lt;Item Name=\"Item 5\" Category=\"Cat2\" /&gt;\n &lt;Item Name=\"Item 6\" Category=\"Cat3\" /&gt;\n &lt;/Info&gt;\n &lt;/x:XData&gt;\n &lt;/XmlDataProvider&gt;\n\n &lt;CollectionViewSource x:Key='src' Source=\"{Binding Source={StaticResource MyData}, XPath=Item}\"&gt;\n &lt;CollectionViewSource.GroupDescriptions&gt;\n &lt;PropertyGroupDescription PropertyName=\"@Category\" /&gt;\n &lt;/CollectionViewSource.GroupDescriptions&gt;\n &lt;/CollectionViewSource&gt;\n\n &lt;ControlTemplate x:Key=\"ListTemplate\" TargetType=\"ListView\"&gt;\n &lt;ListView BorderThickness=\"0\"\n ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}'\n DisplayMemberPath=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}\"&gt;\n &lt;ListView.GroupStyle&gt;\n &lt;GroupStyle&gt;\n &lt;GroupStyle.ContainerStyle&gt;\n &lt;Style TargetType=\"{x:Type GroupItem}\"&gt;\n &lt;Setter Property=\"Margin\" Value=\"0,0,0,5\" /&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type GroupItem}\"&gt;\n &lt;StackPanel&gt;\n &lt;Expander Name=\"exp\" IsExpanded=\"{Binding IsChecked, ElementName=chkExpandAll, Mode=TwoWay, UpdateSourceTrigger=Explicit}\"&gt;\n &lt;Expander.Header&gt;\n &lt;DockPanel&gt;\n &lt;TextBlock FontWeight=\"Bold\" Text=\"{Binding Path=Name}\" Margin=\"5,0,0,0\" Width=\"100\" /&gt;\n &lt;TextBlock FontWeight=\"Bold\" Text=\"{Binding Path=ItemCount}\" /&gt;\n &lt;/DockPanel&gt;\n &lt;/Expander.Header&gt;\n &lt;Expander.Content&gt;\n &lt;ItemsPresenter /&gt;\n &lt;/Expander.Content&gt;\n &lt;/Expander&gt;\n &lt;/StackPanel&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;/Style&gt;\n &lt;/GroupStyle.ContainerStyle&gt;\n &lt;/GroupStyle&gt;\n &lt;/ListView.GroupStyle&gt;\n &lt;/ListView&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Window.Resources&gt;\n\n &lt;StackPanel&gt;\n &lt;CheckBox Name=\"chkExpandAll\" Content=\"Expand All\" /&gt;\n &lt;ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath=\"@Name\" BorderThickness=\"1\" Template=\"{StaticResource ListTemplate}\" /&gt;\n &lt;/StackPanel&gt;\n\n&lt;/Window&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30038/" ]
I have ListView with Grouping Items. Grouping uses custom GroupStyle (Expander). I would like to have check box which will Expand and collapse all groups when. It works fine untill I click manually on the group header and expand or collapse that group. After clicking that particular group stops to respond on check box selection. Looks like binding is broken after user manually clicks on the group. Please advise what I am doing wrong. Thanks a lot. Sincerely, Vlad. ``` <Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <Window.Resources> <XmlDataProvider x:Key="MyData" XPath="/Info"> <x:XData> <Info xmlns=""> <Item Name="Item 1" Category="Cat1" /> <Item Name="Item 2" Category="Cat1" /> <Item Name="Item 3" Category="Cat2" /> <Item Name="Item 4" Category="Cat2" /> <Item Name="Item 5" Category="Cat2" /> <Item Name="Item 6" Category="Cat3" /> </Info> </x:XData> </XmlDataProvider> <CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="@Category" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> <ControlTemplate x:Key="ListTemplate" TargetType="ListView"> <ListView BorderThickness="0" ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}' DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"> <ListView.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Margin" Value="0,0,0,5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Expander IsExpanded="{Binding IsChecked, ElementName=chkExpandAll, Mode=OneWay}"> <Expander.Header> <DockPanel> <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100" /> <TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}" /> </DockPanel> </Expander.Header> <Expander.Content> <ItemsPresenter /> </Expander.Content> </Expander> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </ListView.GroupStyle> </ListView> </ControlTemplate> </Window.Resources> <StackPanel> <CheckBox Name="chkExpandAll" IsChecked="True" Content="Expand All" /> <ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath="@Name" BorderThickness="1" Template="{StaticResource ListTemplate}" /> </StackPanel> </Window> ```
I found solution for the problem. What needs to be done is specify Mode=TwoWay and UpdateSourceTrigger=Explicit, so this way it is not breaking Binding and everything works fine. Bellow is an example of working code. ``` <Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <Window.Resources> <XmlDataProvider x:Key="MyData" XPath="/Info"> <x:XData> <Info xmlns=""> <Item Name="Item 1" Category="Cat1" /> <Item Name="Item 2" Category="Cat1" /> <Item Name="Item 3" Category="Cat2" /> <Item Name="Item 4" Category="Cat2" /> <Item Name="Item 5" Category="Cat2" /> <Item Name="Item 6" Category="Cat3" /> </Info> </x:XData> </XmlDataProvider> <CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="@Category" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> <ControlTemplate x:Key="ListTemplate" TargetType="ListView"> <ListView BorderThickness="0" ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}' DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"> <ListView.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Margin" Value="0,0,0,5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <StackPanel> <Expander Name="exp" IsExpanded="{Binding IsChecked, ElementName=chkExpandAll, Mode=TwoWay, UpdateSourceTrigger=Explicit}"> <Expander.Header> <DockPanel> <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100" /> <TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}" /> </DockPanel> </Expander.Header> <Expander.Content> <ItemsPresenter /> </Expander.Content> </Expander> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </ListView.GroupStyle> </ListView> </ControlTemplate> </Window.Resources> <StackPanel> <CheckBox Name="chkExpandAll" Content="Expand All" /> <ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath="@Name" BorderThickness="1" Template="{StaticResource ListTemplate}" /> </StackPanel> </Window> ```
227,083
<p>I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net? I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.</p>
[ { "answer_id": 227123, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 5, "selected": true, "text": "<p>\"Copying bytes of memory\" is something that .NET isn't particularly suited for (and VB.NET even less so). So, unless switching to C is an option for you, a function call is pretty much unavoidable for this.</p>\n\n<p>BitConverter is a well-thought-out, tested function. Of course, you can avoid it by doing something like (in C#):</p>\n\n<pre><code>myInt = (*pbyte) | (*(pbyte + 1) &lt;&lt; 8) | (*(pbyte + 2) &lt;&lt; 16) | (*(pbyte + 3) &lt;&lt; 24);\n</code></pre>\n\n<p>(which is, incidentally, <i>exactly</i> what BitConverter does for you when converting a byte array to an Integer...).</p>\n\n<p>However, this code:</p>\n\n<ul>\n<li>Is much, much harder to read and understand than the BitConverter equivalent;</li>\n<li>Doesn't do any of the error checking that BitConverter does for you;</li>\n<li>Doesn't differentiate between little-endian and big-endian representations, like BitConverter does.</li>\n</ul>\n\n<p>In other words: you might \"save\" a function call, but you will be significantly worse off in the end (even assuming you don't introduce any bugs). In general, the .NET Framework is very, very well designed, and you shouldn't think twice about using its functionality, unless you encounter actual (performance) issues with it.</p>\n" }, { "answer_id": 227166, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": "<p>mdb is exactly correct, but, here is some code to convert a vb byte array to little endian integer anyway...(just in case you wish to write your own bitconverter class)</p>\n\n<p>' where bits() is your byte array of length 4</p>\n\n<pre><code>Dim i as Integer \n\ni = (((bits(0) Or (bits(1) &lt;&lt; 8)) Or (bits(2) &lt;&lt; &amp;H10)) Or (bits(3) &lt;&lt; &amp;H18))\n</code></pre>\n" }, { "answer_id": 227177, "author": "Ihar Bury", "author_id": 18001, "author_profile": "https://Stackoverflow.com/users/18001", "pm_score": 1, "selected": false, "text": "<p>You can block copy byte[] to int[] using System.Buffer class.</p>\n" }, { "answer_id": 227253, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>I'm aware of BitConverter, but it\n seems like quite a waste to do a\n function call to do something that\n should be able to be done by copying 4\n bytes of memory.</p>\n</blockquote>\n\n<p>Whereas I view the situation as \"it seems quite a waste trying to hand-code an efficient way of doing this when there's already a method call which does exactly what I want.\"</p>\n\n<p>Unless you're <em>absolutely convinced</em> that you have a performance bottleneck in this exact piece of code, use the functionality provided by the framework.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net? I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.
"Copying bytes of memory" is something that .NET isn't particularly suited for (and VB.NET even less so). So, unless switching to C is an option for you, a function call is pretty much unavoidable for this. BitConverter is a well-thought-out, tested function. Of course, you can avoid it by doing something like (in C#): ``` myInt = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); ``` (which is, incidentally, *exactly* what BitConverter does for you when converting a byte array to an Integer...). However, this code: * Is much, much harder to read and understand than the BitConverter equivalent; * Doesn't do any of the error checking that BitConverter does for you; * Doesn't differentiate between little-endian and big-endian representations, like BitConverter does. In other words: you might "save" a function call, but you will be significantly worse off in the end (even assuming you don't introduce any bugs). In general, the .NET Framework is very, very well designed, and you shouldn't think twice about using its functionality, unless you encounter actual (performance) issues with it.
227,101
<p>I have somewhat of a staging server on the public internet running copies of the production code for a few websites. I'd really not like it if the staging sites get indexed. </p> <p>Is there a way I can modify my httpd.conf on the staging server to block search engine crawlers? </p> <p>Changing the robots.txt wouldn't really work since I use scripts to copy the same code base to both servers. Also, I would rather not change the virtual host conf files either as there is a bunch of sites and I don't want to have to remember to copy over a certain setting if I make a new site.</p>
[ { "answer_id": 227119, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"http://www.evolt.org/article/Using_Apache_to_stop_bad_robots/18/15126/\" rel=\"nofollow noreferrer\">Using Apache to stop bad robots</a>. You can get the <a href=\"http://www.user-agents.org/\" rel=\"nofollow noreferrer\">user agents</a> online or just allow browsers, rather than trying to block all bots.</p>\n" }, { "answer_id": 227128, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>Could you alias robots.txt on the staging virtualhosts to a restrictive robots.txt hosted in a different location?</p>\n" }, { "answer_id": 227138, "author": "Kevin", "author_id": 2678, "author_profile": "https://Stackoverflow.com/users/2678", "pm_score": 1, "selected": false, "text": "<p>Depending on your deployment scenario, you should look for ways to deploy different robots.txt files to dev/stage/test/prod (or whatever combination you have). Assuming you have different database config files or (or whatever's analogous) on the different servers, this should follow a similar process (you <em>do</em> have different passwords for your databases, right?)</p>\n\n<p>If you don't have a one-step deployment process in place, this is probably good motivation to get one... there are tons of tools out there for different environments - Capistrano is a pretty good one, and favored in the Rails/Django world, but is by no means the only one.</p>\n\n<p>Failing all that, you could probably set up a global Alias directive in your Apache config that would apply to all virtualhosts and point to a restrictive robots.txt</p>\n" }, { "answer_id": 227171, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 2, "selected": false, "text": "<p>To truly stop pages from being indexed, you'll need to hide the sites behind <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_auth.html\" rel=\"nofollow noreferrer\">HTTP auth</a>. You can do this in your global Apache config and use a simple .htpasswd file.</p>\n\n<p>Only downside to this is you now have to type in a username/password the first time you browse to any pages on the staging server.</p>\n" }, { "answer_id": 1278647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can use Apache's mod_rewrite to do it. Let's assume that your real host is www.example.com and your staging host is staging.example.com. Create a file called 'robots-staging.txt' and conditionally rewrite the request to go to that.</p>\n\n<p>This example would be suitable for protecting a single staging site, a bit of a simpler use case than what you are asking for, but this has worked reliably for me:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine on\n\n # Dissuade web spiders from crawling the staging site\n RewriteCond %{HTTP_HOST} ^staging\\.example\\.com$\n RewriteRule ^robots.txt$ robots-staging.txt [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>You could try to redirect the spiders to a master robots.txt on a different server, but \nsome of the spiders may balk after they get anything other than a \"200 OK\" or \"404 not found\" return code from the HTTP request, and they may not read the redirected URL.</p>\n\n<p>Here's how you would do that:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine on\n\n # Redirect web spiders to a robots.txt file elsewhere (possibly unreliable)\n RewriteRule ^robots.txt$ http://www.example.com/robots-staging.txt [R]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 7364999, "author": "jsdalton", "author_id": 99289, "author_profile": "https://Stackoverflow.com/users/99289", "pm_score": 6, "selected": true, "text": "<p>Create a robots.txt file with the following contents:</p>\n\n<pre><code>User-agent: *\nDisallow: /\n</code></pre>\n\n<p>Put that file somewhere on your staging server; your directory root is a great place for it (e.g. <code>/var/www/html/robots.txt</code>).</p>\n\n<p>Add the following to your httpd.conf file:</p>\n\n<pre><code># Exclude all robots\n&lt;Location \"/robots.txt\"&gt;\n SetHandler None\n&lt;/Location&gt;\nAlias /robots.txt /path/to/robots.txt\n</code></pre>\n\n<p>The <code>SetHandler</code> directive is probably not required, but it might be needed if you're using a handler like mod_python, for example.</p>\n\n<p>That robots.txt file will now be served for all virtual hosts on your server, overriding any robots.txt file you might have for individual hosts.</p>\n\n<p>(Note: My answer is essentially the same thing that ceejayoz's answer is suggesting you do, but I had to spend a few extra minutes figuring out all the specifics to get it to work. I decided to put this answer here for the sake of others who might stumble upon this question.)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24988/" ]
I have somewhat of a staging server on the public internet running copies of the production code for a few websites. I'd really not like it if the staging sites get indexed. Is there a way I can modify my httpd.conf on the staging server to block search engine crawlers? Changing the robots.txt wouldn't really work since I use scripts to copy the same code base to both servers. Also, I would rather not change the virtual host conf files either as there is a bunch of sites and I don't want to have to remember to copy over a certain setting if I make a new site.
Create a robots.txt file with the following contents: ``` User-agent: * Disallow: / ``` Put that file somewhere on your staging server; your directory root is a great place for it (e.g. `/var/www/html/robots.txt`). Add the following to your httpd.conf file: ``` # Exclude all robots <Location "/robots.txt"> SetHandler None </Location> Alias /robots.txt /path/to/robots.txt ``` The `SetHandler` directive is probably not required, but it might be needed if you're using a handler like mod\_python, for example. That robots.txt file will now be served for all virtual hosts on your server, overriding any robots.txt file you might have for individual hosts. (Note: My answer is essentially the same thing that ceejayoz's answer is suggesting you do, but I had to spend a few extra minutes figuring out all the specifics to get it to work. I decided to put this answer here for the sake of others who might stumble upon this question.)
227,121
<p>Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.</p> <pre><code>foreach(UserControl uc in plhMediaBuys.Controls) { uc.PulblicPropertyIWantAccessTo; } </code></pre>
[ { "answer_id": 227127, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 3, "selected": false, "text": "<pre><code>foreach(UserControl uc in plhMediaBuys.Controls)\n{\n if (uc is MySpecificType)\n {\n return (uc as MySpecificType).PulblicPropertyIWantAccessTo;\n }\n}\n</code></pre>\n" }, { "answer_id": 227133, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 4, "selected": true, "text": "<pre><code>foreach(UserControl uc in plhMediaBuys.Controls) {\n MyControl c = uc as MyControl;\n if (c != null) {\n c.PublicPropertyIWantAccessTo;\n }\n}\n</code></pre>\n" }, { "answer_id": 227139, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "<h2>Casting</h2>\n\n<p>I prefer to use:</p>\n\n<pre><code>foreach(UserControl uc in plhMediaBuys.Controls)\n{\n ParticularUCType myControl = uc as ParticularUCType;\n if (myControl != null)\n {\n // do stuff with myControl.PulblicPropertyIWantAccessTo;\n }\n}\n</code></pre>\n\n<p>Mainly because using the is keyword causes two (quasi-expensive) casts:</p>\n\n<pre><code>if( uc is ParticularUCType ) // one cast to test if it is the type\n{\n ParticularUCType myControl = (ParticularUCType)uc; // second cast\n ParticularUCType myControl = uc as ParticularUCType; // same deal this way\n // do stuff with myControl.PulblicPropertyIWantAccessTo;\n}\n</code></pre>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"http://rusek.org/stefan/default.aspx/2008/10/22/the-3-cast-operators-in-c/73/\" rel=\"nofollow noreferrer\">The 3 Cast Operators in C#</a></li>\n<li><a href=\"http://www.codeproject.com/KB/cs/csharpcasts.aspx\" rel=\"nofollow noreferrer\">Type Casting Impact over Execution Performance in C#</a></li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18785/" ]
Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties. ``` foreach(UserControl uc in plhMediaBuys.Controls) { uc.PulblicPropertyIWantAccessTo; } ```
``` foreach(UserControl uc in plhMediaBuys.Controls) { MyControl c = uc as MyControl; if (c != null) { c.PublicPropertyIWantAccessTo; } } ```
227,129
<p>I am trying to dynamically load the contents of a div tag with a .cfm page that contains a cfchart in png format. When the user clicks on a link, I am using the load function to put the .cfm page into the div.</p> <pre><code>$("#bank").bind("click", function(){ $("#chartx").load("bank.cfm"); }); </code></pre> <p>I can get this to come up perfectly in Firefox, but not in IE6. It gives no error messages.</p>
[ { "answer_id": 227178, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": 0, "selected": false, "text": "<p>Have you tried jQuery.get? Maybe something like:</p>\n\n<pre><code>$(\"#bank\").bind(\"click\", function(){\n $.get(\"bank.cfm\", function(data){\n $(\"#chartx\").html(data);\n });\n});\n</code></pre>\n\n<p>It's not as clean but it's more specific. Maybe it will take a different course from whatever is breaking.</p>\n" }, { "answer_id": 227465, "author": "Light", "author_id": 30485, "author_profile": "https://Stackoverflow.com/users/30485", "pm_score": 2, "selected": false, "text": "<p>Weirdest thing, but the cfdebug information in the classic style appended on the page is what causes it to break.</p>\n" }, { "answer_id": 319329, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Oh, so that's what it was. I was going to say that sometimes on some computers if you have IE security settings set too high, AJAX calls that load special components into the page sometimes don't work.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30485/" ]
I am trying to dynamically load the contents of a div tag with a .cfm page that contains a cfchart in png format. When the user clicks on a link, I am using the load function to put the .cfm page into the div. ``` $("#bank").bind("click", function(){ $("#chartx").load("bank.cfm"); }); ``` I can get this to come up perfectly in Firefox, but not in IE6. It gives no error messages.
Weirdest thing, but the cfdebug information in the classic style appended on the page is what causes it to break.
227,132
<p>Is it possible to use the asp templating engine (With the partial code-behind class, dynamic &lt;% ... %> blocks and such) to generate non HTML? I want to have a clean and maintainable way to generate code dynamically. (Specifically, I want to generate LaTeX code populated with values from a database.) </p> <p>Currently my LaTeX templates are resource strings with placeholders that I string.replace with the database values. This solution rapidly became very difficult to maintain and clean. I'd really like to use the dynamic blocks from aspx markup, but I'm not sure a) whether aspx will throw a fit when the output isn't HTML, or b) how to actually render the result into a .tex file.</p> <p>The generating code itself is located in a C# .dll. We're using .NET 3.5</p> <p>Is this possible? Thanks in advance. </p>
[ { "answer_id": 227154, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "<p>I don't see why not. Someone I knew at a former job created a database wrapper generator using ASP.NET pages and the repeater control to insert properties. He then wrote out the document contents to a source file.</p>\n\n<p>If you are worried about ASP.NET will throw a fit, you can just create a very limited test case and see for yourself. Shouldn't take much time to test a theory and let you know if it meets your needs.</p>\n" }, { "answer_id": 227169, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>It's certainly possible. Most server controls will be out, as they'll automatically emit HTML markup. But, you can databind the page and use databinding expressions. Visual Studio will no doubt complain about invalid markup.</p>\n\n<p>You then have to run your pages through Cassini or the ASP.NET pipeline to get the output. I've got a unit test harness somewhere that does that, and it's surprisingly easy.</p>\n\n<p>A <em>better</em> idea, though, would probably be to use a code generator. Something like CodeSmith should work nicely, or even Visual Studio's built in <a href=\"http://blog.wekeroad.com/blog/make-visual-studio-generate-your-repository/\" rel=\"nofollow noreferrer\">T4</a> gives you a lot of flexibility while not trying to tie you into HTML.</p>\n" }, { "answer_id": 227176, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 0, "selected": false, "text": "<p>For code generation you should take a look into the T4 templating features.\nIt uses a syntax similar to ASP.Net.</p>\n\n<p>See Scott Hanselmans Post:\n<a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx</a></p>\n" }, { "answer_id": 227179, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 0, "selected": false, "text": "<p>Yes you can. Just create a standard .aspx page, delete all the HTML and place whatever content you want in the page. Then you can use &lt;% %> tags to place dynamic content within the page. And like Jason Z said, you can use the Repeater control to iterate through collections of items to list out in the \"page\". Also, you wont be able to use all the other server controls since they generate HTML, but you can still create your own server control and/or user controls as necessary.</p>\n" }, { "answer_id": 227203, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 4, "selected": true, "text": "<p>The T4 templating that comes with Visual Studio 2008 natively or with Visual Studio 2005 SDK, you can pretty much generate anything you want.</p>\n<p>You can have more info on the following links:</p>\n<ul>\n<li><a href=\"https://www.hanselman.com/blog/t4-text-template-transformation-toolkit-code-generation-best-kept-visual-studio-secret\" rel=\"nofollow noreferrer\">Scott Hanselman's Blog</a></li>\n<li><a href=\"https://web.archive.org/web/20111101090855/http://blog.wekeroad.com:80/blog/make-visual-studio-generate-your-repository\" rel=\"nofollow noreferrer\">Rob Conery's Blog</a></li>\n<li><a href=\"http://olegsych.com/\" rel=\"nofollow noreferrer\">Oleg Sych's Blog</a> which is an entire repository of T4 examples</li>\n<li><a href=\"https://weblogs.asp.net/jdanforth/t4-support-in-vs2008\" rel=\"nofollow noreferrer\">Johan Danforth's Blog</a></li>\n</ul>\n<p>I'm pretty sure that all those links is a good start to your quest.</p>\n<p>If you want to generate T4 templates outside of Visual Studio, there is custom MSBuild task to invoke a T4 template (<a href=\"https://web.archive.org/web/20200803154046/http://geekswithblogs.net/EltonStoneman/archive/2008/07/25/an-msbuild-task-to-execute-t4-templates.aspx\" rel=\"nofollow noreferrer\">link</a>)</p>\n<p>Here is a sample of the &quot;Execute&quot; code of the MSBuild task. <a href=\"https://web.archive.org/web/20090313034538/http://www.sixeyed.com:80/fileDrop/code/MSBuild/Sixeyed.MSBuild/Sixeyed.MSBuild/Tasks/CodeGen/ExecuteT4Template.cs\" rel=\"nofollow noreferrer\">Click here for the source code</a>:</p>\n<pre><code>public override bool Execute()\n{\n bool success = false;\n\n //read in the template:\n string template = File.ReadAllText(this.TemplatePath);\n\n //replace tags with property and item group values:\n ProjectHelper helper = new ProjectHelper(this);\n template = helper.ResolveProjectItems(template);\n\n //copy the template to a temp file:\n this._tempFilePath = Path.GetTempFileName();\n File.WriteAllText(this._tempFilePath, template);\n\n //shell out to the exe:\n ProcessHelper.Run(this, TextTransform.ToolPath, TextTransform.ExeName, string.Format(TextTransform.ArgumentFormat, this.OutputPath, this._tempFilePath));\n success = true;\n\n return success;\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26626/" ]
Is it possible to use the asp templating engine (With the partial code-behind class, dynamic <% ... %> blocks and such) to generate non HTML? I want to have a clean and maintainable way to generate code dynamically. (Specifically, I want to generate LaTeX code populated with values from a database.) Currently my LaTeX templates are resource strings with placeholders that I string.replace with the database values. This solution rapidly became very difficult to maintain and clean. I'd really like to use the dynamic blocks from aspx markup, but I'm not sure a) whether aspx will throw a fit when the output isn't HTML, or b) how to actually render the result into a .tex file. The generating code itself is located in a C# .dll. We're using .NET 3.5 Is this possible? Thanks in advance.
The T4 templating that comes with Visual Studio 2008 natively or with Visual Studio 2005 SDK, you can pretty much generate anything you want. You can have more info on the following links: * [Scott Hanselman's Blog](https://www.hanselman.com/blog/t4-text-template-transformation-toolkit-code-generation-best-kept-visual-studio-secret) * [Rob Conery's Blog](https://web.archive.org/web/20111101090855/http://blog.wekeroad.com:80/blog/make-visual-studio-generate-your-repository) * [Oleg Sych's Blog](http://olegsych.com/) which is an entire repository of T4 examples * [Johan Danforth's Blog](https://weblogs.asp.net/jdanforth/t4-support-in-vs2008) I'm pretty sure that all those links is a good start to your quest. If you want to generate T4 templates outside of Visual Studio, there is custom MSBuild task to invoke a T4 template ([link](https://web.archive.org/web/20200803154046/http://geekswithblogs.net/EltonStoneman/archive/2008/07/25/an-msbuild-task-to-execute-t4-templates.aspx)) Here is a sample of the "Execute" code of the MSBuild task. [Click here for the source code](https://web.archive.org/web/20090313034538/http://www.sixeyed.com:80/fileDrop/code/MSBuild/Sixeyed.MSBuild/Sixeyed.MSBuild/Tasks/CodeGen/ExecuteT4Template.cs): ``` public override bool Execute() { bool success = false; //read in the template: string template = File.ReadAllText(this.TemplatePath); //replace tags with property and item group values: ProjectHelper helper = new ProjectHelper(this); template = helper.ResolveProjectItems(template); //copy the template to a temp file: this._tempFilePath = Path.GetTempFileName(); File.WriteAllText(this._tempFilePath, template); //shell out to the exe: ProcessHelper.Run(this, TextTransform.ToolPath, TextTransform.ExeName, string.Format(TextTransform.ArgumentFormat, this.OutputPath, this._tempFilePath)); success = true; return success; } ```
227,140
<p>I have need to write an application which uses a speech recognition engine -- either the built in vista one, or a third party one -- that can display a word or phrase, and recognise when the user reads it (or an approximation of it). I also need to be able to switch quickly between languages, without changing the language of the operating system.</p> <p>The users will be using the system for very short periods. The application needs to work without the requirement of first training the recognition engine to the users' voices.</p> <p>It would also be fantastic if this could work on Windows XP or lesser versions of Windows Vista.</p> <p>Optionally, the system needs to be able to read information on the screen back to the user, in the user's selected language. I can work around this specification using pre-recorded voice-overs, but the preferred method would be to use a text-to-speech engine.</p> <p>Can anyone recommend something for me?</p>
[ { "answer_id": 227162, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 3, "selected": false, "text": "<p>If the engine is what you're asking about then I've found (beware, I'm just listing, I haven't tried any of them):</p>\n\n<p><a href=\"http://www.lumenvox.com/products/speech_engine/\" rel=\"noreferrer\">Lumenvox engine</a></p>\n\n<p>you also have the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=5e86ec97-40a7-453f-b0ee-6583171b4530&amp;DisplayLang=en\" rel=\"noreferrer\">SAPI SDK</a> from Microsoft itself, I've only tried it for text to speech but according to its definition:</p>\n\n<p>The SDK also includes freely distributable text-to-speech (TTS) engines (in U.S. English and Simplified Chinese) <strong>and speech recognition (SR) engines</strong> (in U.S. English, Simplified Chinese, and Japanese).</p>\n" }, { "answer_id": 227168, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.nuance.com/for-developers/dragon/index.htm\" rel=\"nofollow noreferrer\">Dragon Naturally Speaking SDK</a> might be worth looking at.\n<a href=\"http://www.codeproject.com/KB/cs/TextToSpeechWindowsSAPI.aspx\" rel=\"nofollow noreferrer\">This project</a> looked interesting.</p>\n\n<p>Haven't got to play with either of them though.</p>\n" }, { "answer_id": 227184, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 1, "selected": false, "text": "<p>Check out the new Speech class libraries in .NET 3.5</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognizer.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognizer.aspx</a></p>\n</blockquote>\n\n<p>general documentation for SR and TTS</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx</a>\n <a href=\"http://msdn.microsoft.com/en-us/library/system.speech.synthesis.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.speech.synthesis.aspx</a></p>\n</blockquote>\n" }, { "answer_id": 227190, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>Text to speech is available with the <a href=\"http://msdn.microsoft.com/en-us/library/ms723627(VS.85).aspx\" rel=\"nofollow noreferrer\">Speech API</a>. Personally, I'd probably require Vista and use the managed interfaces to <a href=\"http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx\" rel=\"nofollow noreferrer\">System.Speech.SpeechRecognition</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.speech.synthesis.ttsengine.aspx\" rel=\"nofollow noreferrer\">System.Speech.Synthesis.TtsEngine</a>, but a P/Invoke should be possible into the unmanaged APIs if you really need XP support.</p>\n" }, { "answer_id": 227192, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 2, "selected": false, "text": "<p>Be warned that you're not going to get good results if you don't require training first. Speech recognition is a statistical application of phonetics, a field which is pretty frank about the fact that there's so much variation in the signal that it's almost a miracle anyone can understand what anyone else says. An off-the-shelf speech recognition engine will most likely tend towards a more general accent of English, but will fail miserably for anything even slightly different. </p>\n\n<p>That's why training is so important. We can do well by overfitting with ease, especially if we reduce the problem space. But creating an extensible machine learning solution? Therein always lies the rub.</p>\n\n<p>That being says, consider Sphinx-4. It's an off-the-shelf solution written in Java available at <a href=\"http://cmusphinx.sourceforge.net/sphinx4/\" rel=\"nofollow noreferrer\">http://cmusphinx.sourceforge.net/sphinx4/</a></p>\n" }, { "answer_id": 227217, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 6, "selected": false, "text": "<p>A similar question was asked on Joel on Software a while back. You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx\" rel=\"noreferrer\">System.Speech.Recognition</a> namespace to do this...with some limitations. Add System.Speech (should be in the GAC) to your project. Here's some sample code for a WinForms app:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n SpeechRecognizer rec = new SpeechRecognizer();\n\n public Form1()\n {\n InitializeComponent();\n rec.SpeechRecognized += rec_SpeechRecognized;\n }\n\n void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)\n {\n lblLetter.Text = e.Result.Text;\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n var c = new Choices();\n for (var i = 0; i &lt;= 100; i++)\n c.Add(i.ToString());\n var gb = new GrammarBuilder(c);\n var g = new Grammar(gb);\n rec.LoadGrammar(g);\n rec.Enabled = true;\n }\n</code></pre>\n\n<p>This recognizes the numbers from 1 to 100, and displays the resulting number on the form. You'll need a form with a label called lblLetter on it.</p>\n\n<p>System.Speech only works with a pre-defined list of words or phrases; it's not exactly NaturallySpeaking, either in versatility or in recognition quality. But you don't have to train it to the user's voice, and if you only have a few different things the user can say, it works reasonably well. And it's free! (if you have Visual Studio)</p>\n\n<p>It won't work well if you use very short phrases; I made a program for my kid to say letters of the alphabet and see them on-screen, but it doesn't do that well since many of the letters sound alike (especially from the mouth of a four-year-old).</p>\n\n<p>As for more flexible options...well, there's the aforementioned NaturallySpeaking, which has an SDK. But you have to contact sales to get any sort of access to it, and no pricing is listed, so it comes across as one of those \"How much does it cost? Well, how much have you got?\" kind of things. There doesn't seem to be a \"download and play around with it\" option. :(</p>\n\n<p>As for text-to-speech, <a href=\"http://msdn.microsoft.com/en-us/library/system.speech.synthesis.aspx\" rel=\"noreferrer\">System.Speech.Synthesis</a> does this. It's even easier than the speech recognition. I wrote a small program to let me type, hit Enter, and read the text aloud. My four-year-old gets mesmerized by it. :) (\"Daddy, I wanna tawk to da wobot.\")</p>\n" }, { "answer_id": 263528, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 4, "selected": false, "text": "<p>[Note: I was the development lead for the managed speech recognition API in .NET 3.0]</p>\n\n<p>System.Speech is part of .NET 3.0, so it is available on both Vista and XP. In Vista you have the added benefit of having a speech recognition engine pre-installed by the OS. On XP you choices are: use the SAPI 5.1 SDK with a very old engine (but might work well enough for your command and control scenario), install Office 2003 which installs a newer version of the recognizer. There are a few SAPI 5 complient speech recognition engines available as well.</p>\n\n<p>If you need to switch languages, you will want to use the System.Speech.Recognition.SpeechRecognitionEngine class which allows you to choose the SR engine for the language you need to support. Note that engines are defined by a set of languages they support (they might be using the same binary, only swapping data files to support additional languages).</p>\n\n<p>Comment if you need to know more.</p>\n\n<p>Philipp</p>\n" }, { "answer_id": 263558, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"http://www.microsoft.com/speech/speech2007/default.mspx\" rel=\"nofollow noreferrer\">Microsoft Speech Server</a>, which I think now is part of <a href=\"http://office.microsoft.com/en-us/communicationsserver/FX101729111033.aspx\" rel=\"nofollow noreferrer\">Office Communication Server 2007</a>. It contains a SR/TTS engines, C# API and tools that integrate with Visual Studio.</p>\n" }, { "answer_id": 316444, "author": "Rob Segal", "author_id": 7285, "author_profile": "https://Stackoverflow.com/users/7285", "pm_score": 3, "selected": false, "text": "<p>Before this add 'Speech' reference</p>\n\n<p><img src=\"https://i.stack.imgur.com/Xcf6X.jpg\" alt=\"System.Speech\"></p>\n\n<p>Found that the code example posted by Kyralessa on Oct 22nd didn't work for me but a slightly revised version did. When adding strings into the Choices object use full text English words not numbers. Seems the MS speech recognition engine can't recognize numbers by themselves.</p>\n\n<p>I have marked these modifications with some commenting added to the previous example.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n SpeechRecognizer rec = new SpeechRecognizer();\n\n public Form1()\n {\n InitializeComponent();\n rec.SpeechRecognized += rec_SpeechRecognized;\n }\n\n void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)\n {\n lblLetter.Text = e.Result.Text;\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n var c = new Choices();\n\n // Doens't work must use English words to add to Choices and\n // populate grammar.\n //\n //for (var i = 0; i &lt;= 100; i++)\n // c.Add(i.ToString());\n\n c.Add(\"one\");\n c.Add(\"two\");\n c.Add(\"three\");\n c.Add(\"four\");\n // etc...\n\n var gb = new GrammarBuilder(c);\n var g = new Grammar(gb);\n rec.LoadGrammar(g);\n rec.Enabled = true;\n }\n</code></pre>\n" }, { "answer_id": 3008719, "author": "Michael Levy", "author_id": 90236, "author_profile": "https://Stackoverflow.com/users/90236", "pm_score": 0, "selected": false, "text": "<p>This is the article from MSDN magazine that first discussed using the System.Speech APIs for Vista. Some of it is out of date because the API changed between beta (when the article was written) and the release of Vista, but this is still one of the best resources I've found and covers a good intro to the System.Speech namespace. See <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163663.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163663.aspx</a></p>\n" }, { "answer_id": 38470655, "author": "Fidel Orozco", "author_id": 1260174, "author_profile": "https://Stackoverflow.com/users/1260174", "pm_score": 0, "selected": false, "text": "<p>Well, this question already has many good responses but I think it is valuable to update with some info from 2016 documentation the responses from Rob Segal and Philipp Schmid pointing to this nice code example:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/office/system.speech.recognition.speechrecognitionengine.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/office/system.speech.recognition.speechrecognitionengine.aspx</a> </p>\n\n<p>It did not use the shared recognizer of Windows (The little Windows Mic that shows out up in the middle of the screen), it use a nice in app SpeechRecognitionEngine that not need any visual cue. The UI is completly at your control. </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6389/" ]
I have need to write an application which uses a speech recognition engine -- either the built in vista one, or a third party one -- that can display a word or phrase, and recognise when the user reads it (or an approximation of it). I also need to be able to switch quickly between languages, without changing the language of the operating system. The users will be using the system for very short periods. The application needs to work without the requirement of first training the recognition engine to the users' voices. It would also be fantastic if this could work on Windows XP or lesser versions of Windows Vista. Optionally, the system needs to be able to read information on the screen back to the user, in the user's selected language. I can work around this specification using pre-recorded voice-overs, but the preferred method would be to use a text-to-speech engine. Can anyone recommend something for me?
A similar question was asked on Joel on Software a while back. You can use the [System.Speech.Recognition](http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx) namespace to do this...with some limitations. Add System.Speech (should be in the GAC) to your project. Here's some sample code for a WinForms app: ``` public partial class Form1 : Form { SpeechRecognizer rec = new SpeechRecognizer(); public Form1() { InitializeComponent(); rec.SpeechRecognized += rec_SpeechRecognized; } void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { lblLetter.Text = e.Result.Text; } void Form1_Load(object sender, EventArgs e) { var c = new Choices(); for (var i = 0; i <= 100; i++) c.Add(i.ToString()); var gb = new GrammarBuilder(c); var g = new Grammar(gb); rec.LoadGrammar(g); rec.Enabled = true; } ``` This recognizes the numbers from 1 to 100, and displays the resulting number on the form. You'll need a form with a label called lblLetter on it. System.Speech only works with a pre-defined list of words or phrases; it's not exactly NaturallySpeaking, either in versatility or in recognition quality. But you don't have to train it to the user's voice, and if you only have a few different things the user can say, it works reasonably well. And it's free! (if you have Visual Studio) It won't work well if you use very short phrases; I made a program for my kid to say letters of the alphabet and see them on-screen, but it doesn't do that well since many of the letters sound alike (especially from the mouth of a four-year-old). As for more flexible options...well, there's the aforementioned NaturallySpeaking, which has an SDK. But you have to contact sales to get any sort of access to it, and no pricing is listed, so it comes across as one of those "How much does it cost? Well, how much have you got?" kind of things. There doesn't seem to be a "download and play around with it" option. :( As for text-to-speech, [System.Speech.Synthesis](http://msdn.microsoft.com/en-us/library/system.speech.synthesis.aspx) does this. It's even easier than the speech recognition. I wrote a small program to let me type, hit Enter, and read the text aloud. My four-year-old gets mesmerized by it. :) ("Daddy, I wanna tawk to da wobot.")
227,148
<p>I am a support engineer and our company's product allows XSLT transforms to customize outputs.</p> <p>I made a xsl transform for this purpose. It works well for source files of typical size (several 100k), but occasionally a really huge (10M) source file will come by. In such case, the output is not generated even if I let it grind several days.</p> <p>The SW engineering team tested it and discovered that for the transform and large source file in question is indeed very slow (>days), if our product is compiled to use the transform engine in .Net 1.1, but if they compile it with .Net 2.0, it is plenty fast (about 1-2 minutes).</p> <p>The long term solution obviously is, wait for the next release.</p> <p>For the short term I am wondering the following: 1) Is XSLT flexible enough that there are more efficient and less efficient ways to acheive the same result? For example, is it possible that the way I structured the xsl, the transform engine has to iterate from the beginning of the source file many many times, taking longer and longer as the next result piece gets farther and farther from the beginning? (Schlemiel the Painter), or 2) Is it more dependent on how the transform engine interprets the xsl?</p> <p>If 2 is the case, I don't want to waste a lot of time trying to improve the xsl (I am not a big xsl genius, it was hard enough for me to achieve what little I did...).</p> <p>Thanks!</p>
[ { "answer_id": 227197, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 3, "selected": false, "text": "<p>I'm not familiar with the .NET implementations, but there are a few things you can do in general to speed up processing of large documents:</p>\n\n<ul>\n<li>Avoid using \"//\" in Xpath expressions unless absolutely necessary.</li>\n<li>If you only need the first or only element that matches an Xpath expression, use the \"[1]\" qualifier, e.g. \"//iframe[1]\". Many processors implement optimizations for this.</li>\n<li>Whenever possible, when dealing with huge XML input, see if you can design a solution around a stream-based parser (like SAX) instead of a DOM-based parser.</li>\n</ul>\n" }, { "answer_id": 227454, "author": "trebormf", "author_id": 30454, "author_profile": "https://Stackoverflow.com/users/30454", "pm_score": 2, "selected": false, "text": "<p>Normally, if you see a non-linear increase in processing time vs. input size, you should suspect your code more than the framework. But since the problem goes away when the tool is compiled with .NET 2.0, all bets are off.</p>\n\n<p>With XSLT, it's hard to create a non-linear performance curve if you do all your parsing with straight template matches:</p>\n\n<pre><code>&lt;xsl:template match=\"foo\"&gt;\n &lt;!--OUTPUT--&gt;\n &lt;xsl:apply-templates / &gt;\n &lt;!--OUTPUT--&gt;\n&lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"bar\"&gt;\n &lt;!--OUTPUT--&gt;\n &lt;xsl:apply-templates / &gt;\n &lt;!--OUTPUT--&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p><strong>Pay careful attention to anywhere you might have resorted to <code>&lt;xsl:for-each&gt;</code></strong> for parsing; template matches are virtually always a better way to achieve the same result.</p>\n\n<p>One way to troubleshoot this performance problem is to recreate your XSLT one template-match at a time, testing the processing time after adding each match. You might start with this match:</p>\n\n<pre><code>&lt;xsl:template match=\"*\"&gt;\n &lt;xsl:copy&gt; &lt;!--Copy node --&gt;\n &lt;xsl:copy-of select=\"@*\"/&gt; &lt;!--Copy node attributes --&gt;\n &lt;xsl:apply-templates /&gt; &lt;!--Process children --&gt;\n &lt;/xsl:copy&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>This will match and copy every node, one at a time, to a new document. This should not exhibit a non-linear increase in processing time vs. input size (if it does, then the problem is not with your XSLT code).</p>\n\n<p>As you recreate your XSLT, if you add a template-match that suddenly kills performance, comment out every block inside the template. Then, uncomment one block at a time, testing the processing time each iteration, until you find the block that causes the problem.</p>\n" }, { "answer_id": 229275, "author": "Matt Large", "author_id": 2978, "author_profile": "https://Stackoverflow.com/users/2978", "pm_score": 2, "selected": false, "text": "<p>One thing world checking is if your XSLT does lookups into other parts of the XML document a lot, i.e. you are in one context node and lookup a value in another part of the document or even another document. If you are doing this it can hit performance quite hard and you should consider using <a href=\"http://www.zvon.org/xxl/XSLTreference/Output/xslt_key.html\" rel=\"nofollow noreferrer\">xsl:key</a> and the key function for this. It tells the processor to implement fast lookup index on the data in question.</p>\n\n<p>I was once building an XSLT that took 8 hours to run (with lots of cross references) and switching to use keys gave it a massive speed boost.</p>\n" }, { "answer_id": 229299, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 1, "selected": false, "text": "<p>Upon looking up your problem, I found a KB at Microsoft about that. You can see it <a href=\"http://support.microsoft.com/kb/324478\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>They say that the XSLT transform in .NET 1 has some issues with the performance and that they can offer a quick fix. </p>\n\n<p>If you want to try to troubleshoot the problem, there is a XSLT profiler available <a href=\"http://code.msdn.microsoft.com/xsltprofiler\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Otherwise, you can see what links is given on the Microsoft website for optimizing speed issues with XSLT (<a href=\"http://www.google.ca/search?q=XSLT+performance+site%3Amicrosoft.com\" rel=\"nofollow noreferrer\">link</a>).</p>\n" }, { "answer_id": 279497, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>To detect when to start a new section, I did this:</p>\n\n<pre><code>&lt;xsl:if test=\"@TheFirstCol&gt;preceding-sibling::*[1]/@TheFirstCol\"\n</code></pre>\n \n <p>Could this be causing a lot or re-iteration?</p>\n</blockquote>\n\n<p>Definitely. The algorithm you've chosen is O(N<sup>2</sup>) and would be very slow with sufficient number of siblings, regardless of the implementation language.</p>\n\n<p>Here is an efficient algorithm using keys:</p>\n\n<h1>Solution1:</h1>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n &lt;xsl:output method=\"text\"/&gt;\n\n &lt;xsl:key name=\"kC1Value\" match=\"@c1\" use=\".\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:for-each select=\"*/x[generate-id(@c1) = generate-id(key('kC1Value',@c1)[1])]\"&gt;\n\n &lt;xsl:value-of select=\"concat('&amp;#xA;',@c1)\"/&gt;\n\n &lt;xsl:for-each select=\"key('kC1Value',@c1)\"&gt;\n &lt;xsl:value-of select=\"'&amp;#xA;'\"/&gt;\n &lt;xsl:for-each select=\"../@*[not(name()='c1')]\"&gt;\n &lt;xsl:value-of select=\"concat(' ', .)\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>Unfortunately, XslTransform (.Net 1.1) has a notoriously inefficient implementation of the <code>generate-id()</code> function.</p>\n\n<p>The following may be faster with XslTransform:</p>\n\n<h1>Solution2:</h1>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n &lt;xsl:output method=\"text\"/&gt;\n\n &lt;xsl:key name=\"kC1Value\" match=\"@c1\" use=\".\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:for-each select=\"*/x[count(@c1 | key('kC1Value',@c1)[1]) = 1]\"&gt;\n\n &lt;xsl:value-of select=\"concat('&amp;#xA;',@c1)\"/&gt;\n\n &lt;xsl:for-each select=\"key('kC1Value',@c1)\"&gt;\n &lt;xsl:value-of select=\"'&amp;#xA;'\"/&gt;\n &lt;xsl:for-each select=\"../@*[not(name()='c1')]\"&gt;\n &lt;xsl:value-of select=\"concat(' ', .)\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>When applied on the following small XML document:</p>\n\n<pre><code>&lt;t&gt;\n &lt;x c1=\"1\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"1\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"1\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"1\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"2\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"2\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"2\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"2\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"3\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"4\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"4\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"4\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"4\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"5\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"6\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"7\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"7\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"7\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"7\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"8\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"8\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"8\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/&gt;\n &lt;x c1=\"8\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/&gt;\n&lt;/t&gt;\n</code></pre>\n\n<p>both solutions produced the wanted result:</p>\n\n<pre><code>1\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n2\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n3\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n4\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n5\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n6\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n7\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n8\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n</code></pre>\n\n<p>From the above small XML file I generated a 10MB XML file by copying every element 6250 times (using another XSLT transformation :) ).</p>\n\n<p>With the 10MB xml file and with XslCompiledTransform (.Net 2.0 + ) the two solutions had the following transformation times:</p>\n\n<blockquote>\n <p>Solution1: 3.3sec.<br>\n Solution2: 2.8sec.</p>\n</blockquote>\n\n<p>With XslTransform (.Net 1.1) Solution2 ran for 1622sec.; that is about 27 minutes.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24233/" ]
I am a support engineer and our company's product allows XSLT transforms to customize outputs. I made a xsl transform for this purpose. It works well for source files of typical size (several 100k), but occasionally a really huge (10M) source file will come by. In such case, the output is not generated even if I let it grind several days. The SW engineering team tested it and discovered that for the transform and large source file in question is indeed very slow (>days), if our product is compiled to use the transform engine in .Net 1.1, but if they compile it with .Net 2.0, it is plenty fast (about 1-2 minutes). The long term solution obviously is, wait for the next release. For the short term I am wondering the following: 1) Is XSLT flexible enough that there are more efficient and less efficient ways to acheive the same result? For example, is it possible that the way I structured the xsl, the transform engine has to iterate from the beginning of the source file many many times, taking longer and longer as the next result piece gets farther and farther from the beginning? (Schlemiel the Painter), or 2) Is it more dependent on how the transform engine interprets the xsl? If 2 is the case, I don't want to waste a lot of time trying to improve the xsl (I am not a big xsl genius, it was hard enough for me to achieve what little I did...). Thanks!
> > To detect when to start a new section, I did this: > > > > ``` > <xsl:if test="@TheFirstCol>preceding-sibling::*[1]/@TheFirstCol" > > ``` > > Could this be causing a lot or re-iteration? > > > Definitely. The algorithm you've chosen is O(N2) and would be very slow with sufficient number of siblings, regardless of the implementation language. Here is an efficient algorithm using keys: Solution1: ========== ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:key name="kC1Value" match="@c1" use="."/> <xsl:template match="/"> <xsl:for-each select="*/x[generate-id(@c1) = generate-id(key('kC1Value',@c1)[1])]"> <xsl:value-of select="concat('&#xA;',@c1)"/> <xsl:for-each select="key('kC1Value',@c1)"> <xsl:value-of select="'&#xA;'"/> <xsl:for-each select="../@*[not(name()='c1')]"> <xsl:value-of select="concat(' ', .)"/> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` Unfortunately, XslTransform (.Net 1.1) has a notoriously inefficient implementation of the `generate-id()` function. The following may be faster with XslTransform: Solution2: ========== ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:key name="kC1Value" match="@c1" use="."/> <xsl:template match="/"> <xsl:for-each select="*/x[count(@c1 | key('kC1Value',@c1)[1]) = 1]"> <xsl:value-of select="concat('&#xA;',@c1)"/> <xsl:for-each select="key('kC1Value',@c1)"> <xsl:value-of select="'&#xA;'"/> <xsl:for-each select="../@*[not(name()='c1')]"> <xsl:value-of select="concat(' ', .)"/> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` When applied on the following small XML document: ``` <t> <x c1="1" c2="0" c3="0" c4="0" c5="0"/> <x c1="1" c2="0" c3="1" c4="0" c5="0"/> <x c1="1" c2="2" c3="0" c4="0" c5="0"/> <x c1="1" c2="1" c3="1" c4="0" c5="0"/> <x c1="2" c2="0" c3="0" c4="0" c5="0"/> <x c1="2" c2="0" c3="1" c4="0" c5="0"/> <x c1="2" c2="2" c3="0" c4="0" c5="0"/> <x c1="2" c2="1" c3="1" c4="0" c5="0"/> <x c1="3" c2="0" c3="0" c4="0" c5="0"/> <x c1="3" c2="0" c3="1" c4="0" c5="0"/> <x c1="3" c2="2" c3="0" c4="0" c5="0"/> <x c1="3" c2="1" c3="1" c4="0" c5="0"/> <x c1="3" c2="0" c3="0" c4="0" c5="0"/> <x c1="3" c2="0" c3="1" c4="0" c5="0"/> <x c1="3" c2="2" c3="0" c4="0" c5="0"/> <x c1="3" c2="1" c3="1" c4="0" c5="0"/> <x c1="4" c2="0" c3="0" c4="0" c5="0"/> <x c1="4" c2="0" c3="1" c4="0" c5="0"/> <x c1="4" c2="2" c3="0" c4="0" c5="0"/> <x c1="4" c2="1" c3="1" c4="0" c5="0"/> <x c1="5" c2="0" c3="0" c4="0" c5="0"/> <x c1="5" c2="0" c3="1" c4="0" c5="0"/> <x c1="5" c2="2" c3="0" c4="0" c5="0"/> <x c1="5" c2="1" c3="1" c4="0" c5="0"/> <x c1="5" c2="0" c3="0" c4="0" c5="0"/> <x c1="5" c2="0" c3="1" c4="0" c5="0"/> <x c1="6" c2="2" c3="0" c4="0" c5="0"/> <x c1="6" c2="1" c3="1" c4="0" c5="0"/> <x c1="6" c2="0" c3="0" c4="0" c5="0"/> <x c1="6" c2="0" c3="1" c4="0" c5="0"/> <x c1="6" c2="2" c3="0" c4="0" c5="0"/> <x c1="6" c2="1" c3="1" c4="0" c5="0"/> <x c1="7" c2="0" c3="0" c4="0" c5="0"/> <x c1="7" c2="0" c3="1" c4="0" c5="0"/> <x c1="7" c2="2" c3="0" c4="0" c5="0"/> <x c1="7" c2="1" c3="1" c4="0" c5="0"/> <x c1="8" c2="0" c3="0" c4="0" c5="0"/> <x c1="8" c2="0" c3="1" c4="0" c5="0"/> <x c1="8" c2="2" c3="0" c4="0" c5="0"/> <x c1="8" c2="1" c3="1" c4="0" c5="0"/> </t> ``` both solutions produced the wanted result: ``` 1 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 2 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 3 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 4 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 5 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 6 2 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 7 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 8 0 0 0 0 0 1 0 0 2 0 0 0 1 1 0 0 ``` From the above small XML file I generated a 10MB XML file by copying every element 6250 times (using another XSLT transformation :) ). With the 10MB xml file and with XslCompiledTransform (.Net 2.0 + ) the two solutions had the following transformation times: > > Solution1: 3.3sec. > > Solution2: 2.8sec. > > > With XslTransform (.Net 1.1) Solution2 ran for 1622sec.; that is about 27 minutes.
227,187
<p>I have a console application that require to use some code that need administrator level. I have read that I need to add a Manifest file myprogram.exe.manifest that look like that :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;assembly xmlns=&quot;urn:schemas-microsoft-com:asm.v1&quot; manifestVersion=&quot;1.0&quot;&gt; &lt;trustInfo xmlns=&quot;urn:schemas-microsoft-com:asm.v3&quot;&gt; &lt;security&gt; &lt;requestedPrivileges&gt; &lt;requestedExecutionLevel level=&quot;requireAdministrator&quot;&gt; &lt;/requestedPrivileges&gt; &lt;/security&gt; &lt;/trustInfo&gt; &lt;/assembly&gt; </code></pre> <p>But it still doesn't raise the UAC (in the console or in debugging in VS). How can I solve this issue?</p> <h2>Update</h2> <p>I am able to make it work if I run the solution in Administrator or when I run the /bin/*.exe in Administrator. I am still wondering if it's possible to have something that will pop when the application start instead of explicitly right click&gt;Run as Administrator?</p>
[ { "answer_id": 259146, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 4, "selected": true, "text": "<p>You need to embed the UAC manifest as an embedded Win32 resource. See <a href=\"http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx\" rel=\"noreferrer\">Adding a UAC Manifest to Managed Code</a>.</p>\n\n<p>In short, you use a Windows SDK command line tool to embed it into your executable.</p>\n\n<p>You can automate this as a post-build step by placing the following line as a post build task in your VS project's properties:</p>\n\n<pre><code>mt.exe -manifest \"$(ProjectDir)$(TargetName).exe.manifest\" -updateresource:\"$(TargetDir)$(TargetName).exe;#1\"\n</code></pre>\n" }, { "answer_id": 2188255, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 6, "selected": false, "text": "<p>For anyone using Visual Studio, it's super easy. I was about to go set up the Windows SDK and do mt.exe post-build steps and all that before realizing it's built into VS. I figured I'd record it for posterity.</p>\n\n<ol>\n<li>Project | Add New Item -> Visual C# Items -> Application Manifest File</li>\n<li>Open app.manifest, change requestedExecutionLevel.@level to \"requireAdministrator\"</li>\n<li>Build</li>\n</ol>\n\n<p>Ta-da</p>\n" }, { "answer_id": 2679654, "author": "Joe Daley", "author_id": 31563, "author_profile": "https://Stackoverflow.com/users/31563", "pm_score": 5, "selected": false, "text": "<p>Scott's answer will do what you asked, but Microsoft recommends that console applications display an \"access denied\" message rather than prompt for elevation.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/bb756922.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/bb756922.aspx</a>:</p>\n\n<blockquote>\n <p>A console application presents its output on the console window and not\n with a separate user interface. If an application needs a full administrator\n access token to run, then that application needs to be launched from\n an elevated console window.</p>\n \n <p>You must do the following for console applications:</p>\n \n <ol>\n <li><p>Mark that your application “asInvoker”: You can do this by authoring the manifest of your application in which you set RequestedExecutionLevel == asInvoker. This setup allows callers from non-elevated contexts to create your process, which allows them to proceed to step 2.</p></li>\n <li><p>Provide an error message if application is run without a full administrator access token: If the application is launched in a non-elevated console, your application should give a brief message and exit. The recommended message is: \"Access Denied. Administrator permissions are needed to use the selected options. Use an administrator command prompt to complete these tasks.\"</p></li>\n </ol>\n \n <p>The application should also return the error code ERROR_ELEVATION_REQUIRED upon failure to launch to facilitate scripting.</p>\n</blockquote>\n\n<p>My C# code for this is below. It is tested on Windows XP (administrator -> ok, standard user -> denied) and Windows Server 2008 (elevated administrator -> ok, non-elevated administrator -> denied, standard user -> denied).</p>\n\n<pre><code>static int Main(string[] args)\n{\n if (!HasAdministratorPrivileges())\n {\n Console.Error.WriteLine(\"Access Denied. Administrator permissions are \" +\n \"needed to use the selected options. Use an administrator command \" +\n \"prompt to complete these tasks.\");\n return 740; // ERROR_ELEVATION_REQUIRED\n }\n\n ...\n return 0;\n}\n\nprivate static bool HasAdministratorPrivileges()\n{\n WindowsIdentity id = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(id);\n return principal.IsInRole(WindowsBuiltInRole.Administrator);\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I have a console application that require to use some code that need administrator level. I have read that I need to add a Manifest file myprogram.exe.manifest that look like that : ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="requireAdministrator"> </requestedPrivileges> </security> </trustInfo> </assembly> ``` But it still doesn't raise the UAC (in the console or in debugging in VS). How can I solve this issue? Update ------ I am able to make it work if I run the solution in Administrator or when I run the /bin/\*.exe in Administrator. I am still wondering if it's possible to have something that will pop when the application start instead of explicitly right click>Run as Administrator?
You need to embed the UAC manifest as an embedded Win32 resource. See [Adding a UAC Manifest to Managed Code](http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx). In short, you use a Windows SDK command line tool to embed it into your executable. You can automate this as a post-build step by placing the following line as a post build task in your VS project's properties: ``` mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1" ```
227,208
<p>I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this?</p> <p>I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins. </p> <p>The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.</p>
[ { "answer_id": 227754, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 4, "selected": false, "text": "<p>I'm assuming you need this to work only in browsers that support SVG.</p>\n\n<p>Firefox, Safari, and Opera provide the non-standard <code>XMLSerializer</code> API, so you could do something like this:</p>\n\n<pre><code>var svg = document.getElementById('svg_root'); // or whatever you call it\nvar serializer = new XMLSerializer();\nvar str = serializer.serializeToString(svg);\n</code></pre>\n\n<p>From there, you can send it to the server and receive a PNG in return.</p>\n\n<p>Here's <a href=\"https://developer.mozilla.org/en/Parsing_and_serializing_XML\" rel=\"noreferrer\">Mozilla's developer page on serializing XML from the DOM</a>.</p>\n" }, { "answer_id": 237990, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "<p>Opera has implementation of <a href=\"http://www.w3.org/TR/DOM-Level-3-LS/load-save.html\" rel=\"nofollow noreferrer\">W3C's DOM→XML serializer</a>. In XML mode <code>innerHTML</code> returns well-formed XML in Gecko.</p>\n\n<p>HTML5 <code>&lt;canvas&gt;</code> can export its content as PNG file using <code>toDataURL()</code> and it's possible to paint any <code>&lt;img&gt;</code> element on canvas using <code>drawImage()</code>, so it should be possible to create <code>&lt;img src=\"data:application/svg+xml,…\"&gt;</code>, paint it on canvas and export as <code>data:</code> URL.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30238/" ]
I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this? I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins. The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.
I'm assuming you need this to work only in browsers that support SVG. Firefox, Safari, and Opera provide the non-standard `XMLSerializer` API, so you could do something like this: ``` var svg = document.getElementById('svg_root'); // or whatever you call it var serializer = new XMLSerializer(); var str = serializer.serializeToString(svg); ``` From there, you can send it to the server and receive a PNG in return. Here's [Mozilla's developer page on serializing XML from the DOM](https://developer.mozilla.org/en/Parsing_and_serializing_XML).
227,210
<p>I've spent most of the day making what are basically some housekeeping changes to the codebase of one of our projects (replacing all <code>System.out.println()</code> calls with log4j).</p> <p>I'm kind of curious how many lines of code I've updated with this set of changes.</p> <p>Is there anyway with <code>cvs diff</code> or another command to get an accurate count of how many lines have changed?</p> <p>I've tried</p> <pre><code>cvs diff -b -B -R </code></pre> <p>to get all of the changes in the working directory (and recursively the subdirectories), but for each file changed it also prints out file/version information, which makes just counting the lines of output useless.</p> <p>Any ideas?</p>
[ { "answer_id": 227251, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 2, "selected": false, "text": "<p>You can simply pipe output of cvs diff to diffstat.</p>\n" }, { "answer_id": 227296, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>What about verify that you've changed all instances with something like:</p>\n\n<pre><code>find . | egrep -v -e '(CVS|&lt;other patterns you don't want&gt;)' | \\\n xargs egrep -e 'System\\.out\\.println[(][)]' | wc -l\n</code></pre>\n\n<p>that should give you zero.</p>\n\n<p>Then replacing the regex in the second egrep with 'log4j' should have wc -l returning the number of lines you've changed.</p>\n\n<p>HTH.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n" }, { "answer_id": 227316, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 3, "selected": true, "text": "<p>Filter out extra lines from the diff output and then count the lines.</p>\n\n<p>For example, grep only lines starting with &lt; or ></p>\n\n<pre><code>cvs diff -b -B -R | egrep '^&lt;|&gt;' | wc -l\n</code></pre>\n" }, { "answer_id": 274623, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://invisible-island.net/diffstat/\" rel=\"noreferrer\">diffstat</a> utility is a nice tool for getting some simple metrics from the output of cvs, svn or other diffs.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I've spent most of the day making what are basically some housekeeping changes to the codebase of one of our projects (replacing all `System.out.println()` calls with log4j). I'm kind of curious how many lines of code I've updated with this set of changes. Is there anyway with `cvs diff` or another command to get an accurate count of how many lines have changed? I've tried ``` cvs diff -b -B -R ``` to get all of the changes in the working directory (and recursively the subdirectories), but for each file changed it also prints out file/version information, which makes just counting the lines of output useless. Any ideas?
Filter out extra lines from the diff output and then count the lines. For example, grep only lines starting with < or > ``` cvs diff -b -B -R | egrep '^<|>' | wc -l ```
227,215
<p>What's the best performing way to convert a DataRowCollection instance to a DataRow[]?</p>
[ { "answer_id": 227269, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": "<p>This is kind of obvious, but:</p>\n\n<p><code>DataRowCollection.CopyTo(DataRow[] array, Int32 offset)</code> ?</p>\n\n<p>It seems like no matter what, you're going to have to iterate the collection (CopyTo iterates the internal DataRowTree elements).</p>\n\n<p>I suppose you could use reflection to access the non-public tree, but at a significant cost.</p>\n" }, { "answer_id": 227273, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 7, "selected": false, "text": "<pre><code>DataRow[] rows = dt.Select();\n</code></pre>\n\n<p>Assuming you still have access to the datatable.</p>\n" }, { "answer_id": 10282474, "author": "Nordin", "author_id": 29669, "author_profile": "https://Stackoverflow.com/users/29669", "pm_score": 4, "selected": false, "text": "<p>For the sake of completeness, this is another way (with Linq), and it <em>preserve the row ordering</em>:</p>\n\n<pre><code>DataRow[] rows = dt.Rows.Cast&lt;DataRow&gt;().ToArray()\n</code></pre>\n" }, { "answer_id": 25531600, "author": "Deilan", "author_id": 3095779, "author_profile": "https://Stackoverflow.com/users/3095779", "pm_score": 3, "selected": false, "text": "<p>If you have not access to the containing table, you may use the extension method:</p>\n\n<pre><code>public static class DataRowCollectionExtensions\n{\n public static IEnumerable&lt;DataRow&gt; AsEnumerable(this DataRowCollection source)\n {\n return source.Cast&lt;DataRow&gt;();\n }\n}\n</code></pre>\n\n<p>And thereafter:</p>\n\n<pre><code>DataRow[] dataRows = dataRowCollection.AsEnumerable().ToArray();\n</code></pre>\n\n<p>But if you have access to the containing table, it's better to access rows using <code>DataTable</code>'s <code>AsEnumerable</code> extension method (<a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable(v=vs.110).aspx\" rel=\"nofollow\">Description</a>, <a href=\"http://referencesource.microsoft.com/System.Data.DataSetExtensions/a.html#234b3444d2a5ff75\" rel=\"nofollow\">Source</a>):</p>\n\n<pre><code>DataRow[] dataRows = dataTable.AsEnumerable().ToArray();\n</code></pre>\n\n<p>Either way you may use <code>DataTable</code>'s <code>Select</code> method with several overloads (<a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.select(v=vs.110).aspx\" rel=\"nofollow\">Description</a>, <a href=\"http://referencesource.microsoft.com/System.Data/R/d57c1612e35a7f9a.html\" rel=\"nofollow\">Source</a>):</p>\n\n<pre><code>DataRow[] dataRows = dataTable.Select();\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What's the best performing way to convert a DataRowCollection instance to a DataRow[]?
``` DataRow[] rows = dt.Select(); ``` Assuming you still have access to the datatable.
227,225
<p>So like most new .NET developers you start of passing DataSets everywhere and although things do the job it doesn't seem right. </p> <p>The next progression is usually to create entity objects that extend a DAL base class so you have i.e. </p> <pre><code>public class User : UserDAL { //User specific methods } public class UserDAL { //Bunch of user specific properties public User Load(int Id) { //Some low level ADO calls } private User LoadFromDataSet(DataSet ds) { //Load entity properties from DataSet } } </code></pre> <p>User extends UserDAL objects that has low level data access calls using ADO.NET. </p> <p>From here you go on to learn that this implementation means your tied to a data access layer and you make use of a separate entity, data access object and DAO interface for mocking or to easily swap out the DAO if need be. i.e.</p> <pre><code>public UserDAO : IUserDAO { //Data access Functions } </code></pre> <p>With use of generics and reflection or a good ORM you can relieve some of the more common data access CRUD operations i.e.</p> <pre><code>Public UserDAO&lt;User&gt; : BaseDAO&lt;User&gt;, IUserDAO { //BaseDAO deals with basic crud so more custom data access methods can go here } </code></pre> <p>So basically that's where I am currently at, aside from some other nice practices like using IoC to resolve the specific IUserDAO I want. But while I see the advantage to this structure I am also left feeling like I miss the old User.Load(1) method calls. </p> <p>What I was wondering is would it be such a bad thing to inject my IUserDAO into the User entity and have that take care of the basic CRUD operations? </p> <p>My understanding is that as a POCO the User entity would have no problems been passed over the wire and adding methods like Save(), Load() etc would have no relavence in the sense of a data transfer object. </p> <p>But with that said my entities usually have lazy loaded collections which mean nothing in a DTO sense. Also, with WFP I believe can pick and chose which properties I want serializing, or at very least I could create a new UserDTO when I need to send it across the wire. </p> <p>So basically, aside from that issue what are the other problems with making my User entity include DataAccess related methods? Also could someone clarify whether what I am talking about is referred to as an active record pattern or is this something else?</p> <p>EDIT: </p> <p>cristianlibardo noted:</p> <blockquote> <p>As for potential drawbacks there is greater coupling to peristence code, resitence when following/updating associations, testability and querying.</p> </blockquote> <p>There would be a greater some level of coupling but what I was thinking was somehting like the following:</p> <pre><code>public class User { IUserDAO userDAO; public User() { userDAO = IoCContainer.Resolve&lt;IUserDAO&gt;; } public User(IUserDAO userDAO) { this.userDAO = userDAO; } //DAL methods } </code></pre> <p>So the coupling should be minimal and as for testability, I don't see it as a problem as I can just inject a mock DAO into the entity. </p> <p>Thanks to Brian Hasden, these are really good resources, but I guess I just wanted justification for something I was obviously going to do. Thanks for giving the said justification. </p>
[ { "answer_id": 227256, "author": "Brian Hasden", "author_id": 28926, "author_profile": "https://Stackoverflow.com/users/28926", "pm_score": 2, "selected": true, "text": "<p>I came to the same conclusion. The load usually doesn't make sense in the entity because once you have an instance, you're either creating a new entity or you've already got a loaded entity. I've been using entities with Save (create and update) and Delete for years now without any issues. That being said, it's usually useful to still have a DAO to do other things, so you're not exactly combining the DAO and the entity. Most of the time for my entities the Save and Delete methods are just calling into the DAO Save and Delete methods.</p>\n\n<p>BTW, I usually combine a dirty flag with the entity to know when properties have been changed so that you don't make unnecessary calls to save when the entity hasn't changed.</p>\n\n<p>Typically, entities that don't really do anything but contain getters and setters for private members mean you're working with an anemic domain model. It's an anti-pattern that's fairly controversial.</p>\n\n<p>You can find more information about it at:</p>\n\n<p><a href=\"http://www.martinfowler.com/bliki/AnemicDomainModel.html\" rel=\"nofollow noreferrer\">http://www.martinfowler.com/bliki/AnemicDomainModel.html</a>\n<a href=\"http://wrschneider.blogspot.com/2005/01/avoiding-anemic-domain-models-with.html\" rel=\"nofollow noreferrer\">http://wrschneider.blogspot.com/2005/01/avoiding-anemic-domain-models-with.html</a>\n<a href=\"http://www.dotnetjunkies.com/WebLog/richardslade/archive/2007/03/07/209401.aspx\" rel=\"nofollow noreferrer\">http://www.dotnetjunkies.com/WebLog/richardslade/archive/2007/03/07/209401.aspx</a></p>\n" }, { "answer_id": 227289, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 1, "selected": false, "text": "<p>Yes, what you're describing sounds just like active record (a database row made into an object with the logic to persist itself from/to the database). It's an effective technique, no doubt.</p>\n\n<p>As for potential drawbacks there is greater coupling to peristence code, resitence when following/updating associations, testability and querying.</p>\n" }, { "answer_id": 228161, "author": "jonsequitur", "author_id": 23316, "author_profile": "https://Stackoverflow.com/users/23316", "pm_score": 0, "selected": false, "text": "<p>Keeping persistence out of your domain classes' inheritance models largely serves the goal of writing understandable and maintainable code.</p>\n\n<p>Persistence is an orthogonal concern to what your class's real responsibilities are. I've noticed that the inherit-from-DAO approach arbitrarily divides the world into two categories of classes that, from the point of view of responsibilities and behaviors, are no different. Which side a class falls on will often change over time. You don't want that change to impact that class's API and interactions with other classes.</p>\n\n<p>Example: Say that today, your Product class makes use of an IPriceCalculator, retrieved via IoC. Tomorrow, you decide you need to allow modification of the algorithms per-product, so your IPriceCalculator becomes data-driven. This could be a painful change, especially if your price calculators already had a base class supplying important functionality.</p>\n\n<p>This example highlights another consideration: inheriting from a DAO class means your User class just lost the ability to inherit a Person class that may have useful behaviors. (In the .NET world, MarshalByRefObject is a common base class that people need to inherit which can conflict with inheritance-based DAO requirements.) With single inheritance, it's not ideal to inherit in order to gain functionality that's probably a separate concern.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425/" ]
So like most new .NET developers you start of passing DataSets everywhere and although things do the job it doesn't seem right. The next progression is usually to create entity objects that extend a DAL base class so you have i.e. ``` public class User : UserDAL { //User specific methods } public class UserDAL { //Bunch of user specific properties public User Load(int Id) { //Some low level ADO calls } private User LoadFromDataSet(DataSet ds) { //Load entity properties from DataSet } } ``` User extends UserDAL objects that has low level data access calls using ADO.NET. From here you go on to learn that this implementation means your tied to a data access layer and you make use of a separate entity, data access object and DAO interface for mocking or to easily swap out the DAO if need be. i.e. ``` public UserDAO : IUserDAO { //Data access Functions } ``` With use of generics and reflection or a good ORM you can relieve some of the more common data access CRUD operations i.e. ``` Public UserDAO<User> : BaseDAO<User>, IUserDAO { //BaseDAO deals with basic crud so more custom data access methods can go here } ``` So basically that's where I am currently at, aside from some other nice practices like using IoC to resolve the specific IUserDAO I want. But while I see the advantage to this structure I am also left feeling like I miss the old User.Load(1) method calls. What I was wondering is would it be such a bad thing to inject my IUserDAO into the User entity and have that take care of the basic CRUD operations? My understanding is that as a POCO the User entity would have no problems been passed over the wire and adding methods like Save(), Load() etc would have no relavence in the sense of a data transfer object. But with that said my entities usually have lazy loaded collections which mean nothing in a DTO sense. Also, with WFP I believe can pick and chose which properties I want serializing, or at very least I could create a new UserDTO when I need to send it across the wire. So basically, aside from that issue what are the other problems with making my User entity include DataAccess related methods? Also could someone clarify whether what I am talking about is referred to as an active record pattern or is this something else? EDIT: cristianlibardo noted: > > As for potential drawbacks there is greater coupling to peristence code, resitence when following/updating associations, testability and querying. > > > There would be a greater some level of coupling but what I was thinking was somehting like the following: ``` public class User { IUserDAO userDAO; public User() { userDAO = IoCContainer.Resolve<IUserDAO>; } public User(IUserDAO userDAO) { this.userDAO = userDAO; } //DAL methods } ``` So the coupling should be minimal and as for testability, I don't see it as a problem as I can just inject a mock DAO into the entity. Thanks to Brian Hasden, these are really good resources, but I guess I just wanted justification for something I was obviously going to do. Thanks for giving the said justification.
I came to the same conclusion. The load usually doesn't make sense in the entity because once you have an instance, you're either creating a new entity or you've already got a loaded entity. I've been using entities with Save (create and update) and Delete for years now without any issues. That being said, it's usually useful to still have a DAO to do other things, so you're not exactly combining the DAO and the entity. Most of the time for my entities the Save and Delete methods are just calling into the DAO Save and Delete methods. BTW, I usually combine a dirty flag with the entity to know when properties have been changed so that you don't make unnecessary calls to save when the entity hasn't changed. Typically, entities that don't really do anything but contain getters and setters for private members mean you're working with an anemic domain model. It's an anti-pattern that's fairly controversial. You can find more information about it at: <http://www.martinfowler.com/bliki/AnemicDomainModel.html> <http://wrschneider.blogspot.com/2005/01/avoiding-anemic-domain-models-with.html> <http://www.dotnetjunkies.com/WebLog/richardslade/archive/2007/03/07/209401.aspx>
227,282
<p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p> <pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] &gt;= D x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C </code></pre> <p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p> <p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p> <p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
[ { "answer_id": 227306, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>It looks like this is a <a href=\"http://en.wikipedia.org/wiki/Linear_programming\" rel=\"nofollow noreferrer\">linear programming</a> problem.</p>\n" }, { "answer_id": 227319, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": false, "text": "<p>This looks like a <a href=\"http://en.wikipedia.org/wiki/Linear_programming\" rel=\"noreferrer\">linear programming</a> problem. The <a href=\"http://en.wikipedia.org/wiki/Simplex_algorithm\" rel=\"noreferrer\">Simplex algorithm</a> normally gives good results. It basically walks the boundaries of the subspace delimited by the inequalities, looking for the optimum.</p>\n\n<p>Think of it visually: each inequality denotes a half-space, a plane in n-dimensional space that you have to be on the right side of. Your utility function is what you're trying to optimize. If the space is closed, the optimum is going to be at one of the apexes of the closed space; if it's open, it's possible that the optimum is infinite.</p>\n" }, { "answer_id": 227345, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>You might want to use Matlab or Mathematica or look at code from <a href=\"http://www.nrbook.com/a/bookcpdf.php\" rel=\"nofollow noreferrer\">Numerical Recipes in C</a> for ideas on how to implement minimization functions. The link provided is to the 1992 version of the book. Newer versions are available at Amazon.</p>\n" }, { "answer_id": 227436, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"http://www.lindo.com/\" rel=\"nofollow noreferrer\">company</a> has a tool to do that sort of thing.</p>\n" }, { "answer_id": 227614, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>Have a look at the <a href=\"http://en.wikipedia.org/wiki/Integer_programming#Integer_unknowns\" rel=\"nofollow noreferrer\">wikipedia</a> entry on linear programming. The integer programming section is what you're searching for (the constraint of the x[i] being integers is not an easy one). </p>\n\n<p>Search python libraries for branch&amp;bound, branch&amp;cut and the like (I don't think they have been implemented in scipy yet).</p>\n\n<p>Other interesting links:</p>\n\n<ul>\n<li><a href=\"http://www.gnu.org/software/glpk/\" rel=\"nofollow noreferrer\">GNU Linear Programming Kit</a></li>\n<li><a href=\"http://www-128.ibm.com/developerworks/linux/library/l-glpk1/\" rel=\"nofollow noreferrer\">IBM article on GLPK</a></li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
I'm working on a programming problem which boils down to a set of an equation and inequality: ``` x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C ``` I want to solve for the values of `X` that will give the absolute minimum of `C`, given the input `D` and lists and `A` and `B` consisting of `a[0 - n]` and `b[0 - n ]`. I'm doing the problem at the moment in Python, but the problem in general is language-agnostic. CLARIFICATION UPDATE: the coefficients `x[0 - n]` are restricted to the set of non-negative integers.
This looks like a [linear programming](http://en.wikipedia.org/wiki/Linear_programming) problem. The [Simplex algorithm](http://en.wikipedia.org/wiki/Simplex_algorithm) normally gives good results. It basically walks the boundaries of the subspace delimited by the inequalities, looking for the optimum. Think of it visually: each inequality denotes a half-space, a plane in n-dimensional space that you have to be on the right side of. Your utility function is what you're trying to optimize. If the space is closed, the optimum is going to be at one of the apexes of the closed space; if it's open, it's possible that the optimum is infinite.
227,287
<p>I know how to find a method in java using a fixed string,</p> <pre><code>someClass.getMethod("foobar", argTypes); </code></pre> <p>but is there a way to use a regular expression rather than a fixed string to find a method on a given class? </p> <p>An example of the usage might be if I wanted to find a method that was called either "foobar" or "fooBar". Using a regular expression like "foo[Bb]ar" would match either of these method names.</p>
[ { "answer_id": 227300, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>You should apply your regexp on <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getDeclaredMethods()\" rel=\"nofollow noreferrer\">getDeclaredMethods</a>() reflection method (or GetMethods() if you want only the public ones).</p>\n\n<p>[Warning: both methods will throw a SecurityException if there is a security manager.]</p>\n\n<p>You apply it on each name of each method returned by getDeclaredMethod() and only memorize in a Collection the compliant Methods.</p>\n\n<p>Something like!</p>\n\n<pre><code>try\n{\n final Pattern aMethodNamePattern = Pattern.compile(\"foo[Bb]ar\");\n final List&lt;Method&gt; someMethods = aClass.getDeclaredMethods();\n final List&lt;Method&gt; someCompliantMethods = new ArrayList&lt;Method&gt;();\n for(final Method aMethod: someMethods)\n {\n final String aMethodName = aMethod.getName();\n final Matcher aMethodNameMatcher = aMethodNamePattern.getMatcher(aMethodName);\n if(aMethodNameMatcher.matches() == true)\n {\n someCompliantMethods.add(aMethod);\n }\n}\ncatch(...) // catch all exceptions like SecurityException, IllegalAccessException, ...\n</code></pre>\n" }, { "answer_id": 227333, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>Not directly. You could loop over all the methods and check each.</p>\n\n<pre><code>Pattern p = Pattern.compile(\"foo[Bb]ar\");\nfor(Method m : someClass.getMethods()) {\n if(p.matcher(m.getName()).matches()) {\n return m; \n }\n}\n</code></pre>\n" }, { "answer_id": 227344, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>No, you can't do that, but you can get a list of the method a class has and apply the regexp to them.</p>\n\n<pre><code>Method[] getMethods( String regexp, Class clazz, Object ... argTypes ){\n List&lt;Method&gt; toReturn = new ArrayList&lt;Method&gt;();\n for( Method m : clazz.getDeclaredMethods() ){ \n if( m.getName().matches( regExp ) ) { // validate argTypes aswell here...\n toReturn.add( m );\n }\n }\n return toReturn.toArray(); \n}\n</code></pre>\n\n<p>Well something like that....</p>\n" }, { "answer_id": 227367, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 1, "selected": false, "text": "<p>You could do it by iterating over ALL the methods on a class and matching them that way.</p>\n\n<p>Not that simple, but it would do the trick</p>\n\n<pre><code> ArrayList&lt;Method&gt; matches = new ArrayList&lt;Method&gt;();\n for(Method meth : String.class.getMethods()) {\n if (meth.getName().matches(\"lengt.\")){\n matches.add(meth);\n }\n }\n</code></pre>\n" }, { "answer_id": 35428600, "author": "krzysiek.ste", "author_id": 2750931, "author_profile": "https://Stackoverflow.com/users/2750931", "pm_score": 0, "selected": false, "text": "<p>When I want look for some method using simple name pattern I use this <a href=\"https://github.com/ronmamo/reflections\" rel=\"nofollow\">org.reflections</a></p>\n\n<p>For example looking for some methods which are public and name start with get:</p>\n\n<pre><code>Set&lt;Method&gt; getters = ReflectionUtils.getAllMethods(SomeClass.class, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix(\"get\"));\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
I know how to find a method in java using a fixed string, ``` someClass.getMethod("foobar", argTypes); ``` but is there a way to use a regular expression rather than a fixed string to find a method on a given class? An example of the usage might be if I wanted to find a method that was called either "foobar" or "fooBar". Using a regular expression like "foo[Bb]ar" would match either of these method names.
You should apply your regexp on [getDeclaredMethods](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getDeclaredMethods())() reflection method (or GetMethods() if you want only the public ones). [Warning: both methods will throw a SecurityException if there is a security manager.] You apply it on each name of each method returned by getDeclaredMethod() and only memorize in a Collection the compliant Methods. Something like! ``` try { final Pattern aMethodNamePattern = Pattern.compile("foo[Bb]ar"); final List<Method> someMethods = aClass.getDeclaredMethods(); final List<Method> someCompliantMethods = new ArrayList<Method>(); for(final Method aMethod: someMethods) { final String aMethodName = aMethod.getName(); final Matcher aMethodNameMatcher = aMethodNamePattern.getMatcher(aMethodName); if(aMethodNameMatcher.matches() == true) { someCompliantMethods.add(aMethod); } } catch(...) // catch all exceptions like SecurityException, IllegalAccessException, ... ```
227,288
<p><a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow noreferrer">YUI Compressor</a> does not accept wildcard parameters, so I cannot run it like this: </p> <pre><code>C:&gt;java -jar yuicompressor.jar *.js </code></pre> <p>But I have over 500 files and would rather not have to create a batch file like this:</p> <pre><code>C:&gt;java -jar yuicompressor.jar file1.js -o deploy\file1.js C:&gt;java -jar yuicompressor.jar file2.js -o deploy\file2.js ... C:&gt;java -jar yuicompressor.jar file500.js -o deploy\file500.js </code></pre> <p>And of course my file names are <em>not</em> in such uniform way.</p> <p>Is there way to automate this without writing any code? :)</p>
[ { "answer_id": 227336, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "<p>I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work:</p>\n\n<pre><code>for %%a in (*.js) do @java -jar yuicompressor.jar \"%%a\" -o \"deploy\\%%a\"\n</code></pre>\n" }, { "answer_id": 227354, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 1, "selected": false, "text": "<p>You'll need to use some sort of a script to get a list of all the .js files, and then runs the YUI Compressor on all of them. On the windows command prompt, something like this should work:</p>\n\n<pre><code>FOR %f IN (*.js) DO java -jar yuicompressor.jar %f -o deploy\\%f\n</code></pre>\n" }, { "answer_id": 227364, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 2, "selected": false, "text": "<p>And for unix or cygwin you can use xargs or something like:</p>\n\n<p>ls -1 *.js | awk '{printf(\"java -jar yuicompressor.jar %s -o deploy/%s\",$1,$1)}'</p>\n\n<p>Pipe that to /bin/sh when you're happy with the command line to execute it.</p>\n" }, { "answer_id": 227371, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 2, "selected": false, "text": "<p>I should mention that using GNU Make, I have the following rule:</p>\n\n<pre><code>%-min.js: %.js\n ${java} -jar ${compressor} $&lt; -o ${&lt;:.js=-min.js}\n</code></pre>\n" }, { "answer_id": 227512, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 3, "selected": false, "text": "<p>If you are geared towards Java, you can also use Ant for conversion. I've found a <a href=\"http://blog.gomilko.com/2007/11/29/yui-compression-tool-as-ant-task/\" rel=\"noreferrer\">blog entry</a> about an <a href=\"http://www.ubik-ingenierie.com/ubikwiki/index.php?title=Minifying_JS/CSS\" rel=\"noreferrer\">Ant Taks for the YUI Compressor</a>. Disclaimer: Never tried it - sorry</p>\n" }, { "answer_id": 5660438, "author": "hazerd", "author_id": 626531, "author_profile": "https://Stackoverflow.com/users/626531", "pm_score": 3, "selected": false, "text": "<p>YUI compressor now supports wildcards, starting from version 2.4.4. You can get the latest version <a href=\"http://yuilibrary.com/download/yuicompressor/\" rel=\"nofollow noreferrer\">here</a> or from <a href=\"https://github.com/yui/yuicompressor\" rel=\"nofollow noreferrer\">YUI Git Hub</a>.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) does not accept wildcard parameters, so I cannot run it like this: ``` C:>java -jar yuicompressor.jar *.js ``` But I have over 500 files and would rather not have to create a batch file like this: ``` C:>java -jar yuicompressor.jar file1.js -o deploy\file1.js C:>java -jar yuicompressor.jar file2.js -o deploy\file2.js ... C:>java -jar yuicompressor.jar file500.js -o deploy\file500.js ``` And of course my file names are *not* in such uniform way. Is there way to automate this without writing any code? :)
I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work: ``` for %%a in (*.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a" ```
227,305
<p>I am building up a view with various text and image elements.</p> <p>I want to display some text in the view with a blurry copy of the text behind it, but not just a text shadow.</p> <p>How do I apply Gaussian blurred text onto a UIImage or layer?</p>
[ { "answer_id": 228176, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 0, "selected": false, "text": "<p>On the desktop, no question, you'd use CoreImage to do this.</p>\n\n<p>On the phone though, I don't think there exists a way to do this using CoreGraphics. If it is absolutely critical OpenGLES may be able to help.</p>\n\n<p>However, I would suggest rethinking your interface. I would think the blurred text would be distracting.</p>\n\n<p>Edit: mledford points out in the comments that you could use CoreAnimation. I don't know if CA on the phone includes blur radius like on the desktop, but you could try it.</p>\n" }, { "answer_id": 230669, "author": "Noah Witherspoon", "author_id": 30618, "author_profile": "https://Stackoverflow.com/users/30618", "pm_score": 1, "selected": false, "text": "<p>iPhone OS doesn't provide any Core Image filters that I know of - otherwise, yes, a filtered CALayer would be the right way to do it. If NSBitmapImageRep were available, you could do a primitive blur by drawing the text to it, shrinking the image (downsampling), then enlarging the image again (upsampling) - unfortunately it seems to be missing as well. I've seen blurred text accomplished in Flash, which (last I checked) doesn't have pixel-level filtering; you might try looking for a tutorial on that and seeing what you can adapt to Cocoa Touch.</p>\n" }, { "answer_id": 310236, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 0, "selected": false, "text": "<p>You will take a performance hit if you use alpha layers. Consider a different approach if possible (maybe even precompositing the text and flattening it into a graphic instead of multiple layers).</p>\n\n<p>Try it, and use Instruments to check out the performance and see if it's acceptable. If you're doing it in a scrolling view, your scrolling will bog down a <em>lot</em>.</p>\n" }, { "answer_id": 1256500, "author": "mahboudz", "author_id": 86020, "author_profile": "https://Stackoverflow.com/users/86020", "pm_score": 3, "selected": false, "text": "<p>Take a look at Apple's GLImageProcessing iPhone sample. It does some blurring, among other things.</p>\n\n<p>The relevant code includes:</p>\n\n<pre><code>static void blur(V2fT2f *quad, float t) // t = 1\n{\n GLint tex;\n V2fT2f tmpquad[4];\n float offw = t / Input.wide;\n float offh = t / Input.high;\n int i;\n\n glGetIntegerv(GL_TEXTURE_BINDING_2D, &amp;tex);\n\n // Three pass small blur, using rotated pattern to sample 17 texels:\n //\n // .\\/.. \n // ./\\\\/ \n // \\/X/\\ rotated samples filter across texel corners\n // /\\\\/. \n // ../\\. \n\n // Pass one: center nearest sample\n glVertexPointer (2, GL_FLOAT, sizeof(V2fT2f), &amp;quad[0].x);\n glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &amp;quad[0].s);\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n glColor4f(1.0/5, 1.0/5, 1.0/5, 1.0);\n validateTexEnv();\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\n // Pass two: accumulate two rotated linear samples\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n for (i = 0; i &lt; 4; i++)\n {\n tmpquad[i].x = quad[i].s + 1.5 * offw;\n tmpquad[i].y = quad[i].t + 0.5 * offh;\n tmpquad[i].s = quad[i].s - 1.5 * offw;\n tmpquad[i].t = quad[i].t - 0.5 * offh;\n }\n glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &amp;tmpquad[0].x);\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n glActiveTexture(GL_TEXTURE1);\n glEnable(GL_TEXTURE_2D);\n glClientActiveTexture(GL_TEXTURE1);\n glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &amp;tmpquad[0].s);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glBindTexture(GL_TEXTURE_2D, tex);\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);\n glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);\n glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);\n glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS);\n glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PRIMARY_COLOR);\n glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);\n glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);\n glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PRIMARY_COLOR);\n\n glColor4f(0.5, 0.5, 0.5, 2.0/5);\n validateTexEnv();\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\n // Pass three: accumulate two rotated linear samples\n for (i = 0; i &lt; 4; i++)\n {\n tmpquad[i].x = quad[i].s - 0.5 * offw;\n tmpquad[i].y = quad[i].t + 1.5 * offh;\n tmpquad[i].s = quad[i].s + 0.5 * offw;\n tmpquad[i].t = quad[i].t - 1.5 * offh;\n }\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n\n // Restore state\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n glClientActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, Half.texID);\n glDisable(GL_TEXTURE_2D);\n glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);\n glActiveTexture(GL_TEXTURE0);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glDisable(GL_BLEND);\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30342/" ]
I am building up a view with various text and image elements. I want to display some text in the view with a blurry copy of the text behind it, but not just a text shadow. How do I apply Gaussian blurred text onto a UIImage or layer?
Take a look at Apple's GLImageProcessing iPhone sample. It does some blurring, among other things. The relevant code includes: ``` static void blur(V2fT2f *quad, float t) // t = 1 { GLint tex; V2fT2f tmpquad[4]; float offw = t / Input.wide; float offh = t / Input.high; int i; glGetIntegerv(GL_TEXTURE_BINDING_2D, &tex); // Three pass small blur, using rotated pattern to sample 17 texels: // // .\/.. // ./\\/ // \/X/\ rotated samples filter across texel corners // /\\/. // ../\. // Pass one: center nearest sample glVertexPointer (2, GL_FLOAT, sizeof(V2fT2f), &quad[0].x); glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &quad[0].s); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor4f(1.0/5, 1.0/5, 1.0/5, 1.0); validateTexEnv(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Pass two: accumulate two rotated linear samples glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); for (i = 0; i < 4; i++) { tmpquad[i].x = quad[i].s + 1.5 * offw; tmpquad[i].y = quad[i].t + 0.5 * offh; tmpquad[i].s = quad[i].s - 1.5 * offw; tmpquad[i].t = quad[i].t - 0.5 * offh; } glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &tmpquad[0].x); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glClientActiveTexture(GL_TEXTURE1); glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &tmpquad[0].s); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindTexture(GL_TEXTURE_2D, tex); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS); glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PRIMARY_COLOR); glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PRIMARY_COLOR); glColor4f(0.5, 0.5, 0.5, 2.0/5); validateTexEnv(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Pass three: accumulate two rotated linear samples for (i = 0; i < 4; i++) { tmpquad[i].x = quad[i].s - 0.5 * offw; tmpquad[i].y = quad[i].t + 1.5 * offh; tmpquad[i].s = quad[i].s + 0.5 * offw; tmpquad[i].t = quad[i].t - 1.5 * offh; } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Restore state glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Half.texID); glDisable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); glActiveTexture(GL_TEXTURE0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glDisable(GL_BLEND); } ```
227,312
<p>Currently we are using prototype and jQuery as our js frameworks. Right now, jQuery is set to $j() to prevent conflicts from prototype.</p> <p>In the past, we've used a lot of prototype's Element.down(), Element.next(), and Element.previous() to traverse the DOM. However, I need a simple way to retrieve the last child element. I know i can loop through an array by using Element.childElements() but I would like something inline that reads cleanly and can be pipelined.</p> <p>Just thought I would ask before I go reinventing the wheel. Here's a snippet of code that has lastChild in it that needs to be replaced:</p> <pre><code>_find : function(rows, address) { var obj = null; for (var i=0; i &lt; rows.length &amp;&amp; obj == null; i++) { if (rows[i].down().className == 'b') obj = this._find(rows[i].lastChild.down().down().childElements(), address); else if (rows[i].lastChild.getAttribute('tabAddress') == address) return rows[i].lastChild; } return obj; } </code></pre>
[ { "answer_id": 227323, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 1, "selected": false, "text": "<p>Try this it has always worked for me in jQuery</p>\n\n<pre><code>var lastChild = $(\"#parent :last-child\");\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/Selectors/lastChild\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/lastChild</a></p>\n" }, { "answer_id": 227342, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 1, "selected": false, "text": "<p>Using Prototype you can use the <a href=\"http://www.prototypejs.org/api/utility/dollar-dollar\" rel=\"nofollow noreferrer\">$$</a> utility function which supports most of the CSS3 syntax:</p>\n\n<pre><code>var lastChild = $$(\".b:last-child\")[0];\n</code></pre>\n" }, { "answer_id": 228558, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 5, "selected": true, "text": "<p>Guys, note that the selector functions return arrays of elements (not single elements), so you must adddress the element in the result array by index: [0].</p>\n\n<p>Code in prototype</p>\n\n<pre><code>//if you only have the id of the parent\nvar lastChild = $$(\"#parent :last-child\")[0]; \n//or\n//if you have the actual DOM element\nvar lastChild = $(element).select(\":last-child\")[0]; \n</code></pre>\n\n<p>Code in Jquery</p>\n\n<pre><code>//if you only have the id of the parent\nvar lastChild = $(\"#parent :last-child\")[0]; \n//or\n//if you have the actual DOM element\nvar lastChild = $(\":last-child\", element)[0]; \n</code></pre>\n\n<p>Code in plain vanilla javascript</p>\n\n<pre><code>var element = document.getElementById(\"parent\");\nvar lastChild = element.childNodes[element.childNodes.length - 1];\n</code></pre>\n\n<p>Also note that these can return null if the parent element has no child nodes.</p>\n\n<ul>\n<li><a href=\"http://www.quirksmode.org/css/firstchild.html\" rel=\"noreferrer\">Some info on the CSS :last-child selector</a></li>\n</ul>\n" }, { "answer_id": 15666324, "author": "Chris McFadyen", "author_id": 2216908, "author_profile": "https://Stackoverflow.com/users/2216908", "pm_score": 0, "selected": false, "text": "<p>In case anyone finds this while searching the web to answer their question, with Prototype you can do:</p>\n\n<pre><code>Element.childElements().last();\n</code></pre>\n" }, { "answer_id": 37665142, "author": "mwieczorek", "author_id": 280919, "author_profile": "https://Stackoverflow.com/users/280919", "pm_score": 0, "selected": false, "text": "<p>For anyone else's reference who still uses Prototype, You can add custom element methods:</p>\n\n<p><code>Element.addMethods({ ... });</code></p>\n\n<p>I added these two among others:</p>\n\n<pre><code>first: function(element) {\n element = $(element);\n return element.childElements()[0]; \n},\nlast: function(element) {\n element = $(element);\n var i = element.childElements().size() - 1;\n return element.childElements()[i];\n}\n\nvar first = $('foo').first();\nvar last = $('foo').last();\n</code></pre>\n\n<p>The <code>Element.first()</code> method is sort of redundant, I use it for cleaner-looking code when chaining.</p>\n\n<p>Make sure you <code>reutrn element</code> to enable chaining.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203/" ]
Currently we are using prototype and jQuery as our js frameworks. Right now, jQuery is set to $j() to prevent conflicts from prototype. In the past, we've used a lot of prototype's Element.down(), Element.next(), and Element.previous() to traverse the DOM. However, I need a simple way to retrieve the last child element. I know i can loop through an array by using Element.childElements() but I would like something inline that reads cleanly and can be pipelined. Just thought I would ask before I go reinventing the wheel. Here's a snippet of code that has lastChild in it that needs to be replaced: ``` _find : function(rows, address) { var obj = null; for (var i=0; i < rows.length && obj == null; i++) { if (rows[i].down().className == 'b') obj = this._find(rows[i].lastChild.down().down().childElements(), address); else if (rows[i].lastChild.getAttribute('tabAddress') == address) return rows[i].lastChild; } return obj; } ```
Guys, note that the selector functions return arrays of elements (not single elements), so you must adddress the element in the result array by index: [0]. Code in prototype ``` //if you only have the id of the parent var lastChild = $$("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(element).select(":last-child")[0]; ``` Code in Jquery ``` //if you only have the id of the parent var lastChild = $("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(":last-child", element)[0]; ``` Code in plain vanilla javascript ``` var element = document.getElementById("parent"); var lastChild = element.childNodes[element.childNodes.length - 1]; ``` Also note that these can return null if the parent element has no child nodes. * [Some info on the CSS :last-child selector](http://www.quirksmode.org/css/firstchild.html)
227,351
<p>I want to expose the functionality of an SAP program (transaction) as a BAPI. I need to call a report and supply range filters such that the GUI is bypassed.</p> <p>Does anyone have a working example of the SUBMIT ... WITH ... ABAP construct, or other suggestions on how to accomplish what I need to do?</p>
[ { "answer_id": 231587, "author": "Esti", "author_id": 25687, "author_profile": "https://Stackoverflow.com/users/25687", "pm_score": 2, "selected": false, "text": "<p>Here is a working example:</p>\n\n<pre><code>SUBMIT SAPF140 \n TO SAP-SPOOL \"optional\"\n SPOOL PARAMETERS print_parameters \"optional\"\n WITHOUT SPOOL DYNPRO \"optional (hides the spool pop-up)\"\n VIA JOB jobname NUMBER l_number \"optional\"\n AND RETURN \"optional - returns to the calling prog\"\n WITH EVENT = REVENT\n WITH BUKRS IN RBUKRS\n WITH BELNR IN lRBELNR\n WITH GJAHR IN RGJAHR\n WITH USNAM = SY-UNAME\n WITH DATUM = SAVE_DATUM\n WITH UZEIT = SAVE_UZEIT\n WITH DELDAYS = RDELDAYS\n WITH KAUTO = 'X'\n WITH RPDEST = SAVE_PDEST\n WITH TITLE = TITLE.\n</code></pre>\n\n<p>All the \"WITH\" statements relates to selection fields on the called program where I use = it is a PARAMETER statement (single field), where I use IN it is a SELECT_OPTIONS statement (range)</p>\n\n<p>Here is a simple example of how to fill a range:</p>\n\n<pre><code>REFRESH lrbelnr.\nlrbelnr-sign = 'I'.\nlrbelnr-option = 'EQ'.\nlrbelnr-low = HBKORM-belnr.\nCLEAR lrbelnr-high.\nappend lrbelnr.\n</code></pre>\n" }, { "answer_id": 1960087, "author": "Matthias Kneissl", "author_id": 236803, "author_profile": "https://Stackoverflow.com/users/236803", "pm_score": 1, "selected": false, "text": "<p>If you want to suppress this functionality as a BAPI you have to wrap the functionality in a Remote Function Call (RFC) module. Just implement a RFC function module. Depending how the report is implemented, it may use ABAP objects, which can also be called from your RFC implementation. Given that case you have a quite good solution. Whenever the report is adjusted, also your BAPI will reflect the changes. In case it's a standard programm from SAP which cannot be wrapped, think about copying it into your namespace and adjusting it. Nevertheless this might give some hassle, when SAP performs an update via Support Package Stack and you won't realize it. The output of the two methods is different. Apart from that, if you want to call it from outside, there is nothing else possible than implementing a RFC module. </p>\n\n<p>A submit report can not return the values outside. Reports are always only for GUI functionalities and not for exchanging data. In case your report uses select options, you somehow have to implement this feature \"by hand\" in your RFC, as this statements can not be used inside RFC modules. I would generally try to rework the report, modularize it and put the selection information in a central class or maybe another function module wich can be called from the report and your BAPI function module. The filters you are talking about can not be implemented in RFCs automatically. You have to implement those ranges manually. The warning which comes up cannot be suppressed, if you do a RFC call from a remote system and the popup with the warning comes up you'll end with a shortdump. Therefore, you have to rework the report and to re-implement it for your needs.</p>\n\n<p>If you are just looking for bypassing it via job scheduling, create a variant and schedule the report with that variant but I suppose that's not the solution you're looking for.</p>\n" }, { "answer_id": 3965396, "author": "rahul", "author_id": 480044, "author_profile": "https://Stackoverflow.com/users/480044", "pm_score": 1, "selected": false, "text": "<p>You can use inbuilt <a href=\"http://www.comeletstalk.com\" rel=\"nofollow\">BAPI</a> also just write \"<em>Range</em>\" and press F4.</p>\n" }, { "answer_id": 8267560, "author": "franblay", "author_id": 231100, "author_profile": "https://Stackoverflow.com/users/231100", "pm_score": 0, "selected": false, "text": "<p>You can wrap your report in an <a href=\"http://help.sap.com/saphelp_nwes72/helpdata/en/69/c250274ba111d189750000e8322d00/frameset.htm\" rel=\"nofollow\">BATCH INPUT session</a> and execute it inside a function. The only drawback is that you need to rewrite the BATCH INPUT every time you change the report.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26652/" ]
I want to expose the functionality of an SAP program (transaction) as a BAPI. I need to call a report and supply range filters such that the GUI is bypassed. Does anyone have a working example of the SUBMIT ... WITH ... ABAP construct, or other suggestions on how to accomplish what I need to do?
Here is a working example: ``` SUBMIT SAPF140 TO SAP-SPOOL "optional" SPOOL PARAMETERS print_parameters "optional" WITHOUT SPOOL DYNPRO "optional (hides the spool pop-up)" VIA JOB jobname NUMBER l_number "optional" AND RETURN "optional - returns to the calling prog" WITH EVENT = REVENT WITH BUKRS IN RBUKRS WITH BELNR IN lRBELNR WITH GJAHR IN RGJAHR WITH USNAM = SY-UNAME WITH DATUM = SAVE_DATUM WITH UZEIT = SAVE_UZEIT WITH DELDAYS = RDELDAYS WITH KAUTO = 'X' WITH RPDEST = SAVE_PDEST WITH TITLE = TITLE. ``` All the "WITH" statements relates to selection fields on the called program where I use = it is a PARAMETER statement (single field), where I use IN it is a SELECT\_OPTIONS statement (range) Here is a simple example of how to fill a range: ``` REFRESH lrbelnr. lrbelnr-sign = 'I'. lrbelnr-option = 'EQ'. lrbelnr-low = HBKORM-belnr. CLEAR lrbelnr-high. append lrbelnr. ```
227,357
<p>I have a master page, with a help link in the top menu. This link should contain the a dynamic bookmark from the current page, so that the user scrolls to the help for the page he is currently seeing.</p> <pre><code>&lt;a href="help.aspx#[NameOfCurentPage]"&gt;Help&lt;/a&gt; </code></pre> <p>How would you implement this?</p>
[ { "answer_id": 227369, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "<p>i haven't written a line of c# in over three months but you could hook up an event in the masterpage (OnLoad) and set the link from there. See what's in the ContentPlaceholder that's your main page and get it's type or name, then apply it to the link.</p>\n" }, { "answer_id": 227387, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 1, "selected": false, "text": "<p>I would use \"<a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx\" rel=\"nofollow noreferrer\">Request.PhysicalPath</a>\" to get the physical path that was requested, then within your help HMTL you can denote the sections by what page they are about.</p>\n\n<p>You might go as far as to use:</p>\n\n<pre><code>Path.GetFileName(Request.PhysicalPath).ToUpper()\n</code></pre>\n\n<p>to normalize the data. Using the PhysicalPath would allow you to have all logic in the master page; which would eliminate the need to write code in all content pages. Just my preference.</p>\n" }, { "answer_id": 227406, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": true, "text": "<p>Another thing you could do is reference the master page through the content page itself.</p>\n\n<p>To make it easier on myself, I create a publicly accessible method in the master page itself:</p>\n\n<pre><code>Public Sub SetNavigationPage(ByVal LinkName As String)\n DirectCast(Me.FindControl(MenuName), HyperLink).NavigateUrl = \"help.aspx#\" &amp; LinkName\nEnd Sub\n</code></pre>\n\n<p>Then in the content page, I get a reference to the master page through the following...</p>\n\n<pre><code>Dim myMaster As MasterPageClass = DirectCast(Me.Master, MasterPageClass)\nmyMaster.SetNavigationPage(\"CurrentPage\")\n</code></pre>\n" }, { "answer_id": 227567, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Put</p>\n\n<pre><code>&lt;a href=\"help.aspx#&lt;%= Path.GetFileName(this.Page.Request.FilePath) %&gt;\"&gt;Help&lt;/a&gt;\n</code></pre>\n\n<p>into the MasterPage, and then anchors on the help page in the format of:</p>\n\n<pre><code>&lt;a name=\"page1.aspx\" /&gt;Blah, blah\n&lt;a name=\"page2.aspx\" /&gt;Blah, blah\n</code></pre>\n\n<p>If you repeat page names in subfolders, eg., Sub1/page1.aspx and Sub2/page1.aspx - you'll have to be slightly more clever.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
I have a master page, with a help link in the top menu. This link should contain the a dynamic bookmark from the current page, so that the user scrolls to the help for the page he is currently seeing. ``` <a href="help.aspx#[NameOfCurentPage]">Help</a> ``` How would you implement this?
Another thing you could do is reference the master page through the content page itself. To make it easier on myself, I create a publicly accessible method in the master page itself: ``` Public Sub SetNavigationPage(ByVal LinkName As String) DirectCast(Me.FindControl(MenuName), HyperLink).NavigateUrl = "help.aspx#" & LinkName End Sub ``` Then in the content page, I get a reference to the master page through the following... ``` Dim myMaster As MasterPageClass = DirectCast(Me.Master, MasterPageClass) myMaster.SetNavigationPage("CurrentPage") ```
227,376
<p>I need to round a value up to the nearest multiple of 2.5.</p> <p>For example:<br> 6 --> 7.5<br> 7.6 --> 10<br> etc. </p> <p>This seems like the best way to do this?</p> <pre><code> Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment If originalNumber Mod increment &lt;&gt; 0 And num &lt; originalNumber Then num += increment End If Return num End Function </code></pre>
[ { "answer_id": 227384, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 6, "selected": true, "text": "<p>Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.</p>\n\n<p>You're close.</p>\n\n<pre><code>Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal\n Return Math.Ceiling( orignialNumber / increment ) * increment\nEnd Function\n</code></pre>\n\n<p>Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.</p>\n" }, { "answer_id": 227385, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<p>Divide the number by 2.5. Round to nearest 1. Multiply by 2.5.</p>\n\n<p>Beware of cumulative errors, and you're all set.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 14125433, "author": "WAL", "author_id": 1943387, "author_profile": "https://Stackoverflow.com/users/1943387", "pm_score": 2, "selected": false, "text": "<pre><code> /*\n This will round up (Math.Ceiling) or down (Math.Floor) based on the midpoint of the increment. \n The other examples use Math.Ceiling and therefore always round up.\n Assume the increment is 2.5 in this example and the number is 6.13\n */\n var halfOfIncrement = Increment / 2; // 2.5 / 2 = 1.25\n var floorResult = Math.Floor(originalNumber / Increment); //Math.Floor(6.13 / 2.5) = Math.Floor(2.452) = 2\n var roundingThreshold = (floorResult * Increment) + halfOfIncrement; //(2 * 2.5) = 5 + 1.25 = 6.25\n\n if (originalNumber &gt;= roundingThreshold) //6.13 &gt;= 6.25 == false therefore take Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 * 2.5 = 5\n result = Math.Ceiling(originalNumber / Increment) * Increment;\n else\n result = Math.Floor(originalNumber / Increment) * Increment;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34548/" ]
I need to round a value up to the nearest multiple of 2.5. For example: 6 --> 7.5 7.6 --> 10 etc. This seems like the best way to do this? ``` Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment If originalNumber Mod increment <> 0 And num < originalNumber Then num += increment End If Return num End Function ```
Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5. You're close. ``` Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal Return Math.Ceiling( orignialNumber / increment ) * increment End Function ``` Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.
227,380
<p>Consider the following code:</p> <pre><code>abstract class SomeClassX&lt;T&gt; { // blah } class SomeClassY: SomeClassX&lt;int&gt; { // blah } class SomeClassZ: SomeClassX&lt;long&gt; { // blah } </code></pre> <p>I want a collection of SomeClassX&lt;T&gt;'s, however, this isn't possible since SomeClassX&lt;int&gt; != SomeClassX&lt;long&gt; and List&lt;SomeClassX&lt;&gt;&gt; isn't allowed.</p> <p>So my solution is to have SomeClassX&lt;T&gt; implement an interface and define my collection as, where ISomeClassX is the interface:</p> <pre><code>class CollectionOfSomeClassX: List&lt;ISomeClassX&gt; { // blah } </code></pre> <p>Is this the best way to do this, or is there better way?</p>
[ { "answer_id": 227384, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 6, "selected": true, "text": "<p>Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.</p>\n\n<p>You're close.</p>\n\n<pre><code>Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal\n Return Math.Ceiling( orignialNumber / increment ) * increment\nEnd Function\n</code></pre>\n\n<p>Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.</p>\n" }, { "answer_id": 227385, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<p>Divide the number by 2.5. Round to nearest 1. Multiply by 2.5.</p>\n\n<p>Beware of cumulative errors, and you're all set.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 14125433, "author": "WAL", "author_id": 1943387, "author_profile": "https://Stackoverflow.com/users/1943387", "pm_score": 2, "selected": false, "text": "<pre><code> /*\n This will round up (Math.Ceiling) or down (Math.Floor) based on the midpoint of the increment. \n The other examples use Math.Ceiling and therefore always round up.\n Assume the increment is 2.5 in this example and the number is 6.13\n */\n var halfOfIncrement = Increment / 2; // 2.5 / 2 = 1.25\n var floorResult = Math.Floor(originalNumber / Increment); //Math.Floor(6.13 / 2.5) = Math.Floor(2.452) = 2\n var roundingThreshold = (floorResult * Increment) + halfOfIncrement; //(2 * 2.5) = 5 + 1.25 = 6.25\n\n if (originalNumber &gt;= roundingThreshold) //6.13 &gt;= 6.25 == false therefore take Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 * 2.5 = 5\n result = Math.Ceiling(originalNumber / Increment) * Increment;\n else\n result = Math.Floor(originalNumber / Increment) * Increment;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30521/" ]
Consider the following code: ``` abstract class SomeClassX<T> { // blah } class SomeClassY: SomeClassX<int> { // blah } class SomeClassZ: SomeClassX<long> { // blah } ``` I want a collection of SomeClassX<T>'s, however, this isn't possible since SomeClassX<int> != SomeClassX<long> and List<SomeClassX<>> isn't allowed. So my solution is to have SomeClassX<T> implement an interface and define my collection as, where ISomeClassX is the interface: ``` class CollectionOfSomeClassX: List<ISomeClassX> { // blah } ``` Is this the best way to do this, or is there better way?
Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5. You're close. ``` Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal Return Math.Ceiling( orignialNumber / increment ) * increment End Function ``` Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.
227,383
<p>How do I programmatically return the maximum of two integers without using any comparison operators and without using <code>if</code>, <code>else</code>, etc?</p>
[ { "answer_id": 227393, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 2, "selected": false, "text": "<p>return (a > b ? a : b);</p>\n\n<p>or</p>\n\n<pre><code>int max(int a, int b)\n{\n int x = (a - b) &gt;&gt; 31;\n int y = ~x;\n return (y &amp; a) | (x &amp; b); \n}\n</code></pre>\n" }, { "answer_id": 227416, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax\" rel=\"nofollow noreferrer\">http://www.graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax</a></p>\n\n<pre><code>r = x - ((x - y) &amp; -(x &lt; y)); // max(x, y)\n</code></pre>\n\n<p>You can have fun with arithmetically shifting <code>(x - y)</code> to saturate the sign bit, but this is usually enough. Or you can test the high bit, always fun.</p>\n" }, { "answer_id": 227418, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 6, "selected": true, "text": "<p>max: // Will put MAX(a,b) into a</p>\n\n<pre><code>a -= b;\na &amp;= (~a) &gt;&gt; 31;\na += b;\n</code></pre>\n\n<p>And:</p>\n\n<p>int a, b;</p>\n\n<p>min: // Will put MIN(a,b) into a</p>\n\n<pre><code>a -= b;\na &amp;= a &gt;&gt; 31;\na += b;\n</code></pre>\n\n<p>from <a href=\"http://web.archive.org/web/20130821015554/http://bob.allegronetwork.com/prog/tricks.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 227432, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 3, "selected": false, "text": "<p>I think I've got it.</p>\n\n<pre><code>int data[2] = {a,b};\nint c = a - b;\nreturn data[(int)((c &amp; 0x80000000) &gt;&gt; 31)];\n</code></pre>\n\n<p>Would this not work? Basically, you take the difference of the two, and then return one or the other based on the sign bit. (This is how the processor does greater than or less than anyway.) So if the sign bit is 0, return a, since a is greater than or equal to b. If the sign bit is 1, return b, because subtracting b from a caused the result to go negative, indicating that b was greater than a. Just make sure that your ints are 32bits signed.</p>\n" }, { "answer_id": 227433, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 2, "selected": false, "text": "<p>not as snazzy as the above... but...</p>\n\n<pre><code>int getMax(int a, int b)\n{\n for(int i=0; (i&lt;a) || (i&lt;b); i++) { }\n return i;\n}\n</code></pre>\n" }, { "answer_id": 227435, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 2, "selected": false, "text": "<p>Since this is a puzzle, solution will be slightly convoluted:</p>\n\n<pre><code>let greater x y = signum (1+signum (x-y))\n\nlet max a b = (greater a b)*a + (greater b a)*b\n</code></pre>\n\n<p>This is Haskell, but it will be the same in any other language. C/C# folks should use \"sgn\" (or \"sign\"?) instead of signum.</p>\n\n<p>Note that this will work on ints of arbitrary size and on reals as well.</p>\n" }, { "answer_id": 227477, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "<p>This is kind of cheating, using assembly language, but it's interesting nonetheless:</p>\n\n<pre><code>\n// GCC inline assembly\nint max(int a, int b)\n{\n __asm__(\"movl %0, %%eax\\n\\t\" // %eax = a\n \"cmpl %%eax, %1\\n\\t\" // compare a to b\n \"cmovg %1, %%eax\" // %eax = b if b>a\n :: \"r\"(a), \"r\"(b));\n}\n</code></pre>\n\n<p>If you want to be strict about the rules and say that the <code>cmpl</code> instruction is illegal for this, then the following (less efficient) sequence will work:</p>\n\n<pre><code>\nint max(int a, int b)\n{\n __asm__(\"movl %0, %%eax\\n\\t\"\n \"subl %1, %%eax\\n\\t\"\n \"cmovge %0, %%eax\\n\\t\"\n \"cmovl %1, %%eax\"\n :: \"r\"(a), \"r\"(b)\n :\"%eax\");\n}\n</code></pre>\n" }, { "answer_id": 867612, "author": "Dimitris", "author_id": 108668, "author_profile": "https://Stackoverflow.com/users/108668", "pm_score": 3, "selected": false, "text": "<p>In the math world:</p>\n<pre><code>max(a+b) = ( (a+b) + |(a-b)| ) / 2\nmin(a-b) = ( (a+b) - |(a-b)| ) / 2\n</code></pre>\n<p>Apart from being mathematically correct it is not making assumptions about the bit size as shifting operations need to do.</p>\n<p><code>|x|</code> stands for the absolute value of x.</p>\n<h1>Comment:</h1>\n<p>You are right, the absolute value was forgotten. This should be valid for all a, b positive or negative</p>\n" }, { "answer_id": 1693476, "author": "Bartosz Wójcik", "author_id": 205036, "author_profile": "https://Stackoverflow.com/users/205036", "pm_score": 2, "selected": false, "text": "<p>From z0mbie's (famous virii writer) article \"Polymorphic Games\", maybe you'll find it useful:</p>\n\n<pre><code>#define H0(x) (((signed)(x)) &gt;&gt; (sizeof((signed)(x))*8-1))\n#define H1(a,b) H0((a)-(b))\n\n#define MIN1(a,b) ((a)+(H1(b,a) &amp; ((b)-(a))))\n#define MIN2(a,b) ((a)-(H1(b,a) &amp; ((a)-(b))))\n#define MIN3(a,b) ((b)-(H1(a,b) &amp; ((b)-(a))))\n#define MIN4(a,b) ((b)+(H1(a,b) &amp; ((a)-(b))))\n//#define MIN5(a,b) ((a)&lt;(b)?(a):(b))\n//#define MIN6(a,b) ((a)&gt;(b)?(b):(a))\n//#define MIN7(a,b) ((b)&gt;(a)?(a):(b))\n//#define MIN8(a,b) ((b)&lt;(a)?(b):(a))\n\n#define MAX1(a,b) ((a)+(H1(a,b) &amp; ((b)-(a))))\n#define MAX2(a,b) ((a)-(H1(a,b) &amp; ((a)-(b))))\n#define MAX3(a,b) ((b)-(H1(b,a) &amp; ((b)-(a))))\n#define MAX4(a,b) ((b)+(H1(b,a) &amp; ((a)-(b))))\n//#define MAX5(a,b) ((a)&lt;(b)?(b):(a))\n//#define MAX6(a,b) ((a)&gt;(b)?(a):(b))\n//#define MAX7(a,b) ((b)&gt;(a)?(b):(a))\n//#define MAX8(a,b) ((b)&lt;(a)?(a):(b))\n\n#define ABS1(a) (((a)^H0(a))-H0(a))\n//#define ABS2(a) ((a)&gt;0?(a):-(a))\n//#define ABS3(a) ((a)&gt;=0?(a):-(a))\n//#define ABS4(a) ((a)&lt;0?-(a):(a))\n//#define ABS5(a) ((a)&lt;=0?-(a):(a))\n</code></pre>\n\n<p>cheers</p>\n" }, { "answer_id": 19205123, "author": "mkny", "author_id": 2055965, "author_profile": "https://Stackoverflow.com/users/2055965", "pm_score": -1, "selected": false, "text": "<pre><code>int max(int a, int b)\n{\n return ((a - b) &gt;&gt; 31) ? b : a;\n}\n</code></pre>\n" }, { "answer_id": 66017995, "author": "giokoguashvili", "author_id": 5200896, "author_profile": "https://Stackoverflow.com/users/5200896", "pm_score": 0, "selected": false, "text": "<p>This is my implementation on C# using only <code>+, -, *, %, /</code> operators</p>\n<pre><code>using static System.Console;\n\nint Max(int a, int b) =&gt; (a + b + Abs(a - b)) / 2;\nint Abs(int x) =&gt; x * ((2 * x + 1) % 2);\n\nWriteLine(Max(-100, -2) == -2); // true\nWriteLine(Max(2, -100) == 2); // true\n</code></pre>\n" }, { "answer_id": 66018533, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 1, "selected": false, "text": "<p>These functions use comparisons but no tests and are fully defined on Standard compliant systems:</p>\n<pre><code>int min(int a, int b) {\n return (a &lt;= b) * a + (b &lt; a) * b;\n}\nint max(int a, int b) {\n return (a &lt;= b) * b + (b &lt; a) * a;\n}\n</code></pre>\n<p>Here is an alternative without multiplications, portable to systems that use two's complement for negative numbers:</p>\n<pre><code>int min(int a, int b) {\n return (a &amp; -(a &lt;= b)) | (b &amp; -(b &lt; a));\n}\nint max(int a, int b) {\n return (b &amp; -(a &lt;= b)) | (a &amp; -(b &lt; a));\n}\n</code></pre>\n<p>Both versions work for all integer types.</p>\n<p>Note that both <strong>gcc</strong> and <strong>clang</strong> generate branchless code for the above functions, and <strong>clang</strong> generates the same optimal code for both alternatives as can be seen on this <a href=\"https://godbolt.org/z/dG5zsP\" rel=\"nofollow noreferrer\">Godbolt Compiler Explorer session</a>.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
How do I programmatically return the maximum of two integers without using any comparison operators and without using `if`, `else`, etc?
max: // Will put MAX(a,b) into a ``` a -= b; a &= (~a) >> 31; a += b; ``` And: int a, b; min: // Will put MIN(a,b) into a ``` a -= b; a &= a >> 31; a += b; ``` from [here](http://web.archive.org/web/20130821015554/http://bob.allegronetwork.com/prog/tricks.html).
227,417
<p>I've run across the following line in a VB6 application.</p> <pre><code>mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight </code></pre> <p>Unfortunately Google and other search engines have not been very useful as they seem to omit the := part. </p> <p>What would be a C# equivalent?</p>
[ { "answer_id": 227431, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": true, "text": "<p>This is Visual Basic syntax for optional named parameters. The <code>Insert</code> function has a parameter named <code>Shift</code>, which is being specified.</p>\n\n<p>C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the <code>Insert</code> method, specifying <code>Type.Missing</code> for all parameters other than <code>Shift</code>.</p>\n\n<p>See also the following StackOverflow question: <a href=\"https://stackoverflow.com/questions/204877/vbnet-operator\">VB.NET := Operator</a></p>\n\n<p>UPDATE (2008-10-29):</p>\n\n<p>C# 4.0 is set to introduce optional and named parameters. See this <a href=\"http://codebetter.com/blogs/matthew.podwysocki/archive/2008/10/28/named-and-optional-arguments-in-c-4-0.aspx\" rel=\"nofollow noreferrer\">blog entry on codebetter.com</a>.</p>\n" }, { "answer_id": 227448, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 2, "selected": false, "text": "<p>VB6 and VB.net has optional parameters in method.\nc# has the option to do method overloading.</p>\n\n<p>VB6/VB.net way of saying Shift:=xlToRight allows passing value of a specific parameter by name.</p>\n\n<p>e.g. \npublic sub mymethod(optional a as integer = -1, optional b as integer=1)\n...\nend sub</p>\n\n<p>I can call this method with mymethod(b:=10)</p>\n\n<p>For c#, there could be 2 methods for this<br></p>\n\n<pre>\n<code>\nvoid Shift()\n{\ndefaultDirection = directionEnum.Left;\nShift(defaultDirection);\n}\n\nvoid Shift(directionEnum direction)\n{\n}\n</code>\n</pre>\n\n<p>1 more thing.\nAlthough you can call method just by passing parameters, adding parameter name when calling makes code a little more readable.<br>\ne.g. DoSomethingWithData(CustomerData:= customer, SortDirection:=Ascending)</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 227468, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 1, "selected": false, "text": "<p>It's really all about Excel and how it handles inserts. If you select a range of cells and right-click Insert you will be asked which direction to shift the cells. This is from the Excel Help:</p>\n\n<p>=======</p>\n\n<p>Insert Method on Range Object</p>\n\n<p>Inserts a cell or a range of cells into the worksheet or macro sheet and shifts other cells away to make space.</p>\n\n<p>expression.Insert(Shift, CopyOrigin)</p>\n\n<p>expression Required. An expression that returns a Range object.</p>\n\n<p>Shift Optional Variant. Specifies which way to shift the cells. Can be one of the following XlInsertShiftDirection constants: xlShiftToRight or xlShiftDown. If this argument is omitted, Microsoft Excel decides based on the shape of the range.</p>\n\n<p>CopyOrigin Optional Variant. The copy origin.</p>\n\n<p>===========</p>\n\n<p>If you don't have the constants defined you can subsitute the following numbers</p>\n\n<p>xlShiftDown: -4121\nxlShiftToLeft: -4159\nxlShiftToRight: -4161\nxlShiftUp: -4162</p>\n" }, { "answer_id": 229167, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "<p>Just to clarify John Rudy's response. </p>\n\n<p>The sytax is optional (small 'o'), meaning you don't have to use it. In my experience, most VB6 coders don't use the syntax and instead prefer regular 'unnamed' parameters.</p>\n\n<p>If you do choose to use it, all subsequent paramters in the sub procedure call must be named.</p>\n\n<p>The named paramter syntax can be used on all parameters, whether or not the corresponding argument was declared using the VBA keyword <code>Optional</code> (capital 'O'). Consider, for example, this (slightly daft) VBA function with two parameters, one required and one <code>Optional</code>:</p>\n\n<pre><code>Private Function TimesTen( _\n ByVal Value As Long, _\n Optional ByVal Factor As Long = 10 _\n) As Long\n TimesTen = Value * Factor\nEnd Function\n</code></pre>\n\n<p>In VBA, I can call it using named parameters for the required parameter (the <code>Optional</code> paramter can simply be omitted in VBA, unlike in C#.NET for which <code>Type.Missing</code> must be used for all omitted <code>Optional</code> parameters):</p>\n\n<pre><code> MsgBox TimesTen(Value:=9)\n</code></pre>\n\n<p>If I wanted to call it with the parameters in the 'wrong' order (why??) I can achieve this using named parameters:</p>\n\n<pre><code> MsgBox TimesTen(Factor:=11, Value:=9)\n</code></pre>\n\n<p>Trying to use a regular 'unnamed' parameter call after a named one causes a compile error:</p>\n\n<pre><code> MsgBox TimesTen(Value:=9, 11)\n</code></pre>\n\n<p>So why do VBA coders use named parameters if VB6 coders rarely do, even though they use essentially the same language? I think it is because the VBA generated by the MS Office applications' macro recorder tends to (always?) generate named parameters and many VBA coders learn programming this way.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14177/" ]
I've run across the following line in a VB6 application. ``` mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight ``` Unfortunately Google and other search engines have not been very useful as they seem to omit the := part. What would be a C# equivalent?
This is Visual Basic syntax for optional named parameters. The `Insert` function has a parameter named `Shift`, which is being specified. C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the `Insert` method, specifying `Type.Missing` for all parameters other than `Shift`. See also the following StackOverflow question: [VB.NET := Operator](https://stackoverflow.com/questions/204877/vbnet-operator) UPDATE (2008-10-29): C# 4.0 is set to introduce optional and named parameters. See this [blog entry on codebetter.com](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/10/28/named-and-optional-arguments-in-c-4-0.aspx).
227,428
<p>I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information?</p> <p>MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data.</p> <p>Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?</p>
[ { "answer_id": 227451, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 3, "selected": false, "text": "<p>I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME)</p>\n\n<p>Just use \"YYYY-MM-DD HH:MM:SS\" for inserting in php: <code>date('Y-m-d H:i:s', $myTimeStampInSeconds);</code></p>\n\n<p>-edit in response to comments below here -</p>\n\n<ol>\n<li>for selected columns you can use <code>$timestamp = <a href=\"http://www.php.net/strtotime\" rel=\"nofollow noreferrer\">strtotime</a>( $yourColumnValue );</code></li>\n<li>i recommend storing in the databas native format because you can then use SQL to compare records using SQL date/time functions like DATEADD() etc.</li>\n</ol>\n" }, { "answer_id": 227508, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 5, "selected": true, "text": "<p>I would store the dates in the MS-SQL format to assist in using the date manipulation functions in T-SQL to their fullest. It's easier to write and read</p>\n\n<pre><code>SELECT * FROM Foo\nWHERE DateDiff(d,field1,now()) &lt; 1\n</code></pre>\n\n<p>Than to try and perform the equivalent operation by manipulating integers</p>\n\n<p>To convert a MsSQL date into a unix timestamp use dateDiff:</p>\n\n<pre><code>SELECT DATEDIFF(s,'1970-01-01 00:00:00',fieldName) as fieldNameTS\nFROM TableName\nWHERE fieldName between '10/1/2008' and '10/31/2008'\n</code></pre>\n\n<p>To Convert an Unix Timestamp into a MsSQL Date, you can either do it in PHP:</p>\n\n<pre><code>$msSQLDate = date(\"Y-m-d H:i:s\", $unixDate );\n</code></pre>\n\n<p>or in MsSQL</p>\n\n<pre><code>INSERT INTO TableName ( \n fieldName\n) VALUES (\n DATEADD(s,'1970-01-01 00:00:00', ? ) \n) \n</code></pre>\n\n<p>Where parameter one is int($unixDate)</p>\n" }, { "answer_id": 229308, "author": "yeradis", "author_id": 30715, "author_profile": "https://Stackoverflow.com/users/30715", "pm_score": 2, "selected": false, "text": "<p>Hello and good day for everyone</p>\n\n<p>Yes , might be thats the best way , store dates in db, they will take db format and you can format when you need as you wich</p>\n\n<p>But there is another one solution in the ISO-developed international date format, i mean ISO 8601.</p>\n\n<p>The international format defined by ISO (ISO 8601) tries to address all date problems by defining a numerical date system as follows: YYYY-MM-DD where</p>\n\n<p>YYYY is the year [all the digits, i.e. 2100]\nMM is the month [01 (January) to 12 (December)]\nDD is the day [01 to 31] depending on moths :P</p>\n\n<p>Using numerical dates does have also some pitfalls with regard to readability and usability it is not perfect.But ISO date format is, however, the best choice for a date representation that is universally (and accurately) understandable.</p>\n\n<p>Note that this format can also be used to represent precise date and time, with timezone information</p>\n\n<p>Here is a detailed information about ISO 8601:2000 </p>\n\n<p><a href=\"http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm\" rel=\"nofollow noreferrer\">http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm</a></p>\n\n<p>With no more....\nBye bye</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18986/" ]
I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information? MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data. Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?
I would store the dates in the MS-SQL format to assist in using the date manipulation functions in T-SQL to their fullest. It's easier to write and read ``` SELECT * FROM Foo WHERE DateDiff(d,field1,now()) < 1 ``` Than to try and perform the equivalent operation by manipulating integers To convert a MsSQL date into a unix timestamp use dateDiff: ``` SELECT DATEDIFF(s,'1970-01-01 00:00:00',fieldName) as fieldNameTS FROM TableName WHERE fieldName between '10/1/2008' and '10/31/2008' ``` To Convert an Unix Timestamp into a MsSQL Date, you can either do it in PHP: ``` $msSQLDate = date("Y-m-d H:i:s", $unixDate ); ``` or in MsSQL ``` INSERT INTO TableName ( fieldName ) VALUES ( DATEADD(s,'1970-01-01 00:00:00', ? ) ) ``` Where parameter one is int($unixDate)
227,430
<p>Here is my function (<strong>updated</strong>):</p> <pre><code>Public Shared Function shortenUrl(ByVal URL As String) As String Return shortenUrl(URL, 32) End Function Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String If URL.Length &gt; maxLength Then String.Format("{0}...{1}", URL.Substring(0, (maxLength / 2)), URL.Substring(URL.Length - ((maxLength / 2) - 3))) Else Return URL End If End Function </code></pre> <p>I fixed the problem where it didn't return <code>maxLength</code> chars because it didn't take into account the ellipses.</p> <hr> <p>It seems to me that it is too complicated; any suggestions, comments, concerns are more than welcome.</p>
[ { "answer_id": 227445, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": true, "text": "<p>Why not do this?</p>\n\n<pre><code>Public Shared Function shortenUrl(ByVal URL As String) As String\n Return shortenUrl(URL, 29)\nEnd Function\nPublic Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String\n If URL.Length &gt; maxLength Then\n Return String.Format(\"{0}...{1}\", URL.Substring(0, maxLength / 2),URL.Substring(URL.Length - (maxLength / 2)))\n Else\n Return URL\n End If\nEnd Function\n</code></pre>\n\n<p>That at least gets rid of all of the tempoary declarations</p>\n" }, { "answer_id": 227452, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 0, "selected": false, "text": "<pre><code>Public Shared Function shortenUrl(ByVal URL As String, Optional ByVal maxLength As Integer = 29) As String\n If URL.Length &gt; maxLength Then \n Return String.Format(\"{0}...{1}\", URL.Substring(0, maxLength / 2), URL.Substring(URL.Length - (maxLength / 2)))\n Else\n Return URL\n End If\nEnd Function\n</code></pre>\n\n<p>Not sure why people hate optional arguments so much. They do the exact same thing <em>and</em> expose to the user what value will be defaulted if they don't provide one.</p>\n" }, { "answer_id": 227671, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Well, I don't know if it's too complicated...but it is wrong. If I call shortenUrl(URL, 29) I'd expect the return would have a maximum length of 29 characters. Your code would give me 31. If I call it with a length of 30, I'll get back 33 characters. You're not including the inserted \"...\", and you're relying on rounding to get the substring lengths and dropping the remainder.</p>\n\n<p>I'd add some param validation, and change it to:</p>\n\n<pre><code>Public Function shortenUrl2(ByVal URL As String, ByVal maxLength As Integer) As String\n Const middle as String = \"...\"\n If maxLength &lt; 0 Then\n Throw New ArgumentOutOfRangeException(\"maxLength\", \"must be greater than or equal to 0\")\n ElseIf String.IsNullOrEmpty(URL) OrElse URL.Length &lt;= maxLength Then\n Return URL\n ElseIf maxLength &lt; middle.Length Then\n Return URL.Substring(0, maxLength)\n End If\n\n Dim left as String = URL.Substring(0, CType(Math.Floor(maxLength / 2), Integer))\n Dim right as String = URL.Substring(URL.Length - (maxLength - left.Length - middle.Length))\n\n Return left &amp; middle &amp; right\nEnd Function\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Here is my function (**updated**): ``` Public Shared Function shortenUrl(ByVal URL As String) As String Return shortenUrl(URL, 32) End Function Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String If URL.Length > maxLength Then String.Format("{0}...{1}", URL.Substring(0, (maxLength / 2)), URL.Substring(URL.Length - ((maxLength / 2) - 3))) Else Return URL End If End Function ``` I fixed the problem where it didn't return `maxLength` chars because it didn't take into account the ellipses. --- It seems to me that it is too complicated; any suggestions, comments, concerns are more than welcome.
Why not do this? ``` Public Shared Function shortenUrl(ByVal URL As String) As String Return shortenUrl(URL, 29) End Function Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String If URL.Length > maxLength Then Return String.Format("{0}...{1}", URL.Substring(0, maxLength / 2),URL.Substring(URL.Length - (maxLength / 2))) Else Return URL End If End Function ``` That at least gets rid of all of the tempoary declarations
227,434
<p>I have an XML schema that includes multiple addresses:</p> <pre><code>&lt;xs:element name="personal_address" maxOccurs="1"&gt; &lt;!-- address fields go here --&gt; &lt;/xs:element&gt; &lt;xs:element name="business_address" maxOccurs="1"&gt; &lt;!-- address fields go here --&gt; &lt;/xs:element&gt; </code></pre> <p>Within each address element, I include a "US State" enumeration:</p> <pre><code>&lt;xs:simpleType name="state"&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:enumeration value="AL" /&gt; &lt;xs:enumeration value="AK" /&gt; &lt;xs:enumeration value="AS" /&gt; .... &lt;xs:enumeration value="WY" /&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>How do I go about writing the "US State" enumeration once and re-using it in each of my address elements? I apologize in advance if this is a n00b question -- I've never written an XSD before.</p> <p>My initial stab at it is the following:</p> <pre><code>&lt;xs:element name="business_address" maxOccurs="1"&gt; &lt;!-- address fields go here --&gt; &lt;xs:element name="business_address_state" type="state" maxOccurs="1"&gt;&lt;/xs:element&gt; &lt;/xs:element&gt; </code></pre>
[ { "answer_id": 227522, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<p>I think you are on the right tracks. I think its more to do with XML namespaces. Try the following:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n targetNamespace=\"http://www.example.org/foo\"\n xmlns:tns=\"http://www.example.org/foo\"\n elementFormDefault=\"qualified\"&gt;\n &lt;xs:element name=\"business_address\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"business_address_state\"\n type=\"tns:state\" maxOccurs=\"1\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n &lt;xs:simpleType name=\"state\"&gt;\n &lt;xs:restriction base=\"xs:string\"&gt;\n &lt;xs:enumeration value=\"AL\" /&gt;\n &lt;xs:enumeration value=\"AK\" /&gt;\n &lt;xs:enumeration value=\"AS\" /&gt;\n &lt;xs:enumeration value=\"WY\" /&gt;\n &lt;/xs:restriction&gt;\n &lt;/xs:simpleType&gt;\n&lt;/xs:schema&gt;\n</code></pre>\n\n<p>Note that the type is <strong>tns:state</strong> not just <strong>state</strong></p>\n\n<p>And then this is how you would use it:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;business_address xmlns=\"http://www.example.org/foo\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.example.org/foo foo.xsd \"&gt;\n &lt;business_address_state&gt;AL&lt;/business_address_state&gt;\n&lt;/business_address&gt;\n</code></pre>\n\n<p>Notice that this XML uses a default namespace the same as the targetNamespace of the XSD</p>\n" }, { "answer_id": 232595, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 2, "selected": false, "text": "<p>While namespaces help keep schemas organized and prevent conflicts,\nit's not the namespace above that allows for the reuse,\nit's the placement of the type as an immediate child of the &lt;xs:schema&gt; root\nthat makes it a global type. (Usable within the namespace w/o the namespace qualifier and from anywhere that the tns namespace is visible w/ the tns: qualifier.)</p>\n\n<p>I prefer to construct my schemas following the \"Garden of Eden\" approach, which maximizes reuse of both elements and types (and can also facilitate external logical referencing of the carefully made unique type/element from, say, a data dictionary stored in a database. </p>\n\n<p>Note that while the \"Garden of Eden\" schema pattern offers the maximum reuse, it also involves the most work. At the bottom of this post, I've provided links to the other patterns covered in the blog series.</p>\n\n<p>&bull; <b>The Garden of Eden approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/05/10/416269.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/05/10/416269.aspx</a> <blockquote>\nUses a modular approach by defining all elements globally and like the Venetian Blind approach all type definitions are declared globally. Each element is globally defined as an immediate child of the node and its type attribute can be set to one of the named complex types. \n</blockquote></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xs:schema targetNamespace=\"TargetNamespace\" xmlns:TN=\"TargetNamespace\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\nelementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\"&gt;\n &lt;xs:element name=\"BookInformation\" type=\"BookInformationType\"/&gt;\n &lt;xs:complexType name=\"BookInformationType\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element ref=\"Title\"/&gt;\n &lt;xs:element ref=\"ISBN\"/&gt;\n &lt;xs:element ref=\"Publisher\"/&gt;\n &lt;xs:element ref=\"PeopleInvolved\" maxOccurs=\"unbounded\"/&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;xs:complexType name=\"PeopleInvolvedType\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"Author\"/&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;xs:element name=\"Title\"/&gt;\n &lt;xs:element name=\"ISBN\"/&gt;\n &lt;xs:element name=\"Publisher\"/&gt;\n &lt;xs:element name=\"PeopleInvolved\" type=\"PeopleInvolvedType\"/&gt;\n&lt;/xs:schema&gt;\n</code></pre>\n\n<blockquote>The advantage of this approach is that the schemas are reusable. Since both the elements and types are defined globally both are available for reuse. This approach offers the maximum amount of reusable content.\n\nThe disadvantages are the that the schema is verbose.\n\nThis would be an appropriate design when you are creating general libraries in which you can afford to make no assumptions about the scope of the schema elements and types and their use in other schemas particularly in reference to extensibility and modularity.</blockquote> \n\n<p><br/>Since every distinct type and element has a single global definition, these canonical particles/components can be related one-to-one to identifiers in a database. And while it may at first glance seem like a tiresome ongoing manual task to maintain the associations between the textual XSD particles/components and the database, SQL Server 2005 can in fact generate canonical schema component identifiers via the statement </p>\n\n<pre><code>CREATE XML SCHEMA COLLECTION\n</code></pre>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms179457.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/ms179457.aspx</a></p>\n\n<p>Conversely, to construct a schema from the canonical particles, SQL Server 2005 provides the </p>\n\n<pre><code>SELECT xml_schema_namespace function\n</code></pre>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms191170.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/ms191170.aspx</a></p>\n\n<p>ca·non·i·cal\n Related to Mathematics. (of an equation, coordinate, etc.) \n \"in simplest or standard form\"\n <a href=\"http://dictionary.reference.com/browse/canonical\" rel=\"nofollow noreferrer\">http://dictionary.reference.com/browse/canonical</a></p>\n\n<p>Other, easier to construct, but less resuable/more \"denormalized/redundant\" schema patterns include</p>\n\n<p>&bull; <b>The Russian Doll approach </b><a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/21/410486.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/21/410486.aspx</a> <blockquote>\nThe schema has one single global element - the root element. All other elements and types are nested progressively deeper giving it the name due to each type fitting into the one above it. Since the elements in this design are declared locally they will not be reusable through the import or include statements.</blockquote></p>\n\n<p>&bull; <b>The the Salami Slice approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/25/411809.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/25/411809.aspx</a> <blockquote>\nAll elements are defined globally but the type definitions are defined locally. This way other schemas may reuse the elements. With this approach, a global element with its locally defined type provide a complete description of the elements content. This information 'slice' is declared individually and then aggregated back together and may also be pieced together to construct other schemas.</blockquote></p>\n\n<p>&bull; <b>The Venetian Blind approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/29/413491.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/29/413491.aspx</a> <blockquote>\nSimilar to the Russian Doll approach in that they both use a single global element. The Venetian Blind approach describes a modular approach by naming and defining all type definitions globally (as opposed to the Salami Slice approach which declares elements globally and types locally). Each globally defined type describes an individual \"slat\" and can be reused by other components. In addition, all the locally declared elements can be namespace qualified or namespace unqualified (the slats can be \"opened\" or \"closed\") depending on the elementFormDefault attribute setting at the top of the schema.</blockquote></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I have an XML schema that includes multiple addresses: ``` <xs:element name="personal_address" maxOccurs="1"> <!-- address fields go here --> </xs:element> <xs:element name="business_address" maxOccurs="1"> <!-- address fields go here --> </xs:element> ``` Within each address element, I include a "US State" enumeration: ``` <xs:simpleType name="state"> <xs:restriction base="xs:string"> <xs:enumeration value="AL" /> <xs:enumeration value="AK" /> <xs:enumeration value="AS" /> .... <xs:enumeration value="WY" /> </xs:restriction> </xs:simpleType> ``` How do I go about writing the "US State" enumeration once and re-using it in each of my address elements? I apologize in advance if this is a n00b question -- I've never written an XSD before. My initial stab at it is the following: ``` <xs:element name="business_address" maxOccurs="1"> <!-- address fields go here --> <xs:element name="business_address_state" type="state" maxOccurs="1"></xs:element> </xs:element> ```
I think you are on the right tracks. I think its more to do with XML namespaces. Try the following: ``` <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/foo" xmlns:tns="http://www.example.org/foo" elementFormDefault="qualified"> <xs:element name="business_address"> <xs:complexType> <xs:sequence> <xs:element name="business_address_state" type="tns:state" maxOccurs="1" /> </xs:sequence> </xs:complexType> </xs:element> <xs:simpleType name="state"> <xs:restriction base="xs:string"> <xs:enumeration value="AL" /> <xs:enumeration value="AK" /> <xs:enumeration value="AS" /> <xs:enumeration value="WY" /> </xs:restriction> </xs:simpleType> </xs:schema> ``` Note that the type is **tns:state** not just **state** And then this is how you would use it: ``` <?xml version="1.0" encoding="UTF-8"?> <business_address xmlns="http://www.example.org/foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/foo foo.xsd "> <business_address_state>AL</business_address_state> </business_address> ``` Notice that this XML uses a default namespace the same as the targetNamespace of the XSD
227,438
<p>I'm attempting to determine the row length in bytes of a table by executing the following stored procedure:</p> <pre><code>CREATE TABLE #tmp ( [ID] int, Column_name varchar(640), Type varchar(640), Computed varchar(640), Length int, Prec int, Scale int, Nullable varchar(640), TrimTrailingBlanks varchar(640), FixedLenNullInSource varchar(640), Collation varchar(256) ) INSERT INTO #tmp exec sp_help MyTable SELECT SUM(Length) FROM #tmp DROP TABLE #tmp </code></pre> <p>The problem is that I don't know the table definition (data types, etc..) of the table returned by 'sp_help.'</p> <p>I get the following error:</p> <pre><code>Insert Error: Column name or number of supplied values does not match table definition. </code></pre> <p>Looking at the sp_help stored procedure does not give me any clues.</p> <p>What is the proper CREATE TABLE statement to insert the results of a sp_help?</p>
[ { "answer_id": 227463, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>I can't help you with creating a temp table to store sp_help information, but I can help you with calculating row lengths. Check out this <a href=\"http://msdn.microsoft.com/en-us/library/aa933068.aspx\" rel=\"nofollow noreferrer\">MSDN article</a>; it helps you calculate such based on the field lengths, type, etc. Probably wouldn't take too much to convert it into a SQL script you could reuse by querying against sysobjects, etc.</p>\n\n<p>EDIT:</p>\n\n<p>I'm redacting my offer to do a script for it. My way was nowhere near as easy as Vendoran's. :) </p>\n\n<p>As an aside, I take back what I said earlier about not being able to help with the temp table. I can: You can't do it. sp_help outputs seven rowsets, so I don't think you'll be able to do something as initially described in the original question. I think you're stuck using a different method to come up with it.</p>\n" }, { "answer_id": 227516, "author": "Vendoran", "author_id": 24666, "author_profile": "https://Stackoverflow.com/users/24666", "pm_score": 3, "selected": false, "text": "<p>How doing it this way instead? </p>\n\n<pre><code>CREATE TABLE tblShowContig\n(\n ObjectName CHAR (255),\n ObjectId INT,\n IndexName CHAR (255),\n IndexId INT,\n Lvl INT,\n CountPages INT,\n CountRows INT,\n MinRecSize INT,\n MaxRecSize INT,\n AvgRecSize INT,\n ForRecCount INT,\n Extents INT,\n ExtentSwitches INT,\n AvgFreeBytes INT,\n AvgPageDensity INT,\n ScanDensity DECIMAL,\n BestCount INT,\n ActualCount INT,\n LogicalFrag DECIMAL,\n ExtentFrag DECIMAL\n)\nGO\n\nINSERT tblShowContig\nEXEC ('DBCC SHOWCONTIG WITH TABLERESULTS')\nGO\n\nSELECT * from tblShowContig WHERE ObjectName = 'MyTable'\nGO\n</code></pre>\n" }, { "answer_id": 227592, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<p>-- Sum up lengths of all columns </p>\n\n<pre><code>select SUM(sc.length) \nfrom syscolumns sc \ninner join systypes st on sc.xtype = st.xtype \nwhere id = object_id('table')\n</code></pre>\n\n<p>-- Look at various items returned </p>\n\n<pre><code>select st.name, sc.* \nfrom syscolumns sc \ninner join systypes st on sc.xtype = st.xtype \nwhere id = object_id('table') \n</code></pre>\n\n<p>No guarantees though, but it appears to be the same length that appears in sp_help 'table'</p>\n\n<p>DISCLAIMER:\nNote that I read the article linked by John Rudy and in addition to the maximum sizes here you also need other things like the NULL bitmap to get the actual row size. Also the sizes here are maximum sizes. If you have a varchar column the actual size is less on most rows....</p>\n\n<p>Vendoran has a nice solution, but I do not see the maximum row size anywhere (based on table definition). I do see the average size and all sorts of allocation information which is exactly what you need to estimate DB size for most things.</p>\n\n<p>If you are interested in just what sp_help returns for length and adding it up, then I think (I'm not 100% sure) that the query to sysobjects returns those same numbers. Do they represent the full maximum row size? No, you are missing things like the NULL bitmap. Do they represent a realistic measure of your actual data? No. Again VARCHAR(500) does not take 500 bytes if you only are storing 100 characters. Also TEXT fields and other fields stored separately from the row do not show their actual size, just the size of the pointer.</p>\n" }, { "answer_id": 227664, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 0, "selected": false, "text": "<p>This will give you all the information you need</p>\n\n<pre><code>Select * into #mytables\nfrom INFORMATION_SCHEMA.columns\n\nselect * from #mytables\n\ndrop table #mytables\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>The answer I gave was incomplete <strong>NOT</strong> incorrect. If you look at the data returned you'd realize that you could write a query using case to calculate a rows size in bytes. It has all you need: the datatype|size|precision. BOL has the bytes used by each datatype.\nI will post the complete answer when I a chance. </p>\n" }, { "answer_id": 229661, "author": "user21826", "author_id": 21826, "author_profile": "https://Stackoverflow.com/users/21826", "pm_score": 2, "selected": false, "text": "<p>None of the aforementioned answers is correct or valid.</p>\n\n<p>The question is one of determining the number of bytes consumed per row by each column's data type.</p>\n\n<p>The only method(s) I have that work are:</p>\n\n<ol>\n<li><p>exec sp_help 'mytable' - then add up the Length field of the second result set (If working from Query Analyzer or Management Studio - simply copy and paste the result into a spreadsheet and do a SUM)</p></li>\n<li><p>Write a C# or VB.NET program that accesses the second resultset and sums the Length field of each row.</p></li>\n<li><p>Modify the code of sp_help.</p></li>\n</ol>\n\n<p>This cannot be done using Transact SQL and sp_help because there is no way to deal with multiple resultsets.</p>\n\n<p>FWIW: The table definitions of the resultsets can be found here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa933429(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa933429(SQL.80).aspx</a> </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21826/" ]
I'm attempting to determine the row length in bytes of a table by executing the following stored procedure: ``` CREATE TABLE #tmp ( [ID] int, Column_name varchar(640), Type varchar(640), Computed varchar(640), Length int, Prec int, Scale int, Nullable varchar(640), TrimTrailingBlanks varchar(640), FixedLenNullInSource varchar(640), Collation varchar(256) ) INSERT INTO #tmp exec sp_help MyTable SELECT SUM(Length) FROM #tmp DROP TABLE #tmp ``` The problem is that I don't know the table definition (data types, etc..) of the table returned by 'sp\_help.' I get the following error: ``` Insert Error: Column name or number of supplied values does not match table definition. ``` Looking at the sp\_help stored procedure does not give me any clues. What is the proper CREATE TABLE statement to insert the results of a sp\_help?
How doing it this way instead? ``` CREATE TABLE tblShowContig ( ObjectName CHAR (255), ObjectId INT, IndexName CHAR (255), IndexId INT, Lvl INT, CountPages INT, CountRows INT, MinRecSize INT, MaxRecSize INT, AvgRecSize INT, ForRecCount INT, Extents INT, ExtentSwitches INT, AvgFreeBytes INT, AvgPageDensity INT, ScanDensity DECIMAL, BestCount INT, ActualCount INT, LogicalFrag DECIMAL, ExtentFrag DECIMAL ) GO INSERT tblShowContig EXEC ('DBCC SHOWCONTIG WITH TABLERESULTS') GO SELECT * from tblShowContig WHERE ObjectName = 'MyTable' GO ```
227,440
<p>I have a Rails application that in the erb code, I use a select box. What I would like to do is reload the page passing the sort parameter. My controller already handles it, but I don't know how to reload the page with the selected value from my select box. Here is my code:</p> <pre><code>&lt;% @options = {:latest =&gt; 'lastest' , :alphabetical =&gt; 'alphabetical', :pricelow =&gt; 'price-low', :pricehigh =&gt;'pricehigh'} %&gt; &lt;%= select_tag 'sort[]', options_for_select(@options), :include_blank =&gt; true,:onchange =&gt; "location.reload('location?sort='+this.value)"%&gt; </code></pre>
[ { "answer_id": 227829, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 3, "selected": true, "text": "<p>Have you considered using an ajax call on your list box? If you have a method on your controller that returns just the sorted list, based on sort parameter, then you could do:</p>\n\n<pre><code>&lt;% @options = {:latest =&gt; 'lastest' , :alphabetical =&gt; 'alphabetical', :pricelow =&gt; 'price-low', :pricehigh =&gt;'pricehigh'} %&gt;\n&lt;%= select_tag 'sort[]', options_for_select(@options), :include_blank =&gt; true,:onchange =&gt; remote_function(:url =&gt; {:controller =&gt; 'your_controller', :action =&gt; 'list_sort_method'}, :with =&gt; \"'sort='+this.value\", :update =&gt; \"div_containing_list\") %&gt;\n</code></pre>\n" }, { "answer_id": 228988, "author": "Cameron McCloud", "author_id": 25484, "author_profile": "https://Stackoverflow.com/users/25484", "pm_score": 2, "selected": false, "text": "<p>If you don't want to use AJAX, then put a form_tag around your code.</p>\n\n<p>Take a look at the Redmine source code on <a href=\"http://redmine.rubyforge.org/svn/trunk\" rel=\"nofollow noreferrer\">http://redmine.rubyforge.org/svn/trunk</a>. The UsersController does something similar - there's a combo box that allows a filter. Selecting the combo reloads the page.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642/" ]
I have a Rails application that in the erb code, I use a select box. What I would like to do is reload the page passing the sort parameter. My controller already handles it, but I don't know how to reload the page with the selected value from my select box. Here is my code: ``` <% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %> <%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => "location.reload('location?sort='+this.value)"%> ```
Have you considered using an ajax call on your list box? If you have a method on your controller that returns just the sorted list, based on sort parameter, then you could do: ``` <% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %> <%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => remote_function(:url => {:controller => 'your_controller', :action => 'list_sort_method'}, :with => "'sort='+this.value", :update => "div_containing_list") %> ```
227,447
<p>When I use this code to output some XML I parsed (and modified) with <code>XmlParser</code></p> <pre><code>XmlParser parser = new XmlParser() def root = parser.parseText(feedUrl.toURL().text) def writer = new StringWriter() new XmlNodePrinter(new PrintWriter(writer)).print(root) println writer.toString() </code></pre> <p>the namespace declarations on the root node are not printed, even though they are there in the <code>toString()</code> of <em>root</em>... any ideas?</p>
[ { "answer_id": 228593, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 2, "selected": true, "text": "<p>It looks like it's denormalizing the output and including the namespace context along with the nodes that actually need the namespace context.</p>\n\n<p>For example, the webpage for this question comes in with creativeCommons namespace embedded:</p>\n\n<pre><code>&lt;feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:creativeCommons=\"http://backend.userland.com/creativeCommonsRssModule\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\"&gt;\n &lt;!-- snip --&gt;\n &lt;creativeCommons:license&gt;http://www.creativecommons.org/licenses/by-nc/2.5/rdf&lt;/creativeCommons:license&gt;\n &lt;!-- snip --&gt;\n&lt;/feed&gt;\n</code></pre>\n\n<p>When you output the xml using this script:</p>\n\n<pre><code>def root = new XmlParser().parseText(\"http://stackoverflow.com/feeds/question/227447\".toURL().text)\nprintln new XmlNodePrinter().print(root)\n</code></pre>\n\n<p>It ends up moving the namespace to the license node that needs that namespace. Not a huge deal in this case as there is only a single node in that namespace. If most of the XML were namespaced, it'd probably bloat things quite a bit more.</p>\n\n<pre><code>&lt;feed xmlns=\"http://www.w3.org/2005/Atom\"&gt;\n &lt;!-- snip --&gt;\n &lt;creativeCommons:license xmlns:creativeCommons=\"http://backend.userland.com/creativeCommonsRssModule\"&gt;\nhttp://www.creativecommons.org/licenses/by-nc/2.5/rdf\n &lt;/creativeCommons:license&gt;\n &lt;!-- snip --&gt;\n&lt;/feed&gt;\n</code></pre>\n\n<p>If you actually wanted the nodes normalized, you'd have to make some tweaks to the XmlNodePrinter to do 2 passes through the XML, first to gather all of the used namespaces and 2nd to output them at the top rather than within each namespaced node. The groovy source code is actually pretty readable and wouldn't be that hard to modify if you actually needed this.</p>\n" }, { "answer_id": 5012799, "author": "Damo", "author_id": 2955, "author_profile": "https://Stackoverflow.com/users/2955", "pm_score": 2, "selected": false, "text": "<p>I've just had the same problem and after a bit of fiddling I've found a workaround. </p>\n\n<p>You use the <strong><em>XmlSluper</em></strong> instead of the <strong><em>XmlParser</em></strong> and use <strong><em>StreamingMarkupBuilder</em></strong> instead of <strong><em>XmlNodePrinter</em></strong>. Then you take advantage of the closure in <strong>bind</strong> and use the <strong>mkp</strong> built-in variable to declare the namespaces.</p>\n\n<p>For example; using the source xml example of Ted's from above:</p>\n\n<pre><code>def root = new XmlSlurper().parseText(\"http://stackoverflow.com/feeds/question/227447\".toURL().text))\ndef outputBuilder = new StreamingMarkupBuilder()\nString result = XmlUtil.serialize(outputBuilder.bind {\n mkp.declareNamespace('':'http://www.w3.org/2005/Atom')\n mkp.declareNamespace('creativeCommons':'http://backend.userland.com/creativeCommonsRssModule')\n mkp.declareNamespace('re':'http://purl.org/atompub/rank/1.0')\n mkp.yield root }\n)\nprintln result\n</code></pre>\n\n<p>Results in : </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;feed xmlns:creativeCommons=\"http://backend.userland.com/creativeCommonsRssModule\" xmlns=\"http://www.w3.org/2005/Atom\" xmlns:re=\"http://purl.org/atompub/rank/1.0\"&gt;\n&lt;title type=\"text\"&gt;How do I print a groovy Node with namespace preserved? - Stack Overflow &lt;/title&gt;\n&lt;link rel=\"self\" type=\"application/atom+xml\" href=\"http://stackoverflow.com/feeds/question/227447\"/&gt;\n&lt;link rel=\"alternate\" type=\"text/html\" href=\"http://stackoverflow.com/questions/227447\"/&gt;\n&lt;subtitle&gt;most recent 30 from stackoverflow.com&lt;/subtitle&gt;\n&lt;updated&gt;2011-02-16T05:13:17Z&lt;/updated&gt;\n&lt;id&gt;http://stackoverflow.com/feeds/question/227447&lt;/id&gt;\n&lt;creativeCommons:license&gt;http://www.creativecommons.org/licenses/by-nc/2.5/rdf&lt;/creativeCommons:license&gt;\n&lt;entry&gt;\n&lt;id&gt;http://stackoverflow.com/questions/227447/how-do-i-print-a-groovy-node-with-namespace-preserved&lt;/id&gt;\n&lt;re:rank scheme=\"http://stackoverflow.com\"&gt;2&lt;/re:rank&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
When I use this code to output some XML I parsed (and modified) with `XmlParser` ``` XmlParser parser = new XmlParser() def root = parser.parseText(feedUrl.toURL().text) def writer = new StringWriter() new XmlNodePrinter(new PrintWriter(writer)).print(root) println writer.toString() ``` the namespace declarations on the root node are not printed, even though they are there in the `toString()` of *root*... any ideas?
It looks like it's denormalizing the output and including the namespace context along with the nodes that actually need the namespace context. For example, the webpage for this question comes in with creativeCommons namespace embedded: ``` <feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0"> <!-- snip --> <creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license> <!-- snip --> </feed> ``` When you output the xml using this script: ``` def root = new XmlParser().parseText("http://stackoverflow.com/feeds/question/227447".toURL().text) println new XmlNodePrinter().print(root) ``` It ends up moving the namespace to the license node that needs that namespace. Not a huge deal in this case as there is only a single node in that namespace. If most of the XML were namespaced, it'd probably bloat things quite a bit more. ``` <feed xmlns="http://www.w3.org/2005/Atom"> <!-- snip --> <creativeCommons:license xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"> http://www.creativecommons.org/licenses/by-nc/2.5/rdf </creativeCommons:license> <!-- snip --> </feed> ``` If you actually wanted the nodes normalized, you'd have to make some tweaks to the XmlNodePrinter to do 2 passes through the XML, first to gather all of the used namespaces and 2nd to output them at the top rather than within each namespaced node. The groovy source code is actually pretty readable and wouldn't be that hard to modify if you actually needed this.
227,449
<p>I'm fairly new to JavaScript. </p> <p>Given a local machine's folder path (Windows), I was wondering how you can extract the names of all the possible folders in the current path, without the knowledge of how many folders there are or what they are called.</p> <p>Thank you very much in advance.</p>
[ { "answer_id": 227458, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>You cannot do this via Javascript in a browser as the JS doesn't have that kind of access to the file system from a browser.</p>\n" }, { "answer_id": 227462, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "<p>If you're executing JavaScript in a web browser then you can't, because in this scenario JavaScript has no access to the local file system for security reasons.</p>\n" }, { "answer_id": 227488, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 1, "selected": false, "text": "<p>Assuming the script will execute in a context where it makes sense to try and access the local hard drives (e.g. in cscript or classic ASP), your best bet is the <a href=\"http://msdn.microsoft.com/en-us/library/d6dw7aeh(VS.85).aspx\" rel=\"nofollow noreferrer\">FileSystemObject</a>.</p>\n" }, { "answer_id": 227582, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>Here is a little script to get you started with FileSystemObject in conjuction with JScript:</p>\n\n<pre><code>var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\nvar shell = new ActiveXObject(\"WScript.Shell\");\nvar path = \"%ProgramFiles%\";\n\nvar programFiles = fso.GetFolder(shell.ExpandEnvironmentStrings(path));\nvar subFolders = new Enumerator(programFiles.SubFolders);\n\nwhile (!subFolders.atEnd())\n{\n var subFolder = subFolders.item();\n WScript.Echo(subFolder.Name);\n subFolders.moveNext();\n}\n</code></pre>\n\n<p>Call that with csript.exe on the command line:</p>\n\n<pre><code>cscript subfolders.js\n</code></pre>\n\n<p>The <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-207D-4BE1-8A76-1C4099D7BBB9&amp;displaylang=en\" rel=\"nofollow noreferrer\">Windows Script 5.6 Documentation</a> holds all the details you need on this topic (and many others). Download it and have it around, it is really helpful. On Windows systems, a little knowledge of FileSystemObject and it's relatives really can save the day.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm fairly new to JavaScript. Given a local machine's folder path (Windows), I was wondering how you can extract the names of all the possible folders in the current path, without the knowledge of how many folders there are or what they are called. Thank you very much in advance.
Here is a little script to get you started with FileSystemObject in conjuction with JScript: ``` var fso = new ActiveXObject("Scripting.FileSystemObject"); var shell = new ActiveXObject("WScript.Shell"); var path = "%ProgramFiles%"; var programFiles = fso.GetFolder(shell.ExpandEnvironmentStrings(path)); var subFolders = new Enumerator(programFiles.SubFolders); while (!subFolders.atEnd()) { var subFolder = subFolders.item(); WScript.Echo(subFolder.Name); subFolders.moveNext(); } ``` Call that with csript.exe on the command line: ``` cscript subfolders.js ``` The [Windows Script 5.6 Documentation](http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-207D-4BE1-8A76-1C4099D7BBB9&displaylang=en) holds all the details you need on this topic (and many others). Download it and have it around, it is really helpful. On Windows systems, a little knowledge of FileSystemObject and it's relatives really can save the day.
227,457
<p>I'm writing a query to summarize some data. I have a flag in the table that is basically boolean, so I need some sums and counts based on one value of it, and then the same thing for the other value, like so:</p> <pre><code>select location ,count(*) ,sum(duration) from my.table where type = 'X' and location = @location and date(some_tstamp) = @date group by location </code></pre> <p>And then the same for another value of the type column. If I join this table twice, how do I still group so I can only get aggregation for each table, i.e. count(a.<code>*</code>) instead of count(*)...</p> <p>Would it be better to write two separate queries?</p> <p><strong>EDIT</strong></p> <p>Thanks everybody, but that's not what I meant. I need to get a summary where type = 'X' and a summary where type = 'Y' separately...let me post a better example. What I meant was a query like this:</p> <pre><code>select a.location ,count(a.*) ,sum(a.duration) ,count(b.*) ,sum(b.duration) from my.table a, my.table b where a.type = 'X' and a.location = @location and date(a.some_tstamp) = @date and b.location = @location and date(b.some_tstamp) = @date and b.type = 'Y' group by a.location </code></pre> <p>What do I need to group by? Also, DB2 doesn't like count(a.<code>*</code>), it's a syntax error.</p>
[ { "answer_id": 227475, "author": "George Eadon", "author_id": 30530, "author_profile": "https://Stackoverflow.com/users/30530", "pm_score": 3, "selected": false, "text": "<p>Your example with the join doesn't make a lot of sense. You're doing a Cartesian product between A and B. Is this really what you want?</p>\n\n<p>The following will find count(*) and sum(duration) for each pair that satisfies the WHERE clause. Based on your description, this sounds like what you're looking for:</p>\n\n<pre><code>select\n type\n ,location\n ,count(*)\n ,sum(duration)\nfrom my.table\nwhere type IN ('X', 'Y')\n and location = @location\n and date(some_tstamp) = @date\ngroup by type, location\n</code></pre>\n" }, { "answer_id": 227502, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 4, "selected": true, "text": "<pre>\n<code>\nselect\n location\n ,Sum(case when type = 'X' then 1 else 0 end) as xCount\n ,Sum(case when type = 'Y' then 1 else 0 end) as YCount\n ,Sum(case when type = 'X' then duration else 0 end) as xCountDuration\n ,Sum(case when type = 'Y' then duration else 0 end) as YCountDuration\nfrom my.table\nwhere \nlocation = @location\n and date(some_tstamp) = @date\ngroup by location\n</code>\n</pre>\n\n<p>This should work in SQL Server. I guess db2 should have something similar.</p>\n\n<p>Edit: Add a where condition to limit the records to select type = X or type = Y, if \"type\" can have value other than X and Y. </p>\n" }, { "answer_id": 227751, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 1, "selected": false, "text": "<p>To make the counts work, instead of count(a.*) just do count(a.location), or any other not-null column (the PK would be ideal).</p>\n\n<p>As to the main question, either of the answers given by shahkalpesh or George Eadon above would work. There is no reason in this example to join the table twice.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13791/" ]
I'm writing a query to summarize some data. I have a flag in the table that is basically boolean, so I need some sums and counts based on one value of it, and then the same thing for the other value, like so: ``` select location ,count(*) ,sum(duration) from my.table where type = 'X' and location = @location and date(some_tstamp) = @date group by location ``` And then the same for another value of the type column. If I join this table twice, how do I still group so I can only get aggregation for each table, i.e. count(a.`*`) instead of count(\*)... Would it be better to write two separate queries? **EDIT** Thanks everybody, but that's not what I meant. I need to get a summary where type = 'X' and a summary where type = 'Y' separately...let me post a better example. What I meant was a query like this: ``` select a.location ,count(a.*) ,sum(a.duration) ,count(b.*) ,sum(b.duration) from my.table a, my.table b where a.type = 'X' and a.location = @location and date(a.some_tstamp) = @date and b.location = @location and date(b.some_tstamp) = @date and b.type = 'Y' group by a.location ``` What do I need to group by? Also, DB2 doesn't like count(a.`*`), it's a syntax error.
``` select location ,Sum(case when type = 'X' then 1 else 0 end) as xCount ,Sum(case when type = 'Y' then 1 else 0 end) as YCount ,Sum(case when type = 'X' then duration else 0 end) as xCountDuration ,Sum(case when type = 'Y' then duration else 0 end) as YCountDuration from my.table where location = @location and date(some_tstamp) = @date group by location ``` This should work in SQL Server. I guess db2 should have something similar. Edit: Add a where condition to limit the records to select type = X or type = Y, if "type" can have value other than X and Y.
227,459
<p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="noreferrer">ASCII</a> value of a character as an <code>int</code> in Python?</p>
[ { "answer_id": 227466, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 6, "selected": false, "text": "<p>You are looking for:</p>\n\n<pre><code>ord()\n</code></pre>\n" }, { "answer_id": 227472, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 12, "selected": true, "text": "<p>From <a href=\"http://mail.python.org/pipermail/python-win32/2005-April/003100.html\" rel=\"noreferrer\">here</a>:</p>\n<blockquote>\n<p>The function <strong><code>ord()</code></strong> gets the int value\nof the char. And in case you want to\nconvert back after playing with the\nnumber, function <strong><code>chr()</code></strong> does the trick.</p>\n</blockquote>\n<pre><code>&gt;&gt;&gt; ord('a')\n97\n&gt;&gt;&gt; chr(97)\n'a'\n&gt;&gt;&gt; chr(ord('a') + 3)\n'd'\n&gt;&gt;&gt;\n</code></pre>\n<p>In Python 2, there was also the <code>unichr</code> function, returning the <a href=\"http://en.wikipedia.org/wiki/Unicode\" rel=\"noreferrer\">Unicode</a> character whose ordinal is the <code>unichr</code> argument:</p>\n<pre><code>&gt;&gt;&gt; unichr(97)\nu'a'\n&gt;&gt;&gt; unichr(1234)\nu'\\u04d2'\n</code></pre>\n<p>In Python 3 you can use <code>chr</code> instead of <code>unichr</code>.</p>\n<hr>\n<p><a href=\"https://docs.python.org/3/library/functions.html#ord\" rel=\"noreferrer\">ord() - Python 3.6.5rc1 documentation</a></p>\n<p><a href=\"https://docs.python.org/2/library/functions.html#ord\" rel=\"noreferrer\">ord() - Python 2.7.14 documentation</a></p>\n" }, { "answer_id": 227889, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 8, "selected": false, "text": "<p>Note that <code>ord()</code> doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of <code>ord('ä')</code> can be 228 if you're using Latin-1, or it can raise a <code>TypeError</code> if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:</p>\n\n<pre><code>&gt;&gt;&gt; ord(u'あ')\n12354\n</code></pre>\n" }, { "answer_id": 36225223, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 6, "selected": false, "text": "<p>The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing: </p>\n\n<pre><code>for ch in mystr:\n code = ord(ch)\n</code></pre>\n\n<p>or the slightly faster:</p>\n\n<pre><code>for code in map(ord, mystr):\n</code></pre>\n\n<p>you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:</p>\n\n<pre><code>for code in mystr.encode('ascii'):\n</code></pre>\n\n<p>and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style <code>bytes</code> object (<code>bytes</code> is an alias for <code>str</code>, which iterates by character), but they do have <code>bytearray</code>:</p>\n\n<pre><code># If mystr is definitely str, not unicode\nfor code in bytearray(mystr):\n\n# If mystr could be either str or unicode\nfor code in bytearray(mystr, 'ascii'):\n</code></pre>\n\n<p>Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a <code>str</code> to get its ASCII codes using <code>map(ord, mystr)</code> starts off taking about twice as long for a <code>len</code> 10 <code>str</code> than using <code>bytearray(mystr)</code> on Py2 or <code>mystr.encode('ascii')</code> on Py3, and as the <code>str</code> gets longer, the multiplier paid for <code>map(ord, mystr)</code> rises to ~6.5x-7x.</p>\n\n<p>The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous <code>str</code> would have a proportionately large temporary <code>bytes</code>/<code>bytearray</code>, but unless this forces you into page thrashing, this isn't likely to matter.</p>\n" }, { "answer_id": 58654933, "author": "Indi", "author_id": 11893427, "author_profile": "https://Stackoverflow.com/users/11893427", "pm_score": 3, "selected": false, "text": "<p>To get the ASCII code of a character, you can use the <code>ord()</code> function.</p>\n\n<p>Here is an example code:</p>\n\n<pre><code>value = input(\"Your value here: \")\nlist=[ord(ch) for ch in value]\nprint(list)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Your value here: qwerty\n[113, 119, 101, 114, 116, 121]\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
How do I get the [ASCII](http://en.wikipedia.org/wiki/ASCII) value of a character as an `int` in Python?
From [here](http://mail.python.org/pipermail/python-win32/2005-April/003100.html): > > The function **`ord()`** gets the int value > of the char. And in case you want to > convert back after playing with the > number, function **`chr()`** does the trick. > > > ``` >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>> ``` In Python 2, there was also the `unichr` function, returning the [Unicode](http://en.wikipedia.org/wiki/Unicode) character whose ordinal is the `unichr` argument: ``` >>> unichr(97) u'a' >>> unichr(1234) u'\u04d2' ``` In Python 3 you can use `chr` instead of `unichr`. --- [ord() - Python 3.6.5rc1 documentation](https://docs.python.org/3/library/functions.html#ord) [ord() - Python 2.7.14 documentation](https://docs.python.org/2/library/functions.html#ord)
227,461
<p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p> <p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p> <pre><code>from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...some translation of f.read() open(filename, 'w').write(new_txt) </code></pre> <p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p> <p>Any other ideas ?</p>
[ { "answer_id": 227721, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>This seems to work:</p>\n\n<pre><code>with open(filename, \"r+\") as f:\n new_txt = process(f.read())\n f.truncate(0)\n f.write(new_txt)\n</code></pre>\n" }, { "answer_id": 227746, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code.</p>\n\n<p>See David M. Beazley's <a href=\"http://www.dabeaz.com/generators/\" rel=\"nofollow noreferrer\">Generator Tricks for Systems Programmers</a>, which is a really important thing for anyone who's writing this kind of code to read.</p>\n" }, { "answer_id": 227788, "author": "user26294", "author_id": 26294, "author_profile": "https://Stackoverflow.com/users/26294", "pm_score": 2, "selected": false, "text": "<p>If you're looking for the python equivalent of \"perl -pi\", here's a pretty good one:</p>\n\n<pre>\nimport fileinput\nfor line in fileinput.input():\n # process line\n</pre>\n\n<p>See <a href=\"http://www.python.org/doc/2.5.2/lib/module-fileinput.html\" rel=\"nofollow noreferrer\">http://www.python.org/doc/2.5.2/lib/module-fileinput.html</a> for more.</p>\n\n<p>Done this way, you would use your python script in a pipe to create the new file:</p>\n\n<pre>\n$ myscript.py infile.txt > outfile.txt\n</pre>\n" }, { "answer_id": 228858, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 1, "selected": false, "text": "<p>To do it in a way which won't <a href=\"http://www.linux.org.au/conf/2007/talk/278.html\" rel=\"nofollow noreferrer\">eat your data</a> if you crash in the middle:</p>\n\n<pre><code>from twisted.python.filepath import FilePath\np = FilePath(filename)\np.setContent(process(p.getContent()))\n</code></pre>\n" }, { "answer_id": 230416, "author": "Hortitude", "author_id": 16584, "author_profile": "https://Stackoverflow.com/users/16584", "pm_score": 6, "selected": true, "text": "<p>Actually an easier way using fileinput is to use the inplace parameter:</p>\n\n<pre><code>import fileinput\nfor line in fileinput.input (filenameToProcess, inplace=1):\n process (line)\n</code></pre>\n\n<p>If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file.</p>\n\n<p>This example adds line numbers to your file:</p>\n\n<pre><code>import fileinput\n\nfor line in fileinput.input (\"b.txt\",inplace=1):\n print \"%d: %s\" % (fileinput.lineno(),line),\n</code></pre>\n" }, { "answer_id": 344925, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 0, "selected": false, "text": "<p>My ugly (but short as stated in the question) solution with <a href=\"http://www.python.org/doc/2.5.2/ref/genexpr.html\" rel=\"nofollow noreferrer\">generator expressions</a>;</p>\n\n<pre><code># Some setup first\nfile('test.txt', 'w').write('\\n'.join('%05d' % i for i in range(100)))\n\n\n# This is the filter function\ndef f(i):\n return i % 3\n\n\n# This is the main part \nfile('test2.txt', 'w').write('\\n'.join(str(f(int(l))) for l in file('test.txt', 'r').readlines()))\n\n\n# And a wrapper for sanity\ndef filter_file(infile, outfile, filter_function)\n outfile.write('\\n'.join(filter_function(l) for l in infile.readlines()))\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
I want to do some basic filtering on a file. Read it, do processing, write it back. I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with: ``` from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...some translation of f.read() open(filename, 'w').write(new_txt) ``` The `with` statement makes things shorter since I don't have to explicitly open and close the file. Any other ideas ?
Actually an easier way using fileinput is to use the inplace parameter: ``` import fileinput for line in fileinput.input (filenameToProcess, inplace=1): process (line) ``` If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file. This example adds line numbers to your file: ``` import fileinput for line in fileinput.input ("b.txt",inplace=1): print "%d: %s" % (fileinput.lineno(),line), ```
227,470
<p>I have a search form on each of my pages. If I use form helper, it defaults to <code>$_POST</code>. I'd like the search term to show up in the URI:</p> <pre><code>http://example.com/search/KEYWORD </code></pre> <p>I've been on Google for about an hour, but to no avail. I've only found articles on how <code>$_GET</code> is basically disabled, because of the native URI convention. I can't be the first person to want this kind of functionality, am I? Thanks in advance!</p>
[ { "answer_id": 227494, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": -1, "selected": false, "text": "<p>I don't know much about CodeIgniter, but it's PHP, so shouldn't <code>$_GET</code> still be available to you? You could format your URL the same way Google does: <code>mysite.com/search?q=KEYWORD</code> and pull the data out with <code>$_GET['q']</code>.</p>\n\n<p>Besides, a search form seems like a bad place to use POST; GET is bookmarkable and doesn't imply that something is changing server-side.</p>\n" }, { "answer_id": 227496, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 2, "selected": false, "text": "<p>As far as I know, there is no method of accomplishing this with a simple POST. However, you can access the form via Javascript and update the destination. For example:</p>\n\n<pre><code>&lt;form id=\"myform\" onsubmit=\"return changeurl();\" method=\"POST\"&gt;\n&lt;input id=\"keyword\"&gt;\n&lt;/form&gt;\n\n&lt;script&gt;\nfunction changeurl()\n{\n var form = document.getElementById(\"myform\");\n var keyword = document.getElementById(\"keyword\");\n\n form.action = \"http://mysite.com/search/\"+escape(keyword.value);\n\n return true;\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 242432, "author": "muitocomplicado", "author_id": 23561, "author_profile": "https://Stackoverflow.com/users/23561", "pm_score": 0, "selected": false, "text": "<p>Check out this post on how to enable GET query strings together with segmented urls. </p>\n\n<p><a href=\"http://codeigniter.com/forums/viewthread/56389/#277621\" rel=\"nofollow noreferrer\">http://codeigniter.com/forums/viewthread/56389/#277621</a></p>\n\n<p>After enabling that you can use the following method to retrieve the additional variables.</p>\n\n<pre><code>// url = http://example.com/search/?q=text\n$this-&gt;input-&gt;get('q');\n</code></pre>\n\n<p>This is better because you don't need to change the permitted_uri_chars config setting. You may get \"The URI you submitted has disallowed characters\" error if you simply put anything the user enters in the URI. </p>\n" }, { "answer_id": 319525, "author": "Teej", "author_id": 37532, "author_profile": "https://Stackoverflow.com/users/37532", "pm_score": 4, "selected": true, "text": "<p>There's a better fix if you're dealing with people without JS enabled.</p>\n\n<p><strong>View:</strong></p>\n\n<pre><code>&lt;?php echo form_open('ad/pre_search');?&gt;\n &lt;input type=\"text\" name=\"keyword\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><strong>Controller</strong> </p>\n\n<pre><code>&lt;?php\n function pre_search()\n {\n redirect('ad/search/.'$this-&gt;input-&gt;post('keyword'));\n }\n\n function search()\n {\n // do stuff;\n }\n?&gt;\n</code></pre>\n\n<p>I have used this a lot of times before.</p>\n" }, { "answer_id": 3438630, "author": "Jimmy", "author_id": 414891, "author_profile": "https://Stackoverflow.com/users/414891", "pm_score": 0, "selected": false, "text": "<p>Here is the best solution:</p>\n\n<pre><code>$uri = $_SERVER['REQUEST_URI'];\n\n$pieces = explode(\"/\", $uri);\n\n$uri_3 = $pieces[3];\n</code></pre>\n\n<p>Thanks <a href=\"http://erunways.com\" rel=\"nofollow noreferrer\">erunways</a>!</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24708/" ]
I have a search form on each of my pages. If I use form helper, it defaults to `$_POST`. I'd like the search term to show up in the URI: ``` http://example.com/search/KEYWORD ``` I've been on Google for about an hour, but to no avail. I've only found articles on how `$_GET` is basically disabled, because of the native URI convention. I can't be the first person to want this kind of functionality, am I? Thanks in advance!
There's a better fix if you're dealing with people without JS enabled. **View:** ``` <?php echo form_open('ad/pre_search');?> <input type="text" name="keyword" /> </form> ``` **Controller** ``` <?php function pre_search() { redirect('ad/search/.'$this->input->post('keyword')); } function search() { // do stuff; } ?> ``` I have used this a lot of times before.
227,485
<p>I have a little demonstration below of a peculiar problem.</p> <pre><code>using System; using System.Windows.Forms; namespace WindowsApplication1 { public class TestForm : Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TextBox textBox1; public TestForm() { //Controls this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.textBox1 = new System.Windows.Forms.TextBox(); // tabControl1 this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(260, 240); this.tabControl1.TabIndex = 0; this.tabControl1.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabControl1_Selected); // tabPage1 this.tabPage1.Controls.Add(this.textBox1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(252, 214); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "tabPage1"; // tabPage2 this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(192, 74); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "tabPage2"; // textBox1 this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(6, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(240, 20); this.textBox1.TabIndex = 0; // TestForm this.ClientSize = new System.Drawing.Size(284, 264); this.Controls.Add(this.tabControl1); this.Name = "Form1"; this.Text = "Form1"; } //Tab Selected private void tabControl1_Selected(object sender, EventArgs e) { this.Text = "TextBox Width: " + this.textBox1.Width.ToString(); } } //Main static class Program { static void Main() { Application.Run(new TestForm()); } } } </code></pre> <p>If you run the above C# code you will have a small form containing a tabcontrol. Within the tabcontrol is a texbox on the first tab. If you follow these steps you will see the problem:</p> <ol> <li>Select tabPage2 (textBox1's width is reported in the form title)</li> <li>Resize the form</li> <li>Select tabPage1 (The wrong textBox1 width is reported)</li> </ol> <p>Any ideas what is going on here? The textbox is obviously bigger than what is being reported. If you click again on tabPage2 the correct size is then updated. Obviously there is an event updating the width of textBox1. Can i trigger this when tabPage1 is selected?</p>
[ { "answer_id": 227520, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": -1, "selected": false, "text": "<p>Not sure if I understand the problem.\nBut, you might use textbox's resize event to capture the width change OR form's resize.</p>\n\n<p>In your example, does the select event of tabPage1 fire when you do step 3?</p>\n" }, { "answer_id": 227525, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Firstly, thanks for the complete program - it made it <em>much</em> easier to work out what was going on!</p>\n\n<p>While the textbox isn't visible, it isn't resized. When you select tabPage1, the Selected event fires <em>before</em> the controls become visible and the textbox gets laid out again.</p>\n\n<p>Now, that's why it's happening - but what's your real situation? If you actually want to capture the size of controls changing, subscribe to their Resize events. If not, could you explain more about what you're trying to achieve?</p>\n" }, { "answer_id": 227528, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 1, "selected": false, "text": "<p>I'm pretty sure that what's happening is the <code>Selected</code> event is raised slightly before the tab page becomes visible. The text box is not resized until the tab page becomes visible, so you end up checking the value of the text box's size before it is actually resized. When you change tabs again, the text box is already resized, so you get the correct value.</p>\n\n<p>Change the last few lines of your example form to look like this and it will become apparent:</p>\n\n<pre><code> this.textBox1.SizeChanged += TextboxSizeChanged;\n }\n\n //Tab Selected\n private void tabControl1_Selected(object sender, EventArgs e)\n {\n System.Diagnostics.Debug.WriteLine(\"tab selected\");\n this.Text = \"TextBox Width: \" + this.textBox1.Width.ToString();\n }\n\n private void TextboxSizeChanged(object sender, EventArgs e)\n {\n System.Diagnostics.Debug.WriteLine(\"Textbox resized\");\n }</code></pre>\n" }, { "answer_id": 227565, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>If you modify your code a little by adding an event handler to the textbox1.Resize event you will see what happens. \nThe tabPage1.Selected event occurs before the controls in the tab page is resized so when you check the width of the textbox you are checking it before it is resized. </p>\n\n<p>Normally this wouldn't be a problem, for the resizing is done properly afterwards, but I guess that you will be using the size of the textbox for something?</p>\n\n<p>You should be able to write your own TabControl that fixes this problem, but you will have to experiment to see what works here.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
I have a little demonstration below of a peculiar problem. ``` using System; using System.Windows.Forms; namespace WindowsApplication1 { public class TestForm : Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TextBox textBox1; public TestForm() { //Controls this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.textBox1 = new System.Windows.Forms.TextBox(); // tabControl1 this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(260, 240); this.tabControl1.TabIndex = 0; this.tabControl1.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabControl1_Selected); // tabPage1 this.tabPage1.Controls.Add(this.textBox1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(252, 214); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "tabPage1"; // tabPage2 this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(192, 74); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "tabPage2"; // textBox1 this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(6, 38); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(240, 20); this.textBox1.TabIndex = 0; // TestForm this.ClientSize = new System.Drawing.Size(284, 264); this.Controls.Add(this.tabControl1); this.Name = "Form1"; this.Text = "Form1"; } //Tab Selected private void tabControl1_Selected(object sender, EventArgs e) { this.Text = "TextBox Width: " + this.textBox1.Width.ToString(); } } //Main static class Program { static void Main() { Application.Run(new TestForm()); } } } ``` If you run the above C# code you will have a small form containing a tabcontrol. Within the tabcontrol is a texbox on the first tab. If you follow these steps you will see the problem: 1. Select tabPage2 (textBox1's width is reported in the form title) 2. Resize the form 3. Select tabPage1 (The wrong textBox1 width is reported) Any ideas what is going on here? The textbox is obviously bigger than what is being reported. If you click again on tabPage2 the correct size is then updated. Obviously there is an event updating the width of textBox1. Can i trigger this when tabPage1 is selected?
Firstly, thanks for the complete program - it made it *much* easier to work out what was going on! While the textbox isn't visible, it isn't resized. When you select tabPage1, the Selected event fires *before* the controls become visible and the textbox gets laid out again. Now, that's why it's happening - but what's your real situation? If you actually want to capture the size of controls changing, subscribe to their Resize events. If not, could you explain more about what you're trying to achieve?
227,486
<p>Does anyone know how to programmaticly find out where the java classloader actually loads the class from? </p> <p>I often work on large projects where the classpath gets very long and manual searching is not really an option. I recently had a <a href="https://stackoverflow.com/questions/226280/eclipse-class-version-bug" title="problem">problem</a> where the classloader was loading an incorrect version of a class because it was on the classpath in two different places.</p> <p>So how can I get the classloader to tell me where on disk the actual class file is coming from?</p> <p><strong><em>Edit:</em></strong> What about if the classloader actually fails to load the class due to a version mismatch (or something else), is there anyway we could find out what file its trying to read before it reads it?</p>
[ { "answer_id": 227492, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "<p>Assuming that you're working with a class named <code>MyClass</code>, the following should work:</p>\n\n<pre><code>MyClass.class.getClassLoader();\n</code></pre>\n\n<p>Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself. For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.</p>\n" }, { "answer_id": 227498, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "<p>Take a look at this similar question.\n<a href=\"https://stackoverflow.com/questions/135971/is-there-a-tool-to-discover-if-the-same-class-exists-in-multiple-jars-in-the-cl#136292\"> Tool to discover same class..</a></p>\n\n<p>I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap ) </p>\n" }, { "answer_id": 227569, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>Here's an example:</p>\n\n<pre><code>package foo;\n\npublic class Test\n{\n public static void main(String[] args)\n {\n ClassLoader loader = Test.class.getClassLoader();\n System.out.println(loader.getResource(\"foo/Test.class\"));\n }\n}\n</code></pre>\n\n<p>This printed out:</p>\n\n<pre><code>file:/C:/Users/Jon/Test/foo/Test.class\n</code></pre>\n" }, { "answer_id": 227640, "author": "Dave DiFranco", "author_id": 30547, "author_profile": "https://Stackoverflow.com/users/30547", "pm_score": 7, "selected": false, "text": "<pre><code>getClass().getProtectionDomain().getCodeSource().getLocation();\n</code></pre>\n" }, { "answer_id": 227677, "author": "Jevgeni Kabanov", "author_id": 20022, "author_profile": "https://Stackoverflow.com/users/20022", "pm_score": 5, "selected": false, "text": "<p>This is what we use:</p>\n\n<pre><code>public static String getClassResource(Class&lt;?&gt; klass) {\n return klass.getClassLoader().getResource(\n klass.getName().replace('.', '/') + \".class\").toString();\n}\n</code></pre>\n\n<p>This will work depending on the ClassLoader implementation: \n<code>getClass().getProtectionDomain().getCodeSource().getLocation()</code></p>\n" }, { "answer_id": 228823, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 7, "selected": false, "text": "<p>Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: <code>-verbose:class</code></p>\n" }, { "answer_id": 19494116, "author": "OldCurmudgeon", "author_id": 823393, "author_profile": "https://Stackoverflow.com/users/823393", "pm_score": 4, "selected": false, "text": "<p>Jon's version fails when the object's <code>ClassLoader</code> is registered as <code>null</code> which seems to imply that it was loaded by the Boot <code>ClassLoader</code>.</p>\n\n<p>This method deals with that issue:</p>\n\n<pre><code>public static String whereFrom(Object o) {\n if ( o == null ) {\n return null;\n }\n Class&lt;?&gt; c = o.getClass();\n ClassLoader loader = c.getClassLoader();\n if ( loader == null ) {\n // Try the bootstrap classloader - obtained from the ultimate parent of the System Class Loader.\n loader = ClassLoader.getSystemClassLoader();\n while ( loader != null &amp;&amp; loader.getParent() != null ) {\n loader = loader.getParent();\n }\n }\n if (loader != null) {\n String name = c.getCanonicalName();\n URL resource = loader.getResource(name.replace(\".\", \"/\") + \".class\");\n if ( resource != null ) {\n return resource.toString();\n }\n }\n return \"Unknown\";\n}\n</code></pre>\n" }, { "answer_id": 29802725, "author": "ecerer", "author_id": 4820142, "author_profile": "https://Stackoverflow.com/users/4820142", "pm_score": 3, "selected": false, "text": "<p>Edit just 1st line: <code>Main</code>.class</p>\n\n<pre><code>Class&lt;?&gt; c = Main.class;\nString path = c.getResource(c.getSimpleName() + \".class\").getPath().replace(c.getSimpleName() + \".class\", \"\");\n\nSystem.out.println(path);\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>/C:/Users/Test/bin/\n</code></pre>\n\n<p>Maybe bad style but works fine!</p>\n" }, { "answer_id": 42238344, "author": "Adam", "author_id": 321772, "author_profile": "https://Stackoverflow.com/users/321772", "pm_score": 0, "selected": false, "text": "<p>This approach works for both files and jars:</p>\n\n<pre><code>Class clazz = Class.forName(nameOfClassYouWant);\n\nURL resourceUrl = clazz.getResource(\"/\" + clazz.getCanonicalName().replace(\".\", \"/\") + \".class\");\nInputStream classStream = resourceUrl.openStream(); // load the bytecode, if you wish\n</code></pre>\n" }, { "answer_id": 46856293, "author": "Hongyang", "author_id": 6090659, "author_profile": "https://Stackoverflow.com/users/6090659", "pm_score": 2, "selected": false, "text": "<p>Typically, we don't what to use hardcoding. We can get className first, and then use ClassLoader to get the class URL.</p>\n\n<pre><code> String className = MyClass.class.getName().replace(\".\", \"/\")+\".class\";\n URL classUrl = MyClass.class.getClassLoader().getResource(className);\n String fullPath = classUrl==null ? null : classUrl.getPath();\n</code></pre>\n" }, { "answer_id": 60120595, "author": "seduardo", "author_id": 476372, "author_profile": "https://Stackoverflow.com/users/476372", "pm_score": 1, "selected": false, "text": "<p>Simple way:</p>\n\n<blockquote>\n <p>System.out.println(java.lang.String.class.getResource(String.class.getSimpleName()+\".class\"));</p>\n</blockquote>\n\n<p>Out Example:</p>\n\n<blockquote>\n <p>jar:file:/D:/Java/jdk1.8/jre/lib/rt.jar!/java/lang/String.class</p>\n</blockquote>\n\n<p>Or</p>\n\n<blockquote>\n <p>String obj = \"simple test\";\n System.out.println(obj.getClass().getResource(obj.getClass().getSimpleName()+\".class\"));</p>\n</blockquote>\n\n<p>Out Example:</p>\n\n<blockquote>\n <p>jar:file:/D:/Java/jdk1.8/jre/lib/rt.jar!/java/lang/String.class</p>\n</blockquote>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25920/" ]
Does anyone know how to programmaticly find out where the java classloader actually loads the class from? I often work on large projects where the classpath gets very long and manual searching is not really an option. I recently had a [problem](https://stackoverflow.com/questions/226280/eclipse-class-version-bug "problem") where the classloader was loading an incorrect version of a class because it was on the classpath in two different places. So how can I get the classloader to tell me where on disk the actual class file is coming from? ***Edit:*** What about if the classloader actually fails to load the class due to a version mismatch (or something else), is there anyway we could find out what file its trying to read before it reads it?
Here's an example: ``` package foo; public class Test { public static void main(String[] args) { ClassLoader loader = Test.class.getClassLoader(); System.out.println(loader.getResource("foo/Test.class")); } } ``` This printed out: ``` file:/C:/Users/Jon/Test/foo/Test.class ```
227,500
<p>I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:</p> <pre><code>&lt;jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" /&gt; &lt;c:set var="pageDividers" value="&lt;%= pageBean.getPageDividers() %&gt;" /&gt; &lt;c:set var="numColumns" value="${pageDividers.size()}" /&gt; </code></pre> <p>The variable <code>pageDividers</code> is a <code>List</code> object.</p> <p>I'm encountering this issue: when I ask for <code>pageDivider</code>'s size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong?</p> <p>The error message is:</p> <blockquote> <p>The function size must be used with a prefix when a default namespace is not specified</p> </blockquote> <p>How do I correctly access or call the methods of my <code>pageDividers</code> object?</p>
[ { "answer_id": 227511, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "<p>To access the property of a bean using EL you simply name the property (not invoke the method). So lets say you have a method called getSize() in the bean then</p>\n\n<pre><code>${pageDividers.size}\n</code></pre>\n\n<p>Notice no ().</p>\n\n<p>EDIT:Sorry...made an error in the original post.</p>\n" }, { "answer_id": 227551, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 6, "selected": true, "text": "<p>When using the dot operator for property access in JSTL, <code>${pageDividers.size}</code> (no <strong>()</strong> needed) results in a call to a method named <code>getSize()</code>.<br>\nSince java.util.List offers a method called <code>size()</code> (rather than <code>getSize()</code>) you won't be able to access the list length by using that code.</p>\n\n<hr>\n\n<p>In order to access to a list size, JSTL offers the <strong>fn:length</strong> function, used like</p>\n\n<pre><code>${fn:length(pageDividers)}\n</code></pre>\n\n<p>Note that in order to use the <strong>fn</strong> namespace, you should declare it as follows</p>\n\n<pre><code>&lt;%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %&gt;\n</code></pre>\n\n<p>In addition, the same function can be used with any collection type, and with Strings too.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this: ``` <jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" /> <c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" /> <c:set var="numColumns" value="${pageDividers.size()}" /> ``` The variable `pageDividers` is a `List` object. I'm encountering this issue: when I ask for `pageDivider`'s size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong? The error message is: > > The function size must be used with a prefix when a default namespace is not specified > > > How do I correctly access or call the methods of my `pageDividers` object?
When using the dot operator for property access in JSTL, `${pageDividers.size}` (no **()** needed) results in a call to a method named `getSize()`. Since java.util.List offers a method called `size()` (rather than `getSize()`) you won't be able to access the list length by using that code. --- In order to access to a list size, JSTL offers the **fn:length** function, used like ``` ${fn:length(pageDividers)} ``` Note that in order to use the **fn** namespace, you should declare it as follows ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> ``` In addition, the same function can be used with any collection type, and with Strings too.
227,519
<p>I am writing a tool to help students learn regular expressions. I will probably be writing it in Java.</p> <p>The idea is this: the student types in a regular expression and the tool shows which parts of a text will get matched by the regex. Simple enough.</p> <p>But I want to support several different regex "flavors" such as:</p> <ul> <li>Basic regular expressions (think: grep)</li> <li>Extended regular expressions (think: egrep)</li> <li>A subset of Perl regular expressions, including the character classes \w, \s, etc.</li> <li>Sed-style regular expressions</li> </ul> <p>Java has the java.util.Regex class, but it supports only Perl-style regular expressions, which is a superset of the basic and extended REs. What I think I need is a way to take any given regular expression and escape the meta-characters that aren't part of a given flavor. Then I could give it to the Regex object and it would behave as if it was written for the selected RE interpreter.</p> <p>For example, given the following regex:</p> <pre><code>^\w+[0-9]{5}-(\d{4})?$ </code></pre> <p>As a basic regular expression, it would be interpreted as:</p> <pre><code>^\\w\+[0-9]\{5\}-\(\\d\{4\}\)\?$ </code></pre> <p>As an extended regular expression, it would be:</p> <pre><code>^\\w+[0-9]{5}-(\\d{4})?$ </code></pre> <p>And as a Perl-style regex, it would be the same as the original expression.</p> <p>Is there a "regular expression for regular expressions" than I could run through a regex search-and-replace to quote the non-meta characters? What else could I do? Are there alternative Java classes I could use?</p>
[ { "answer_id": 227534, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 1, "selected": false, "text": "<p>Alternatively, you could use <a href=\"http://jakarta.apache.org/oro/\" rel=\"nofollow noreferrer\">Jakarta ORO</a>?</p>\n\n<p>This supports the following regex 'flavors':</p>\n\n<ul>\n<li>Perl5 compatible regular expressions</li>\n<li>AWK-like regular expressions</li>\n<li>glob expressions</li>\n</ul>\n" }, { "answer_id": 227588, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 1, "selected": false, "text": "<p>check out this post for a 'regular expression for regular expressions': <a href=\"https://stackoverflow.com/questions/172303/is-there-a-regular-expression-to-detect-a-valid-regular-expression\">Is there a regular expression to detect a valid regular expression?</a></p>\n\n<p>You can use this as a basis for your module.</p>\n" }, { "answer_id": 227626, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<p>I have written something similar: <a href=\"https://stackoverflow.com/questions/172303/is-there-a-regular-expression-to-detect-a-valid-regular-expression#172316\">Is there a regular expression to detect a valid regular expression?</a></p>\n\n<p>You could take part of that expression, and match each token separatly:</p>\n\n<pre><code>[^?+*{}()[\\]\\\\] # literal characters\n\\\\[A-Za-z] # Character classes\n\\\\\\d+ # Back references\n\\\\\\W # Escaped characters\n\\[\\^?(?:\\\\.|[^\\\\])+?\\] # Character classs\n\\((?:\\?[:=!&gt;]|\\?&lt;[=!])? # Beginning of a group\n\\) # End of a group\n(?:[?+*]|\\{\\d+(?:,\\d*)?\\})\\?? # Repetition\n\\| # Alternation\n</code></pre>\n\n<p>For each match, you could have some dictionary of appropriate replacements in the target flavor.</p>\n" }, { "answer_id": 227690, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>if you want your students to learn regex,why not use a freely available tool -- regex Coach -- <a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">http://www.weitz.de/regex-coach/</a> on the net that is pretty good to learn and evaluate regexes ?</p>\n\n<p>look at this SO thread on a similar issue -- <a href=\"https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world\">https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world</a></p>\n\n<p>BR,<BR>\n~A</p>\n" }, { "answer_id": 2828802, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "<p>If your target is a Unix / Linux system, why just shell out to the definitive host of each regex? ie, use grep for BRE, egrep for ERE, perl for PCRE, etc? The only thing your module would need to do is the UI. Most of the regex testers that I have seen (that are decent) use a variant of this approach. </p>\n\n<p>If you want yet another library suggestion, look at <a href=\"http://laurikari.net/tre/about/\" rel=\"nofollow noreferrer\">TRE</a> for the BRE / ERE / POSIX / AWK part. It does not support back references, so PCRE / Python / Ruby / JS / Java is out...</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17312/" ]
I am writing a tool to help students learn regular expressions. I will probably be writing it in Java. The idea is this: the student types in a regular expression and the tool shows which parts of a text will get matched by the regex. Simple enough. But I want to support several different regex "flavors" such as: * Basic regular expressions (think: grep) * Extended regular expressions (think: egrep) * A subset of Perl regular expressions, including the character classes \w, \s, etc. * Sed-style regular expressions Java has the java.util.Regex class, but it supports only Perl-style regular expressions, which is a superset of the basic and extended REs. What I think I need is a way to take any given regular expression and escape the meta-characters that aren't part of a given flavor. Then I could give it to the Regex object and it would behave as if it was written for the selected RE interpreter. For example, given the following regex: ``` ^\w+[0-9]{5}-(\d{4})?$ ``` As a basic regular expression, it would be interpreted as: ``` ^\\w\+[0-9]\{5\}-\(\\d\{4\}\)\?$ ``` As an extended regular expression, it would be: ``` ^\\w+[0-9]{5}-(\\d{4})?$ ``` And as a Perl-style regex, it would be the same as the original expression. Is there a "regular expression for regular expressions" than I could run through a regex search-and-replace to quote the non-meta characters? What else could I do? Are there alternative Java classes I could use?
Alternatively, you could use [Jakarta ORO](http://jakarta.apache.org/oro/)? This supports the following regex 'flavors': * Perl5 compatible regular expressions * AWK-like regular expressions * glob expressions
227,552
<p>I am trying to debug a JavaScript script that gets read in a Firefox extension and executed. I only can see errors via the Firebug console (my code is invisible to Firebug), and it's reporting a "unterminated string literal." </p> <p>I checked the line and the lines around it and everything seems fine-parentheses, braces, and quotes are balanced, etc. What are other possible causes that I should be looking for?</p>
[ { "answer_id": 227561, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 3, "selected": false, "text": "<p>Look for a string which contains an unescaped single qoute that may be inserted by some server side code.</p>\n" }, { "answer_id": 227623, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": false, "text": "<p>You might try running the script through <a href=\"http://jslint.com/\" rel=\"noreferrer\">JSLint</a>.</p>\n" }, { "answer_id": 228129, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 0, "selected": false, "text": "<p>Try a \"binary search\". Delete half the code and try again. If the error is still there, delete half the remaining code. If the error is not there, put what you deleted back in, and delete half of that. Repeat. </p>\n\n<p>You should be able to narrow it down to a few line fairly quickly. My experience has been that at this point, you will notice some stupid malformed string.</p>\n\n<p>It may be expedient to perform this on a saved version of the HTML output to the browser, if you're not sure which server-side resource the error is in.</p>\n" }, { "answer_id": 228185, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>The web page developer guessed wrong about which encoding is used by the viewer's browser. This can usually be solved by specifying an encoding in the page's header.</p>\n" }, { "answer_id": 230318, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": false, "text": "<p>If you've done any cut/paste: some online syntax highlighters will mangle single and double quotes, turning them into formatted quote pairs (matched opening and closing pairs). (tho i can't find any examples right now)... So that entails hitting Command-+ a few times and staring at your quote characters</p>\n\n<p>Try a <a href=\"https://stackoverflow.com/questions/4689/recommended-fonts-for-programming\">different font?</a> also, different editors and IDEs use different tokenizers and highlight rules, and JS is one of more dynamic languages to parse, so try opening the file in emacs, vim, gedit (with JS plugins)... If you get lucky, one of them will show a long purple string running through the end of file. </p>\n" }, { "answer_id": 230426, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 0, "selected": false, "text": "<p>Scan the code that comes <em>before</em> the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.</p>\n" }, { "answer_id": 388368, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": 6, "selected": false, "text": "<p>Look for linebreaks! Those are often the cause. </p>\n" }, { "answer_id": 388588, "author": "meouw", "author_id": 12161, "author_profile": "https://Stackoverflow.com/users/12161", "pm_score": 2, "selected": false, "text": "<p>Have you escaped your forward slashes( / )?\nI've had trouble with those before</p>\n" }, { "answer_id": 1373122, "author": "VoY", "author_id": 6254, "author_profile": "https://Stackoverflow.com/users/6254", "pm_score": 7, "selected": true, "text": "<p>Most browsers seem to have problems with code like this:</p>\n\n<pre><code>var foo = \"&lt;/script&gt;\";\n</code></pre>\n\n<p>In Firefox, Opera and IE8 this results in an unterminated string literal error. Can be pretty nasty when serializing html code which includes scripts.</p>\n" }, { "answer_id": 2553580, "author": "Lea", "author_id": 83473, "author_profile": "https://Stackoverflow.com/users/83473", "pm_score": 0, "selected": false, "text": "<p>Whitespace is another issue I find, causes this error. Using a function to trim the whitespace may help.</p>\n" }, { "answer_id": 2553798, "author": "Álvaro González", "author_id": 13508, "author_profile": "https://Stackoverflow.com/users/13508", "pm_score": 1, "selected": false, "text": "<p>Have you tried <a href=\"http://getfirebug.com/downloads#chromebug\" rel=\"nofollow noreferrer\">Chromebug</a>? It's the Firebug for extensions.</p>\n" }, { "answer_id": 2923150, "author": "cbaigorri", "author_id": 265386, "author_profile": "https://Stackoverflow.com/users/265386", "pm_score": 2, "selected": false, "text": "<p>I've had trouble with angled quotes in the past ( ‘ ) usually from copy and pasting from Word. Replacing them with regular single quotes ( ' ) does the trick.</p>\n" }, { "answer_id": 4334841, "author": "Ipsoratio", "author_id": 527943, "author_profile": "https://Stackoverflow.com/users/527943", "pm_score": 2, "selected": false, "text": "<p>Maybe it's because you have a line break in your PHP code. If you need line breaks in your alert window message, include it as an escaped syntax at the end of each line in your PHP code. I usually do it the following way:</p>\n\n<pre><code>$message = 'line 1.\\\\n';\n$message .= 'line 2.';\n</code></pre>\n" }, { "answer_id": 5918844, "author": "PJ Brunet", "author_id": 722796, "author_profile": "https://Stackoverflow.com/users/722796", "pm_score": 5, "selected": false, "text": "<p>I would vote for jamtoday's answer if I had the \"reputation\"</p>\n\n<p>If your data is coming by way of PHP, this might help</p>\n\n<pre><code>$str = str_replace(array(\"\\r\", \"\\n\"), '', $str);\n</code></pre>\n" }, { "answer_id": 6624697, "author": "Tyndareus", "author_id": 835392, "author_profile": "https://Stackoverflow.com/users/835392", "pm_score": 2, "selected": false, "text": "<p>Also, keep in mind that %0A is the linefeed character URL encoded. It took me awhile to find where there was a linefeed in my offending code.</p>\n" }, { "answer_id": 7420855, "author": "Queue", "author_id": 945238, "author_profile": "https://Stackoverflow.com/users/945238", "pm_score": 4, "selected": false, "text": "<p>I just discovered that <code>\"&lt;\\/script&gt;\"</code> appears to work as well as <code>\"&lt;/scr\"+\"ipt&gt;\"</code>.</p>\n" }, { "answer_id": 8684425, "author": "Brian", "author_id": 1123591, "author_profile": "https://Stackoverflow.com/users/1123591", "pm_score": 4, "selected": false, "text": "<p>Just escape your tag closures or use ascii code</p>\n\n<p>ie</p>\n\n<pre><code>&lt;\\/script&gt;\n</code></pre>\n\n<p>ie</p>\n\n<pre><code>&lt;&amp;#47;script&gt;\n</code></pre>\n" }, { "answer_id": 9688136, "author": "Predte4a", "author_id": 1267014, "author_profile": "https://Stackoverflow.com/users/1267014", "pm_score": 2, "selected": false, "text": "<p>If nothing helps, look for some uni-code characters like</p>\n\n<pre><code>\\u2028\n</code></pre>\n\n<p>this may break your string on more than one line and throw this error</p>\n" }, { "answer_id": 13947608, "author": "Vishal Venugopal", "author_id": 1840974, "author_profile": "https://Stackoverflow.com/users/1840974", "pm_score": -1, "selected": false, "text": "<pre><code>str = str_replace(array(&quot;\\r\\n&quot;,&quot;\\n\\r&quot;,&quot;\\r&quot;, &quot;\\n&quot;), '&lt;br /&gt;', stripslashes($str));\n</code></pre>\n<p>This should work.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
I am trying to debug a JavaScript script that gets read in a Firefox extension and executed. I only can see errors via the Firebug console (my code is invisible to Firebug), and it's reporting a "unterminated string literal." I checked the line and the lines around it and everything seems fine-parentheses, braces, and quotes are balanced, etc. What are other possible causes that I should be looking for?
Most browsers seem to have problems with code like this: ``` var foo = "</script>"; ``` In Firefox, Opera and IE8 this results in an unterminated string literal error. Can be pretty nasty when serializing html code which includes scripts.
227,575
<p>Here is a snippet of the code :</p> <pre><code>HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request.RawUrl); WebRequest.DefaultWebProxy = null;//Ensure that we will not loop by going again in the proxy HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); string charSet = response.CharacterSet; Encoding encoding; if (String.IsNullOrEmpty(charSet)) encoding = Encoding.Default; else encoding = Encoding.GetEncoding(charSet); StreamReader resStream = new StreamReader(response.GetResponseStream(), encoding); return resStream.ReadToEnd(); </code></pre> <p>The problem is if I test with : <a href="http://www.google.fr" rel="noreferrer">http://www.google.fr</a></p> <p>All &quot;é&quot; are not displaying well. I have try to change ASCII to UTF8 and it still display wrong. I have tested the html file in a browser and the browser display the html text well so I am pretty sure the problem is in the method I use to download the html file.</p> <p>What should I change?</p> <p><em>removed dead ImageShack link</em></p> <h3>Update 1: Code and test file changed</h3>
[ { "answer_id": 227598, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Firstly, the easier way of writing that code is to use a StreamReader and ReadToEnd:</p>\n\n<pre><code>HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL);\nusing (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())\n{\n using (Stream resStream = response.GetResponseStream())\n {\n StreamReader reader = new StreamReader(resStream, Encoding.???);\n return reader.ReadToEnd();\n }\n}\n</code></pre>\n\n<p>Then it's \"just\" a matter of finding the right encoding. How did you create the file? If it's with Notepad then you probably want <code>Encoding.Default</code> - but that's obviously not portable, as it's the default encoding for <em>your</em> PC.</p>\n\n<p>In a well-run web server, the response will indicate the encoding in its headers. Having said that, response headers sometimes claim one thing and the HTML claims another, in some cases.</p>\n" }, { "answer_id": 4229277, "author": "Alex Dubinsky", "author_id": 513966, "author_profile": "https://Stackoverflow.com/users/513966", "pm_score": 5, "selected": false, "text": "<p>CharacterSet is \"ISO-8859-1\" by default, if it is not specified in server's content type header (different from \"charset\" meta tag in HTML).\nI compare HttpWebResponse.CharacterSet with charset attribute of HTML. If they are different - I use the charset as specified in HTML to re-read the page again, but with correct encoding this time.</p>\n\n<p>See the code: </p>\n\n<pre><code> string strWebPage = \"\";\n // create request\n System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(sURL);\n // get response\n System.Net.HttpWebResponse objResponse;\n objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();\n // get correct charset and encoding from the server's header\n string Charset = objResponse.CharacterSet;\n Encoding encoding = Encoding.GetEncoding(Charset);\n // read response\n using (StreamReader sr = \n new StreamReader(objResponse.GetResponseStream(), encoding))\n {\n strWebPage = sr.ReadToEnd();\n // Close and clean up the StreamReader\n sr.Close();\n }\n\n // Check real charset meta-tag in HTML\n int CharsetStart = strWebPage.IndexOf(\"charset=\");\n if (CharsetStart &gt; 0)\n {\n CharsetStart += 8;\n int CharsetEnd = strWebPage.IndexOfAny(new[] { ' ', '\\\"', ';' }, CharsetStart);\n string RealCharset = \n strWebPage.Substring(CharsetStart, CharsetEnd - CharsetStart);\n\n // real charset meta-tag in HTML differs from supplied server header???\n if(RealCharset!=Charset)\n {\n // get correct encoding\n Encoding CorrectEncoding = Encoding.GetEncoding(RealCharset);\n\n // read the web page again, but with correct encoding this time\n // create request\n System.Net.WebRequest objRequest2 = System.Net.HttpWebRequest.Create(sURL);\n // get response\n System.Net.HttpWebResponse objResponse2;\n objResponse2 = (System.Net.HttpWebResponse)objRequest2.GetResponse();\n // read response\n using (StreamReader sr = \n new StreamReader(objResponse2.GetResponseStream(), CorrectEncoding))\n {\n strWebPage = sr.ReadToEnd();\n // Close and clean up the StreamReader\n sr.Close();\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 9841920, "author": "Eddo", "author_id": 1288569, "author_profile": "https://Stackoverflow.com/users/1288569", "pm_score": 4, "selected": false, "text": "<p>In case you don't want to download the page twice, I slightly modified Alex's code using <a href=\"https://stackoverflow.com/questions/179676/how-do-i-put-a-webresponse-into-a-memory-stream\">How do I put a WebResponse into a memory stream?</a>. Here's the result</p>\n\n<pre><code>public static string DownloadString(string address)\n{\n string strWebPage = \"\";\n // create request\n System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(address);\n // get response\n System.Net.HttpWebResponse objResponse;\n objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();\n // get correct charset and encoding from the server's header\n string Charset = objResponse.CharacterSet;\n Encoding encoding = Encoding.GetEncoding(Charset);\n\n // read response into memory stream\n MemoryStream memoryStream;\n using (Stream responseStream = objResponse.GetResponseStream())\n {\n memoryStream = new MemoryStream();\n\n byte[] buffer = new byte[1024];\n int byteCount;\n do\n {\n byteCount = responseStream.Read(buffer, 0, buffer.Length);\n memoryStream.Write(buffer, 0, byteCount);\n } while (byteCount &gt; 0);\n }\n\n // set stream position to beginning\n memoryStream.Seek(0, SeekOrigin.Begin);\n\n StreamReader sr = new StreamReader(memoryStream, encoding);\n strWebPage = sr.ReadToEnd();\n\n // Check real charset meta-tag in HTML\n int CharsetStart = strWebPage.IndexOf(\"charset=\");\n if (CharsetStart &gt; 0)\n {\n CharsetStart += 8;\n int CharsetEnd = strWebPage.IndexOfAny(new[] { ' ', '\\\"', ';' }, CharsetStart);\n string RealCharset =\n strWebPage.Substring(CharsetStart, CharsetEnd - CharsetStart);\n\n // real charset meta-tag in HTML differs from supplied server header???\n if (RealCharset != Charset)\n {\n // get correct encoding\n Encoding CorrectEncoding = Encoding.GetEncoding(RealCharset);\n\n // reset stream position to beginning\n memoryStream.Seek(0, SeekOrigin.Begin);\n\n // reread response stream with the correct encoding\n StreamReader sr2 = new StreamReader(memoryStream, CorrectEncoding);\n\n strWebPage = sr2.ReadToEnd();\n // Close and clean up the StreamReader\n sr2.Close();\n }\n }\n\n // dispose the first stream reader object\n sr.Close();\n\n return strWebPage;\n}\n</code></pre>\n" }, { "answer_id": 14523486, "author": "Tony Zeng", "author_id": 2011224, "author_profile": "https://Stackoverflow.com/users/2011224", "pm_score": 0, "selected": false, "text": "<p>I studied the same problem with the help of WireShark, a great protocol analyser. I think that there are some design short coming to the httpWebResponse class. In fact, the whole message entity was downloaded the first time you invoking the GetResponse() method of the HttpWebRequest class, but the framework have no place to hold the data in the HttpWebResponse class or somewhere else, resulting you have to get the response stream the second time.</p>\n" }, { "answer_id": 34367416, "author": "Etienne Coumont", "author_id": 183084, "author_profile": "https://Stackoverflow.com/users/183084", "pm_score": 0, "selected": false, "text": "<p>There is still some problems when requesting the web page \"www.google.fr\" from a WebRequest.</p>\n\n<p>I checked the raw request and response with Fiddler. The problem comes from Google servers. The response HTTP headers are set to charset=ISO-8859-1, the text itself is encoded with ISO-8859-1, while the HTML says charset=UTF-8. This is incoherent and lead to encoding errors.</p>\n\n<p>After many tests, I managed to find a workaround. Just add :</p>\n\n<pre><code>myHttpWebRequest.UserAgent = \"Mozilla/5.0\";\n</code></pre>\n\n<p>to your code, and Google Response will magically and entirely become UTF-8.</p>\n" }, { "answer_id": 38650509, "author": "KinBread", "author_id": 4866150, "author_profile": "https://Stackoverflow.com/users/4866150", "pm_score": 1, "selected": false, "text": "<p>This is code that download one time.</p>\n\n<pre><code>String FinalResult = \"\";\nHttpWebRequest Request = (HttpWebRequest)System.Net.WebRequest.Create( URL );\nHttpWebResponse Response = (HttpWebResponse)Request.GetResponse();\nStream ResponseStream = Response.GetResponseStream();\nStreamReader Reader = new StreamReader( ResponseStream );\n\nbool NeedEncodingCheck = true;\n\nwhile( true )\n{\n string NewLine = Reader.ReadLine(); // it may not working for zipped HTML.\n if( NewLine == null )\n {\n break;\n }\n\n FinalResult += NewLine;\n FinalResult += Environment.NewLine;\n\n if( NeedEncodingCheck )\n {\n int Start = NewLine.IndexOf( \"charset=\" );\n if( Start &gt; 0 )\n {\n Start += \"charset=\\\"\".Length; \n int End = NewLine.IndexOfAny( new[] { ' ', '\\\"', ';' }, Start );\n\n Reader = new StreamReader( ResponseStream, Encoding.GetEncoding(\n NewLine.Substring( Start, End - Start ) ) ); // Replace Reader with new encoding.\n\n NeedEncodingCheck = false;\n }\n }\n}\n\nReader.Close();\nResponse.Close();\n</code></pre>\n" }, { "answer_id": 39458423, "author": "stephenr85", "author_id": 3363709, "author_profile": "https://Stackoverflow.com/users/3363709", "pm_score": 2, "selected": false, "text": "<p>There are some good solutions here, but they all seem to be trying to parse the charset out of the content type string. Here's a solution using System.Net.Mime.ContentType, which should be more reliable, and shorter.</p>\n\n<pre><code> var client = new System.Net.WebClient();\n var data = client.DownloadData(url);\n var encoding = System.Text.Encoding.Default;\n var contentType = new System.Net.Mime.ContentType(client.ResponseHeaders[HttpResponseHeader.ContentType]);\n if (!String.IsNullOrEmpty(contentType.CharSet))\n {\n encoding = System.Text.Encoding.GetEncoding(contentType.CharSet);\n }\n string result = encoding.GetString(data);\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
Here is a snippet of the code : ``` HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request.RawUrl); WebRequest.DefaultWebProxy = null;//Ensure that we will not loop by going again in the proxy HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); string charSet = response.CharacterSet; Encoding encoding; if (String.IsNullOrEmpty(charSet)) encoding = Encoding.Default; else encoding = Encoding.GetEncoding(charSet); StreamReader resStream = new StreamReader(response.GetResponseStream(), encoding); return resStream.ReadToEnd(); ``` The problem is if I test with : <http://www.google.fr> All "é" are not displaying well. I have try to change ASCII to UTF8 and it still display wrong. I have tested the html file in a browser and the browser display the html text well so I am pretty sure the problem is in the method I use to download the html file. What should I change? *removed dead ImageShack link* ### Update 1: Code and test file changed
Firstly, the easier way of writing that code is to use a StreamReader and ReadToEnd: ``` HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL); using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { using (Stream resStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(resStream, Encoding.???); return reader.ReadToEnd(); } } ``` Then it's "just" a matter of finding the right encoding. How did you create the file? If it's with Notepad then you probably want `Encoding.Default` - but that's obviously not portable, as it's the default encoding for *your* PC. In a well-run web server, the response will indicate the encoding in its headers. Having said that, response headers sometimes claim one thing and the HTML claims another, in some cases.
227,581
<p>I have a WPF app that makes use of a Winforms User Control that I have created using C++/CLI. When my app goes to parse the XAML for my main window, it throws an exception. The information appears to be somewhat abbreviated, but it says:</p> <pre><code>A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1) Error in markup file 'OsgViewer;component/osgviewerwin.xaml' Line 1 Position 9. </code></pre> <p>I commented out my Winforms control in the XAML and everything loads fine. I figured maybe the constructor for my control is doing something bad, so I put a breakpoint in it, but the breakpoint does not appear to be enabled when I start to run the app, and is never hit, which I understand to mean the DLL containing that line is not loaded. Which would most likely cause an exception to be thrown when an object of a type in the DLL is instantiated - the body of the object's constructor couldn't be found.</p> <p>I have done this successfully on a different project in the past, so I pulled in a different WinForms User Control from that app, and instantiated it in the XAML, and that all works fine.</p> <p>So it's something in this DLL. I have a reference to the DLL in my WPF C# app, and when I load the DLL in Object Browser all the required classes and namespaces show up fine. The app compiles fine, the problem just shows up when parsing the XAML. Anybody seen something like this? Any ideas as to what could be causing this? Ideas for debugging it? Thanks!</p> <pre><code>&lt;Window x:Class="OsgViewer.OsgViewerWin" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:int="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" xmlns:myns="clr-namespace:MyGlobalNS.MyNS;assembly=MyAssembly" ... &lt;int:WindowsFormsHost x:Name="m_Host"&gt; &lt;myns:CMyClass x:Name="m_MyClass" /&gt; &lt;/int:WindowsFormsHost&gt; ... &lt;/window&gt; </code></pre>
[ { "answer_id": 229060, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 4, "selected": true, "text": "<p>I have experienced problems like that (but not with the exact same error message). It seems as if WPF cannot instantiate your Winforms User Control.</p>\n\n<p>The challenge is to find out why. Here are my suggestions that you could try:</p>\n\n<ol>\n<li>Check if you have enabled unmanaged debugging (in Project Properties -> Debug)</li>\n<li>Find out if there are any dependencies your C++/CLI DLL where the Winforms control is implemented and if those dependencies cannot be resolved.<br/>\nIn order to find out dependencies on native DLLs, you should use the tool <a href=\"http://www.dependencywalker.com/\" rel=\"noreferrer\">Dependency Walker (depends.exe)</a>. .NET Reflector will only examine managed dependencies.</li>\n<li>Comment out code of your Winforms User Control step by step and try again.</li>\n<li>Use Gflags.exe to turn on <em>Loader Snaps</em> (cf. <a href=\"http://blogs.msdn.com/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx\" rel=\"noreferrer\">Debugging LoadLibrary Failures</a>)</li>\n</ol>\n" }, { "answer_id": 714548, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I also had this problem and all I had to do was go into the project properties>Security and click the This is a full trust application. I ran my project again and it worked!</p>\n" }, { "answer_id": 1135798, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Are you sure that you have the dll either in the system32 folder or in the same folder with the exe. I got the exactly same error message when running a WPF project built with CLI dll while the dll was located in the different folder.</p>\n\n<p>mike</p>\n" }, { "answer_id": 1632469, "author": "Nathan Monteleone", "author_id": 27130, "author_profile": "https://Stackoverflow.com/users/27130", "pm_score": 1, "selected": false, "text": "<p>I've seen this problem when trying to use boost::threads. To support thread-local storage, boost::threads makes some Win32 API call that is incompatible with CLI applications. The problem gets triggered if you try to #include something from threads in CLI code.</p>\n\n<p>Solution is to either avoid using boost::threads entirely or restrict its use to .cpp files in native code.</p>\n" }, { "answer_id": 6059125, "author": "Mats", "author_id": 761109, "author_profile": "https://Stackoverflow.com/users/761109", "pm_score": 1, "selected": false, "text": "<p>I had simular symptoms and my problem was that the C# project was set to use Any CPU while the C++ project was set to use x86. To set both to use x86 solved the problem</p>\n" }, { "answer_id": 15912393, "author": "a52", "author_id": 52474, "author_profile": "https://Stackoverflow.com/users/52474", "pm_score": 0, "selected": false, "text": "<p>I also had this execption message, but my solutions was changing the order of XAML elments. I was using a XmlDataProvider and displaying the content in a listbox. I just put the XmlDataProvider before the ListBox.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I have a WPF app that makes use of a Winforms User Control that I have created using C++/CLI. When my app goes to parse the XAML for my main window, it throws an exception. The information appears to be somewhat abbreviated, but it says: ``` A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1) Error in markup file 'OsgViewer;component/osgviewerwin.xaml' Line 1 Position 9. ``` I commented out my Winforms control in the XAML and everything loads fine. I figured maybe the constructor for my control is doing something bad, so I put a breakpoint in it, but the breakpoint does not appear to be enabled when I start to run the app, and is never hit, which I understand to mean the DLL containing that line is not loaded. Which would most likely cause an exception to be thrown when an object of a type in the DLL is instantiated - the body of the object's constructor couldn't be found. I have done this successfully on a different project in the past, so I pulled in a different WinForms User Control from that app, and instantiated it in the XAML, and that all works fine. So it's something in this DLL. I have a reference to the DLL in my WPF C# app, and when I load the DLL in Object Browser all the required classes and namespaces show up fine. The app compiles fine, the problem just shows up when parsing the XAML. Anybody seen something like this? Any ideas as to what could be causing this? Ideas for debugging it? Thanks! ``` <Window x:Class="OsgViewer.OsgViewerWin" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:int="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" xmlns:myns="clr-namespace:MyGlobalNS.MyNS;assembly=MyAssembly" ... <int:WindowsFormsHost x:Name="m_Host"> <myns:CMyClass x:Name="m_MyClass" /> </int:WindowsFormsHost> ... </window> ```
I have experienced problems like that (but not with the exact same error message). It seems as if WPF cannot instantiate your Winforms User Control. The challenge is to find out why. Here are my suggestions that you could try: 1. Check if you have enabled unmanaged debugging (in Project Properties -> Debug) 2. Find out if there are any dependencies your C++/CLI DLL where the Winforms control is implemented and if those dependencies cannot be resolved. In order to find out dependencies on native DLLs, you should use the tool [Dependency Walker (depends.exe)](http://www.dependencywalker.com/). .NET Reflector will only examine managed dependencies. 3. Comment out code of your Winforms User Control step by step and try again. 4. Use Gflags.exe to turn on *Loader Snaps* (cf. [Debugging LoadLibrary Failures](http://blogs.msdn.com/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx))
227,590
<p>For an iPhone app that submits images to a server I need somehow to tie all the images from a particular phone together. With every submit I'd like to send some unique phone id. Looked at <pre> [[UIDevice mainDevice] uniqueIdentifier]<br> and [[NSUserDefaults standardDefaults] stringForKey:@"SBFormattedPhoneNumber"] </pre></p> <p>but getting errors in the simulator.</p> <p>Is there an Apple sanctioned way of doing this?</p>
[ { "answer_id": 227606, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 0, "selected": false, "text": "<p>Haven't done iphone work, but how about taking a hash of something unique to the phone ... oh, say the phone number?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/193182/programmatically-get-own-phone-number-in-iphone-os\">Getting iphone number</a></p>\n" }, { "answer_id": 227654, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 6, "selected": true, "text": "<p>What errors are you getting? <code>[[UIDevice currentDevice] uniqueIdentifier]</code> (<i>edited to fix API, thanks Martin!</i>) is the officially recommended way of doing this.</p>\n" }, { "answer_id": 228230, "author": "Jason Harris", "author_id": 1345109, "author_profile": "https://Stackoverflow.com/users/1345109", "pm_score": 4, "selected": false, "text": "<p>You can also use CFUUID to generate a UUID. Here's some code:</p>\n\n<pre><code>NSString *uuid = nil;\nCFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);\nif (theUUID) {\n uuid = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID));\n [uuid autorelease];\n CFRelease(theUUID);\n}\n</code></pre>\n" }, { "answer_id": 260759, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 4, "selected": false, "text": "<p>By far the easiest and most appropriate way to obtain a unique identifier is to use the mechanisms Apple explicitly provides for obtaining one - <code>[[UIDevice currentDevice] uniqueIdentifier]</code>. You can not guarantee that the phone number will be unique to the device or that the device will even have a phone number. Beyond that, doing so is a horrible idea as it is a definite invasion of the user's privacy. Even the <code>uniqueidentifier</code> should be hashed if you are going to store it in any way.</p>\n" }, { "answer_id": 481338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This is an interesting problem that I am also looking into solving. Here is a scenario that I would like to address.</p>\n\n<p>What happens when you sell your phone to another person... that Device ID will then belong to somebody else, so even if the app is removed from the iPhone, it could be re-added and all that data would then be re-associated to a new user... this is bad.</p>\n\n<p>Using the Phone number with the Device ID MD5 would be a great solution. Another we came up with is having a SQL Lite DB with some token Hashed with the Device ID. Then when the app is removed the DB is killed and all the data is disassociated. I think that might be too brittle.</p>\n\n<p>Any other ideas?</p>\n\n<p>Rob Ellis (PhoneGap/Nitobi)</p>\n" }, { "answer_id": 1049473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>snippit:</p>\n\n<pre><code>NSString *phoneNumber = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:@\"SBFormattedPhoneNumber\"]; // Will return null in simulator!\nNSLog(@\"Formatted phone number [%@]\", phoneNumber);\n</code></pre>\n\n<p>I [recently] ran this code as-is on OS 2.2.1 [and OS 3.0].</p>\n\n<p>It works as expected when run on the device, and returns my phone number with the full international dialing codes [ 1 in my case].</p>\n\n<p>When run on the simulator, the value [returned] is a null string, so it only works on an actual iPhone device.</p>\n\n<p>I did not test it on an iPod Touch.</p>\n\n<p>...</p>\n\n<p>Ran this code on a different device this week, and got a null value instead of the number.</p>\n\n<p>On further research, it appears that the number returned by this code snippit is the number that is set up in iTunes for the device.</p>\n\n<p>If you didn’t enter the iPhone’s number in iTunes at device activation, or perhaps (as in my case) if the default value wasn’t the iPhone’s number and you clicked OK anyway, such that iTunes doesn’t list the phone number when your iPhone is plugged in, this code will return a null string.</p>\n\n<p>[Above is an edited concatenation of comments I recently posted to another article on this topic at <a href=\"http://www.alexcurylo.com/blog/2008/11/15/snippet-phone-number/]\" rel=\"nofollow noreferrer\">http://www.alexcurylo.com/blog/2008/11/15/snippet-phone-number/]</a></p>\n" }, { "answer_id": 1069764, "author": "Andrew Burns", "author_id": 3683, "author_profile": "https://Stackoverflow.com/users/3683", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.innerfence.com/howto/find-iphone-unique-device-identifier-udid\" rel=\"nofollow noreferrer\">Here</a> is some more information on a way to get it from iTunes which may be useful for testing purposes.</p>\n" }, { "answer_id": 1178227, "author": "Holtwick", "author_id": 140927, "author_profile": "https://Stackoverflow.com/users/140927", "pm_score": 0, "selected": false, "text": "<p>I had success with such code:</p>\n\n<pre><code>- (NSString *)stringUniqueID {\n NSString * result;\n CFUUIDRef uuid;\n CFStringRef uuidStr;\n uuid = CFUUIDCreate(NULL);\n assert(uuid != NULL);\n uuidStr = CFUUIDCreateString(NULL, uuid);\n assert(uuidStr != NULL);\n result = [NSString stringWithFormat:@\"%@\", uuidStr];\n assert(result != nil);\n NSLog(@\"UNIQUE ID %@\", result);\n CFRelease(uuidStr);\n CFRelease(uuid);\n return result;\n} \n</code></pre>\n" }, { "answer_id": 7143644, "author": "gN0Me", "author_id": 845958, "author_profile": "https://Stackoverflow.com/users/845958", "pm_score": 3, "selected": false, "text": "<p>Don't forget that in iOS 5 uniqueIdentifier will be deprecated you should use CFUUID instead of that</p>\n" }, { "answer_id": 7721021, "author": "Sam Stewart", "author_id": 151166, "author_profile": "https://Stackoverflow.com/users/151166", "pm_score": 3, "selected": false, "text": "<p>Interestingly, Apple has since deprecated the uniqueIdentifier in iOS 5 (as gN0Me mentioned). Here's the relevant TechCrunch article:\n<a href=\"http://techcrunch.com/2011/08/19/apple-ios-5-phasing-out-udid/\" rel=\"noreferrer\">http://techcrunch.com/2011/08/19/apple-ios-5-phasing-out-udid/</a> </p>\n\n<p>Apple suggests that you no longer uniquely identify the device but instead identify the <em>user</em>. In most cases, this is excellent advice though there are some situations which still require a <strong>globally</strong> unique device ID. These scenarios are quite common in advertising. Hence, I wrote an extremely simple drop-in library which replicates the existing behavior exactly. </p>\n\n<p>In a shameless plug of self promotion, I'll link it here in the hope that someone finds it useful. Also, I welcome all and any feedback/criticism:\n<a href=\"http://www.binpress.com/app/myid/591\" rel=\"noreferrer\">http://www.binpress.com/app/myid/591</a></p>\n\n<p>Nevertheless, in your particular situation I would advise skipping the <strong>globally</strong> unique ID functionality my library provides as it's a bit overkill for your situation. Instead, I would generate a simple CFUUID and store it in NSUserDefaults. This ID would be specific to your application but would allow you to group all the photos for that \"app install\" in your database. </p>\n\n<p>In other words, by deprecating the uniqueIdentifier method, Apple is suggesting that you don't identify per device but instead per app <em>install</em>. Unless you are operating under specific conditions, chances are the <em>per app</em> ID fits your product better anyway.</p>\n" }, { "answer_id": 8677052, "author": "Moomio", "author_id": 1122488, "author_profile": "https://Stackoverflow.com/users/1122488", "pm_score": 3, "selected": false, "text": "<p>In order to Persist the Unique Identifier you create between installations, you could use the Keychain <a href=\"https://github.com/samsoffes/sskeychain\">Made easy with SSKeychain</a>: Simply set your UUID as follows:</p>\n\n<pre><code> [SSKeychain setPassword:@\"Your UUID\" forService:@\"com.yourapp.yourcompany\" account:@\"user\"];\n</code></pre>\n\n<p>and then call it again anytime you need it:</p>\n\n<pre><code>NSString *retrieveuuid = [SSKeychain passwordForService:@\"com.yourapp.yourcompany\" account:@\"user\"];\n</code></pre>\n\n<p>Note: <strong>The services and accounts must match exactly</strong>.</p>\n\n<p>Then, if the App is deleted and reinstalled, the UUID will persist with reinstallation.</p>\n\n<p>If you then want to share this UUID across devices, set up your app to use iCloud. You can then store the UUID in NSUserDefaults, sync with KeyValueStore, and then set the UUID in the new devices keychain with the code above.</p>\n\n<p>This answer would get extremely long if I typed code for all the above, but plenty of sample code around here to figure it all out.</p>\n" }, { "answer_id": 12243860, "author": "James", "author_id": 1615938, "author_profile": "https://Stackoverflow.com/users/1615938", "pm_score": 0, "selected": false, "text": "<p>You can use MAC address as a unique id. Following link will help you</p>\n\n<p><a href=\"https://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone\">How can I programmatically get the MAC address of an iphone</a></p>\n" }, { "answer_id": 31259660, "author": "Karan Alangat", "author_id": 2226263, "author_profile": "https://Stackoverflow.com/users/2226263", "pm_score": 1, "selected": false, "text": "<p>Use Apple's GenericKeyChain which is the best solution . Here is the working sample >><a href=\"https://developer.apple.com/library/prerelease/ios/samplecode/GenericKeychain/Introduction/Intro.html\" rel=\"nofollow\">https://developer.apple.com/library/prerelease/ios/samplecode/GenericKeychain/Introduction/Intro.html</a></p>\n\n<p>Have idea about KeyChainAccess >><a href=\"https://developer.apple.com/library/mac/documentation/Security/Conceptual/keychainServConcepts/02concepts/concepts.html#//apple_ref/doc/uid/TP30000897-CH204-TP9\" rel=\"nofollow\">https://developer.apple.com/library/mac/documentation/Security/Conceptual/keychainServConcepts/02concepts/concepts.html#//apple_ref/doc/uid/TP30000897-CH204-TP9</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30541/" ]
For an iPhone app that submits images to a server I need somehow to tie all the images from a particular phone together. With every submit I'd like to send some unique phone id. Looked at ``` [[UIDevice mainDevice] uniqueIdentifier] and [[NSUserDefaults standardDefaults] stringForKey:@"SBFormattedPhoneNumber"] ``` but getting errors in the simulator. Is there an Apple sanctioned way of doing this?
What errors are you getting? `[[UIDevice currentDevice] uniqueIdentifier]` (*edited to fix API, thanks Martin!*) is the officially recommended way of doing this.
227,596
<p>This has been bugging me, I can't get my head around it. I will use the foodstuffs analogy to try and simplify my probelm.</p> <p>1000 members of the public where asked to pick a variety from each of 13 categories of footstuff. These selections were then stored in a mysql database against their name.</p> <pre><code>e.g. billy mary etc. etc. milk....semi. .skimmed... bread...white...brown.... cheese..edam.....edam.... fruit...apple...orange... veg....potato...sprout... meat....beef.....beef.... sweet..bonbons..liquorice.. fish...trout....salmon... crisp....s&amp;v....plain.... biscuit..hovis..rich tea.. wine.....red.....red..... beer....stella..carlsburg.. carb....coke.....pepsi.... </code></pre> <p>One of those 1000 was then asked to select anywhere from zero to 13 of their selections via checkboxes.</p> <p>By searching the database how many others selected the same varieties?</p> <p>Display in a table showing all their names and what they selected for all 13 varieties.</p> <p>Does that make sense? I hope so 'cause it's driving me mad.</p>
[ { "answer_id": 227779, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>partial answer:</p>\n\n<ul>\n<li>compose a linear set of selections by sorting and concatenating</li>\n<li>comparing then becomes a simple WHERE clause</li>\n</ul>\n\n<p>so you would first do a calculation run, putting strings into some field like \"milk|semi|skimmed\" literally.</p>\n" }, { "answer_id": 227794, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>Assuming you have a simple layout, then you would have something like this (I'll restrict myself to three of the categories):</p>\n\n<pre><code>PersonId What_Milk What_Bread What_Cheese\n 1 Semi Wheat Swiss\n 2 Skimmed Rolls French\n 3 Soy Brown Smelly\n 4 Low Fat Wheat Swiss\n</code></pre>\n\n<p>If I understood correctly, your problem is this:</p>\n\n<p>When the person 4 is asked to choose 0 .. 3 of her food items, she may select the \"Bread\" and the \"Cheese\" checkbox, which means the query should yield person 1 as a match. Right?</p>\n\n<pre><code>SELECT\n PersonId,\n What_Milk,\n What_Bread,\n What_Cheese\nFROM\n FoodPreference\nWHERE\n PersonId != ?\n AND What_Milk = IFNULL(NULLIF(?, ''), What_Milk)\n AND What_Bread = IFNULL(NULLIF(?, ''), What_Bread)\n AND What_Cheese = IFNULL(NULLIF(?, ''), What_Cheese)\n</code></pre>\n\n<p>Your checkbox values will later go where the question mark placeholders are. (<em>I've replaced the CASE WHEN constructs that used to be here with IFNULL/NULLIF, that has the same effect but is friendlier for PHP prepared statements.</em>)</p>\n\n<p>If a checkbox has not been checked (thus fixing the value to something), the corresponding column is compared to itself. That means it's value does not influence the result. If the other columns match, the row will be selected. </p>\n\n<p>That also means that if <em>zero</em> checkboxes are selected by the user, <em>all</em> rows will be returned. The more food items a person selects, the closer the match will be.</p>\n\n<p>In PHP, I'd recommend you use <code>mysqli_prepare()</code> to create a prepared statement from the query string, and <code>mysqli_stmt_bind_param()</code> to bind actual values to the question mark placeholders. That is much safer than building the SQL string directly. The <a href=\"http://de.php.net/manual/en/class.mysqli.php\" rel=\"nofollow noreferrer\">PHP documentation has a whole lot of info on mysqli</a>, have a look at it.</p>\n" }, { "answer_id": 227876, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT \n PersonId, \n milk, \n bread, \n cheese\nFROM FoodPreference\nWHERE PersonId != :chosen_person_id \n AND $milk= CASE WHEN :isset($_POST[\"milk\"]))&gt; '' THEN :isset($_POST[\"milk\"])) ELSE milk END \n AND $bread= CASE WHEN :isset($_POST[\"bread\"]))&gt; '' THEN :isset($_POST[\"bread\"])) ELSE bread END \n AND $cheese= CASE WHEN :isset($_POST[\"cheese\"]))&gt; '' THEN :isset($_POST[\"cheese\"])) ELSE cheese END\n</code></pre>\n\n<p>Am I on the right track?</p>\n" }, { "answer_id": 228037, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>Ok, I posted one response but Tomalak quite rightly pointed out a logical flaw. I'll try again:</p>\n\n<p>An alternative to listing the categories as thirteen columns is to list them as thirteen rows in a table like the following:</p>\n\n<pre><code>CREATE TABLE FoodPreference (\n PersonID INT NOT NULL REFERENCES People,\n FoodCat VARCHAR(10) NOT NULL REFERENCES FoodCategories,\n FoodChoice VARCHAR(10) NOT NULL,\n PRIMARY KEY (PersonID, FoodCat)\n);\nINSERT INTO FoodPreference VALUES\n (123, 'bread', 'white'),\n (123, 'milk', 'skim'),\n (123, 'cheese', 'edam'), ...\n (321, 'bread', 'brown'),\n (321, 'milk', 'whole'),\n (321, 'cheese', 'edam'), ...\n</code></pre>\n\n<p>Then you can use a query like the following, matching any row from the chosen person (p1) to a row with the same food choice from another person (p2) and from there to all the other choices of that person (p3):</p>\n\n<pre><code>SELECT DISTINCT p3.*\nFROM FoodPreference AS p1\n JOIN FoodPreference AS p2 \n ON (p1.FoodCat = p2.FoodCat AND p1.FoodChoice = p2.FoodChoice \n AND p1.PersonID != p2.PersonID)\n JOIN FoodPreference AS p3 \n ON (p2.PersonID = p3.PersonID AND p2.FoodCat != p3.FoodCat)\nWHERE p1.PersonID = {(int)$chosen_person_id}\n AND p1.FoodCat IN ('milk', 'bread', 'cheese');\n</code></pre>\n\n<p>The list 'milk', 'bread', 'cheese' in the WHERE clause is something you need to build in your PHP code, based on the <code>$_POST</code> variable in your application. If a checkbox is checked, include that food category in the list.</p>\n\n<pre><code>&lt;?php\n$food_cat_array = array(\"'none'\");\n$legal_food_cats = array('milk'=&gt;1, 'bread'=&gt;1, 'cheese'=&gt;1, ...);\nforeach (array_intersect_key($_POST, $legal_food_cats) as $key =&gt; $checked) {\n if ($checked) {\n $food_cat_array[] = \"'$key'\"; \n }\n}\n$in_predicate = join(',', $food_cat_array);\n</code></pre>\n" }, { "answer_id": 228249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>$sql = mysql_query(\" \n SELECT \n *\n FROM \".$prefix.\"_users\n WHERE username !='$username' \n AND req_country = IFNULL(NULLIF($bcountry, ''), req_country) \n AND req_region = IFNULL(NULLIF($bregion, ''), req_region) \n AND req_type = IFNULL(NULLIF($btype, ''), req_type)\n AND req_beds = IFNULL(NULLIF($bbeds, ''), req_beds)\n AND req_value = IFNULL(NULLIF($bvalue, ''), req_value)\n AND country = IFNULL(NULLIF($scountry, ''), country) \n AND region = IFNULL(NULLIF($sregion, ''), region) \n AND type = IFNULL(NULLIF($stype, ''), type)\n AND beds = IFNULL(NULLIF($sbeds, ''), beds)\n AND value = IFNULL(NULLIF($svalue, ''), value)\n AND pool = IFNULL(NULLIF($spool, ''), 'Yes')\n AND garage = IFNULL(NULLIF($sgarage, ''), &gt;0) \n AND disabled = IFNULL(NULLIF($sdisabled, ''), 'Yes')\");\n$num = mysql_num_rows($sql);\necho \"Total matches ($num): &lt;br&gt;&lt;br&gt;\";\n while($row = mysql_fetch_array($sql)){...etc\n</code></pre>\n" }, { "answer_id": 231941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>case \"display_results\":\n\nif ($bcountry = !isset($_POST[\"bcountry\"])){\n $bcountry = \"No\";\n }else {\n $bcountry = \"Yes\";\n }\nif ($bregion = !isset($_POST[\"bregion\"])){\n $bregion = \"No\";\n }else {\n $bregion = \"Yes\";\n }\nif ($btype = !isset($_POST[\"btype\"])){\n $btype = \"No\";\n }else {\n $btype = \"Yes\";\n }\nif ($bbeds = !isset($_POST[\"bbeds\"])){\n $bbeds = \"No\";\n }else {\n $bbeds = \"Yes\";\n }\nif ($bvalue = !isset($_POST[\"bvalue\"])){\n $bvalue = \"No\";\n }else {\n $bvalue = \"Yes\";\n }\nif ($scountry = !isset($_POST[\"scountry\"])){\n $scountry = \"No\";\n }else {\n $scountry = \"Yes\";\n }\nif ($sregion = !isset($_POST[\"sregion\"])){\n $sregion = \"No\";\n }else {\n $sregion = \"Yes\";\n }\nif ($stype = !isset($_POST[\"stype\"])){\n $stype = \"No\";\n }else {\n $stype = \"Yes\";\n }\nif ($sbeds = !isset($_POST[\"sbeds\"])){\n $sbeds = \"No\";\n }else {\n $sbeds = \"Yes\";\n }\nif ($svalue = !isset($_POST[\"svalue\"])){\n $svalue = \"No\";\n }else {\n $svalue = \"Yes\";\n }\nif ($spool = !isset($_POST[\"spool\"])){\n $spool = \"No\";\n }else {\n $spool = \"Yes\";\n }\nif ($sgarage = !isset($_POST[\"sgarage\"])){\n $sgarage = \"No\";\n }else {\n $sgarage = \"Yes\";\n }\nif ($sdisabled = !isset($_POST[\"sdisabled\"])){\n $sdisabled = \"No\";\n }else {\n $sdisabled = \"Yes\";\n }\n\n $result = mysql_query(\"SELECT * FROM \".$prefix.\"_users WHERE username!='$username' \nAND (('$bcountry'='Yes' AND req_country= '$country') OR ('$bcountry'='No')) \nAND (('$bregion'='Yes' AND req_region= '$region') OR ('$bregion'='No'))\nAND (('$btype'='Yes' AND req_type= '$type') OR ('$btype'='No'))\nAND (('$bbeds'='Yes' AND req_beds= '$beds') OR ('$bbeds'='No'))\nAND (('$bvalue'='Yes' AND req_value= '$value') OR ('$bvalue'='No'))\nAND (('$scountry'='Yes' AND country= '$req_country') OR ('$scountry'='No'))\nAND (('$sregion'='Yes' AND region= '$req_region') OR ('$sregion'='No'))\nAND (('$stype'='Yes' AND type= '$req_type') OR ('$stype'='No'))\nAND (('$sbeds'='Yes' AND beds= '$req_beds') OR ('$sbeds'='No'))\nAND (('$svalue'='Yes' AND value= '$req_value') OR ('$svalue'='No'))\nAND (('$spool'='Yes' AND pool= 'Yes') OR ('$spool'='No'))\nAND (('$sgarage'='Yes' AND garage&gt;=1 ) OR ('$sgarage'='No'))\nAND (('$sdisabled'='Yes' AND disabled= 'Yes') OR ('$sdisabled'='No'))\n\")or die(\"MySQL ERROR: \".mysql_error());\n$number = mysql_num_rows($result);\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This has been bugging me, I can't get my head around it. I will use the foodstuffs analogy to try and simplify my probelm. 1000 members of the public where asked to pick a variety from each of 13 categories of footstuff. These selections were then stored in a mysql database against their name. ``` e.g. billy mary etc. etc. milk....semi. .skimmed... bread...white...brown.... cheese..edam.....edam.... fruit...apple...orange... veg....potato...sprout... meat....beef.....beef.... sweet..bonbons..liquorice.. fish...trout....salmon... crisp....s&v....plain.... biscuit..hovis..rich tea.. wine.....red.....red..... beer....stella..carlsburg.. carb....coke.....pepsi.... ``` One of those 1000 was then asked to select anywhere from zero to 13 of their selections via checkboxes. By searching the database how many others selected the same varieties? Display in a table showing all their names and what they selected for all 13 varieties. Does that make sense? I hope so 'cause it's driving me mad.
Assuming you have a simple layout, then you would have something like this (I'll restrict myself to three of the categories): ``` PersonId What_Milk What_Bread What_Cheese 1 Semi Wheat Swiss 2 Skimmed Rolls French 3 Soy Brown Smelly 4 Low Fat Wheat Swiss ``` If I understood correctly, your problem is this: When the person 4 is asked to choose 0 .. 3 of her food items, she may select the "Bread" and the "Cheese" checkbox, which means the query should yield person 1 as a match. Right? ``` SELECT PersonId, What_Milk, What_Bread, What_Cheese FROM FoodPreference WHERE PersonId != ? AND What_Milk = IFNULL(NULLIF(?, ''), What_Milk) AND What_Bread = IFNULL(NULLIF(?, ''), What_Bread) AND What_Cheese = IFNULL(NULLIF(?, ''), What_Cheese) ``` Your checkbox values will later go where the question mark placeholders are. (*I've replaced the CASE WHEN constructs that used to be here with IFNULL/NULLIF, that has the same effect but is friendlier for PHP prepared statements.*) If a checkbox has not been checked (thus fixing the value to something), the corresponding column is compared to itself. That means it's value does not influence the result. If the other columns match, the row will be selected. That also means that if *zero* checkboxes are selected by the user, *all* rows will be returned. The more food items a person selects, the closer the match will be. In PHP, I'd recommend you use `mysqli_prepare()` to create a prepared statement from the query string, and `mysqli_stmt_bind_param()` to bind actual values to the question mark placeholders. That is much safer than building the SQL string directly. The [PHP documentation has a whole lot of info on mysqli](http://de.php.net/manual/en/class.mysqli.php), have a look at it.
227,608
<p>Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month.</p> <p>To do it manually, one could use:</p> <pre><code>String[] dateFields = dateString.split("/"); int month = Integer.parseInt(dateFields[0]); int day = Integer.parseInt(dateFields[1]); int year = Integer.parseInt(dateFields[2]); </code></pre> <p>And validate with:</p> <pre><code>dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d") </code></pre> <p>Is there a call to SimpleDateFormat or JodaTime that would handle this?</p>
[ { "answer_id": 227625, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": false, "text": "<p>Yep, use setLenient:</p>\n\n<pre><code>DateFormat df = new SimpleDateFormat(\"MM/dd/yyyy\");\ndf.setLenient(true);\nSystem.out.println(df.parse(\"05/05/1999\"));\nSystem.out.println(df.parse(\"5/5/1999\"));\n</code></pre>\n" }, { "answer_id": 228356, "author": "Ray Myers", "author_id": 2046, "author_profile": "https://Stackoverflow.com/users/2046", "pm_score": 2, "selected": true, "text": "<p>Looks like my problem was using \"MM/DD/yyyy\" when I should have used \"MM/dd/yyyy\". Uppercase <strong>D</strong> is \"Day in year\", while lowercase <strong>d</strong> is \"Day in month\".</p>\n\n<pre><code>new SimpleDateFormat(\"MM/dd/yyyy\").parse(dateString);\n</code></pre>\n\n<p>Does the job. Also, \"M/d/y\" works interchangeably. A closer reading of the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\">SimpleDateFormat API Docs</a> reveals the following:</p>\n\n<p>\"For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.\"</p>\n" }, { "answer_id": 33405835, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "<h1>java.time</h1>\n\n<p>Java 8 and later includes the java.time framework. This framework obsoletes the old java.util.Date/.Calendar classes discussed in the other answers here.</p>\n\n<p>The java.time.format package and its java.time.format.DateTimeFormatter class use pattern codes similar to that seen in the <a href=\"https://stackoverflow.com/a/228356/642706\">accepted Answer</a> by Ray Myers. While similar, they vary a bit. In particular they are strict about the number of repeated characters. If you say <code>MM</code>, then the month must have padded zero or else you get a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeParseException.html\" rel=\"nofollow noreferrer\">DateTimeParseException</a>. If the month number may or may not have a padding zero, simply use the single-character <code>M</code>.</p>\n\n<p>In this example code, note how the month number of the input string has a padding zero while the day-of-month number does not. Both are handled by the single-character pattern. </p>\n\n<pre><code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( \"M/d/yyyy\" );\nLocalDate localDate = formatter.parse ( \"01/2/2015\" , LocalDate :: from );\n</code></pre>\n\n<p>Dump to console.</p>\n\n<pre><code>System.out.println ( \"localDate: \" + localDate );\n</code></pre>\n\n<blockquote>\n <p>localDate: 2015-01-02</p>\n</blockquote>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046/" ]
Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month. To do it manually, one could use: ``` String[] dateFields = dateString.split("/"); int month = Integer.parseInt(dateFields[0]); int day = Integer.parseInt(dateFields[1]); int year = Integer.parseInt(dateFields[2]); ``` And validate with: ``` dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d") ``` Is there a call to SimpleDateFormat or JodaTime that would handle this?
Looks like my problem was using "MM/DD/yyyy" when I should have used "MM/dd/yyyy". Uppercase **D** is "Day in year", while lowercase **d** is "Day in month". ``` new SimpleDateFormat("MM/dd/yyyy").parse(dateString); ``` Does the job. Also, "M/d/y" works interchangeably. A closer reading of the [SimpleDateFormat API Docs](http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html) reveals the following: "For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields."
227,612
<p>I am inserting a column in a DataGridView programmatically (i.e., not bound to any data tables/databases) as follows:</p> <pre><code>int lastIndex = m_DGV.Columns.Count - 1; // Count = 4 in this case DataGridViewTextBoxColumn col = (DataGridViewTextBoxColumn)m_DGV.Columns[lastIndex]; m_DGV.Columns.RemoveAt(lastIndex); m_DGV.Columns.Insert(insertIndex, col); // insertIndex = 2 </code></pre> <p>I have found that my columns are visually out of order sometimes using this method. A workaround is to manually set the DisplayIndex property of the column afterwards. Adding this code "fixes it", but I don't understand why it behaves this way.</p> <pre><code>Console.Write(m_DGV.Columns[0].DisplayIndex); // Has value of 0 Console.Write(m_DGV.Columns[1].DisplayIndex); // Has value of 1 Console.Write(m_DGV.Columns[2].DisplayIndex); // Has value of 3 Console.Write(m_DGV.Columns[3].DisplayIndex); // Has value of 2 col.DisplayIndex = insertIndex; Console.Write(m_DGV.Columns[0].DisplayIndex); // Has value of 0 Console.Write(m_DGV.Columns[1].DisplayIndex); // Has value of 1 Console.Write(m_DGV.Columns[2].DisplayIndex); // Has value of 2 Console.Write(m_DGV.Columns[3].DisplayIndex); // Has value of 3 </code></pre> <p>As an aside, my grid can grow its column count dynamically. I wanted to grow it in chunks, so each insert didn't require a column allocation (and associated initialization). Each "new" column would then be added by grabbing an unused column from the end, inserting it into the desired position, and making it visible.</p>
[ { "answer_id": 227683, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": true, "text": "<p>I suspect this is because the order of the columns in the DataGridView do not necessarily dictate the display order, though without explicitly being assigned by default the order of the columns dictate the DisplayIndex property values. That is why there is a DisplayIndex property, so you may add columns to the collection without performing Inserts - you just need to specify the DisplayIndex value and a cascade update occurs for everything with an equal or greater DisplayIndex. It appears from your example the inserted column is also receiving the first skipped DisplayIndex value.</p>\n\n<p>From <a href=\"http://www.themssforum.com/Csharp/DataGridView-DisplayIndex/\" rel=\"nofollow noreferrer\">a question/answer</a> I found:</p>\n\n<blockquote>\n <p>Changing the DisplayIndex will cause\n all the columns between the old\n DisplayIndex and the new DisplayIndex\n to be shifted.</p>\n</blockquote>\n\n<p>As with nearly all collections (other than LinkedLists) its always better to add to a collection <a href=\"http://www.dotnetperls.com/Content/List-Insert.aspx\" rel=\"nofollow noreferrer\">than insert into</a> a collection. The behavior you are seeing is a reflection of that rule.</p>\n" }, { "answer_id": 241167, "author": "e-holder", "author_id": 22252, "author_profile": "https://Stackoverflow.com/users/22252", "pm_score": 0, "selected": false, "text": "<p>Thanks to cfeduke for excellent advice. I suspected <code>Insert</code> would be slower, but the provided link enlightened me on JUST HOW MUCH slower.</p>\n\n<p>This brings up the question of how to efficiently insert and remove columns dynamically on a DataGridView. It looks like the ideal design would be to add plenty of columns using <code>Add</code> or <code>AddRange</code>, and then never really remove them. You could then simulate removal by setting the <code>Visible</code> property to false. And you could insert a column by grabbing an invisible column, setting its <code>DisplayIndex</code> and making it visible.</p>\n\n<p>However, I suspect there would be landmines to avoid with this approach. Foremost being that you can no longer index your data in a straightforward manner. That is, <code>m_DGV.Columns[i]</code> and <code>m_DGV.Rows[n].Cells[i]</code> will not be mapped properly. I suppose you could create a Map/Dictionary to maintain an external intuitive mapping.</p>\n\n<p>Since my application (as currently designed) requires frequent column insertion and removal it might be worth it. Anyone have any suggestions?</p>\n" }, { "answer_id": 355463, "author": "lc.", "author_id": 44853, "author_profile": "https://Stackoverflow.com/users/44853", "pm_score": 2, "selected": false, "text": "<p>I have a couple of ideas.</p>\n\n<ol>\n<li><p>How about addressing your columns by a unique name, rather than the index in the collection? They might not already have a name, but you could keep track of who's who if you gave them a name that meant something.</p></li>\n<li><p>You can use the <code>GetFirstColumn</code>, <code>GetNextColumn</code>, <code>GetPreviousColumn</code>, <code>GetLastColumn</code> methods of the <code>DataGridViewColumnCollection</code> class, which work on display order, not the order in the collection. You can also just iterate through the collection using a for loop and <code>m_DGV.Columns[i]</code> until you find the one you want.</p></li>\n<li><p>Create an inherited <code>DataGridView</code> and <code>DataGridViewColumnCollection</code>. The <code>DataGridView</code> simply is overridden to use your new collection class. Your new <code>DataGridViewColumnCollection</code> will include a method to address the collection by display index, presumably by iterating through the collection until you find the one you want (see #2). Or you can save a dictionary and keep it updated for very large numbers of columns.</p>\n\n<p>I doubt the performance increase of keeping a dictionary, since every time a column moves, you essentially have to rewrite the entire thing. Iterating through is O(n) anyway, and unless you're talking asynchronous operations with hundreds of columns, you're probably okay.</p>\n\n<p>You might be able to override the <code>this[]</code> operator as well, assuming it doesn't screw up the <code>DataGridView</code>.</p></li>\n</ol>\n\n<p>Idea #1 might be the easiest to implement, but not necessarily the prettiest. Idea #2 works, and you can put it in a function <code>DataGridViewColumn GetColumnByDisplayIndex(int Index)</code>. Idea #3 is cute, and certainly the most encapsulated approach, but isn't exactly trivial.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22252/" ]
I am inserting a column in a DataGridView programmatically (i.e., not bound to any data tables/databases) as follows: ``` int lastIndex = m_DGV.Columns.Count - 1; // Count = 4 in this case DataGridViewTextBoxColumn col = (DataGridViewTextBoxColumn)m_DGV.Columns[lastIndex]; m_DGV.Columns.RemoveAt(lastIndex); m_DGV.Columns.Insert(insertIndex, col); // insertIndex = 2 ``` I have found that my columns are visually out of order sometimes using this method. A workaround is to manually set the DisplayIndex property of the column afterwards. Adding this code "fixes it", but I don't understand why it behaves this way. ``` Console.Write(m_DGV.Columns[0].DisplayIndex); // Has value of 0 Console.Write(m_DGV.Columns[1].DisplayIndex); // Has value of 1 Console.Write(m_DGV.Columns[2].DisplayIndex); // Has value of 3 Console.Write(m_DGV.Columns[3].DisplayIndex); // Has value of 2 col.DisplayIndex = insertIndex; Console.Write(m_DGV.Columns[0].DisplayIndex); // Has value of 0 Console.Write(m_DGV.Columns[1].DisplayIndex); // Has value of 1 Console.Write(m_DGV.Columns[2].DisplayIndex); // Has value of 2 Console.Write(m_DGV.Columns[3].DisplayIndex); // Has value of 3 ``` As an aside, my grid can grow its column count dynamically. I wanted to grow it in chunks, so each insert didn't require a column allocation (and associated initialization). Each "new" column would then be added by grabbing an unused column from the end, inserting it into the desired position, and making it visible.
I suspect this is because the order of the columns in the DataGridView do not necessarily dictate the display order, though without explicitly being assigned by default the order of the columns dictate the DisplayIndex property values. That is why there is a DisplayIndex property, so you may add columns to the collection without performing Inserts - you just need to specify the DisplayIndex value and a cascade update occurs for everything with an equal or greater DisplayIndex. It appears from your example the inserted column is also receiving the first skipped DisplayIndex value. From [a question/answer](http://www.themssforum.com/Csharp/DataGridView-DisplayIndex/) I found: > > Changing the DisplayIndex will cause > all the columns between the old > DisplayIndex and the new DisplayIndex > to be shifted. > > > As with nearly all collections (other than LinkedLists) its always better to add to a collection [than insert into](http://www.dotnetperls.com/Content/List-Insert.aspx) a collection. The behavior you are seeing is a reflection of that rule.
227,613
<p>How do I copy a directory including sub directories excluding files or directories that match a certain regex on a Windows system?</p>
[ { "answer_id": 227636, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 1, "selected": false, "text": "<p>I don't know how to do an exclusion with a copy, but you could work something up along the lines of:</p>\n\n<pre><code>ls -R1 | grep -v &lt;regex to exclude&gt; | awk '{printf(\"cp %s /destination/path\",$1)}' | /bin/sh\n</code></pre>\n" }, { "answer_id": 227675, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>If you happen to be on a Unix-like OS and have access to <code>rsync (1)</code>, you should use that (for example through <code>system()</code>).</p>\n\n<p>Perl's File::Copy is a bit broken (it doesn't copy permissions on Unix systems, for example), so if you don't want to use your system tools, look at CPAN. Maybe <a href=\"http://search.cpan.org/perldoc?File::Copy::Recursive\" rel=\"nofollow noreferrer\">File::Copy::Recursive</a> could be of use, but I don't see any exclude options. I hope somebody else has a better idea.</p>\n" }, { "answer_id": 227696, "author": "dwarring", "author_id": 2105284, "author_profile": "https://Stackoverflow.com/users/2105284", "pm_score": 3, "selected": false, "text": "<p>Another option is File::Xcopy. As the name says, it more-or-less emulates the windows xcopy command, including its filtering and recursive options.</p>\n\n<p>From the documentation:</p>\n\n<pre><code> use File::Xcopy;\n\n my $fx = new File::Xcopy; \n $fx-&gt;from_dir(\"/from/dir\");\n $fx-&gt;to_dir(\"/to/dir\");\n $fx-&gt;fn_pat('(\\.pl|\\.txt)$'); # files with pl &amp; txt extensions\n $fx-&gt;param('s',1); # search recursively to sub dirs\n $fx-&gt;param('verbose',1); # search recursively to sub dirs\n $fx-&gt;param('log_file','/my/log/file.log');\n my ($sr, $rr) = $fx-&gt;get_stat; \n $fx-&gt;xcopy; # or\n $fx-&gt;execute('copy'); \n\n # the same with short name\n $fx-&gt;xcp(\"from_dir\", \"to_dir\", \"file_name_pattern\");\n</code></pre>\n" }, { "answer_id": 227699, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>A classic answer would use '<code>cpio -p</code>':</p>\n\n<pre><code>(cd $SOURCE_DIR; find . -type f -print) |\nperl -ne 'print unless m/&lt;regex-goes-here&gt;/' |\ncpio -pd $TARGET_DIR\n</code></pre>\n\n<p>The '<code>cpio</code>' command deals with the actual copying, including permission preservation. The trick of '<code>cd $SOURCE_DIR; find . ...</code>' deals with removing the leading part of the source path from the names. The only problem with that invocation of '<code>find</code>' is that it won't follow symlinks; you need to add '<code>-follow</code>' if that's what you want.</p>\n" }, { "answer_id": 227936, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": true, "text": "<p>I'd do something like this:</p>\n\n<pre><code>use File::Copy;\nsub copy_recursively {\n my ($from_dir, $to_dir, $regex) = @_;\n opendir my($dh), $from_dir or die \"Could not open dir '$from_dir': $!\";\n for my $entry (readdir $dh) {\n next if $entry =~ /$regex/;\n my $source = \"$from_dir/$entry\";\n my $destination = \"$to_dir/$entry\";\n if (-d $source) {\n mkdir $destination or die \"mkdir '$destination' failed: $!\" if not -e $destination;\n copy_recursively($source, $destination, $regex);\n } else {\n copy($source, $destination) or die \"copy failed: $!\";\n }\n }\n closedir $dh;\n return;\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
How do I copy a directory including sub directories excluding files or directories that match a certain regex on a Windows system?
I'd do something like this: ``` use File::Copy; sub copy_recursively { my ($from_dir, $to_dir, $regex) = @_; opendir my($dh), $from_dir or die "Could not open dir '$from_dir': $!"; for my $entry (readdir $dh) { next if $entry =~ /$regex/; my $source = "$from_dir/$entry"; my $destination = "$to_dir/$entry"; if (-d $source) { mkdir $destination or die "mkdir '$destination' failed: $!" if not -e $destination; copy_recursively($source, $destination, $regex); } else { copy($source, $destination) or die "copy failed: $!"; } } closedir $dh; return; } ```
227,624
<p>I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?</p>
[ { "answer_id": 227638, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 10, "selected": true, "text": "<p>In your action method, return Json(object) to return JSON to your page.</p>\n\n<pre><code>public ActionResult SomeActionMethod() {\n return Json(new {foo=\"bar\", baz=\"Blech\"});\n}\n</code></pre>\n\n<p>Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as </p>\n\n<pre><code>&lt;%= Ajax.ActionLink(\"SomeActionMethod\", new AjaxOptions {OnSuccess=\"somemethod\"}) %&gt;\n</code></pre>\n\n<p>SomeMethod would be a javascript method that then evaluates the Json object returned.</p>\n\n<p>If you want to return a plain string, you can just use the ContentResult:</p>\n\n<pre><code>public ActionResult SomeActionMethod() {\n return Content(\"hello world!\");\n}\n</code></pre>\n\n<p>ContentResult by default returns a text/plain as its contentType.<br>\nThis is overloadable so you can also do:</p>\n\n<pre><code>return Content(\"&lt;xml&gt;This is poorly formatted xml.&lt;/xml&gt;\", \"text/xml\");\n</code></pre>\n" }, { "answer_id": 227706, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 6, "selected": false, "text": "<p>Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the </p>\n\n<pre><code>public ActionResult SomeActionMethod(int id) \n{ \n return Json(new {foo=\"bar\", baz=\"Blech\"});\n}\n</code></pre>\n\n<p>Method from the jquery getJSON method by simply...</p>\n\n<pre><code>$.getJSON(\"../SomeActionMethod\", { id: someId },\n function(data) {\n alert(data.foo);\n alert(data.baz);\n }\n);\n</code></pre>\n" }, { "answer_id": 228182, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 4, "selected": false, "text": "<p>To answer the other half of the question, you can call:</p>\n\n<pre><code>return PartialView(\"viewname\");\n</code></pre>\n\n<p>when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.</p>\n" }, { "answer_id": 1492970, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 7, "selected": false, "text": "<p>I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows.</p>\n\n<p>Your action on the controller can test it as on the request object </p>\n\n<pre><code>if (Request.AcceptTypes.Contains(\"text/html\")) {\n return View();\n}\nelse if (Request.AcceptTypes.Contains(\"application/json\"))\n{\n return Json( new { id=1, value=\"new\" } );\n}\nelse if (Request.AcceptTypes.Contains(\"application/xml\") || \n Request.AcceptTypes.Contains(\"text/xml\"))\n{\n //\n}\n</code></pre>\n\n<p>You can then implement the aspx of the view to cater for the partial xhtml response case.</p>\n\n<p>Then in jQuery you can fetch it passing the type parameter as json:</p>\n\n<pre><code>$.get(url, null, function(data, textStatus) {\n console.log('got %o with status %s', data, textStatus);\n }, \"json\"); // or xml, html, script, json, jsonp or text\n</code></pre>\n\n<p>Hope this helps\nJames</p>\n" }, { "answer_id": 2045986, "author": "Paul Hinett", "author_id": 233861, "author_profile": "https://Stackoverflow.com/users/233861", "pm_score": 3, "selected": false, "text": "<p>You may want to take a look at this very helpful article which covers this very nicely!</p>\n\n<p>Just thought it might help people searching for a good solution to this problem.</p>\n\n<p><a href=\"http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx</a></p>\n" }, { "answer_id": 5337717, "author": "Sarath", "author_id": 353241, "author_profile": "https://Stackoverflow.com/users/353241", "pm_score": 2, "selected": false, "text": "<p>For folks who have upgraded to MVC 3 here is a neat way\n<a href=\"http://geekswithblogs.net/michelotti/archive/2008/06/28/mvc-json---jsonresult-and-jquery.aspx\" rel=\"nofollow\">Using MVC3 and Json</a></p>\n" }, { "answer_id": 16393288, "author": "Vlad", "author_id": 2349318, "author_profile": "https://Stackoverflow.com/users/2349318", "pm_score": 3, "selected": false, "text": "<p>Alternative solution with <a href=\"https://incframework.codeplex.com/\">incoding framework</a></p>\n\n<p>Action return json</p>\n\n<p><strong>Controller</strong></p>\n\n<pre><code> [HttpGet]\n public ActionResult SomeActionMethod()\n {\n return IncJson(new SomeVm(){Id = 1,Name =\"Inc\"});\n }\n</code></pre>\n\n<p><strong>Razor page</strong></p>\n\n<pre><code>@using (var template = Html.Incoding().ScriptTemplate&lt;SomeVm&gt;(\"tmplId\"))\n{\n using (var each = template.ForEach())\n {\n &lt;span&gt; Id: @each.For(r=&gt;r.Id) Name: @each.For(r=&gt;r.Name)&lt;/span&gt;\n }\n}\n\n@(Html.When(JqueryBind.InitIncoding)\n .Do()\n .AjaxGet(Url.Action(\"SomeActionMethod\",\"SomeContoller\"))\n .OnSuccess(dsl =&gt; dsl.Self().Core()\n .Insert\n .WithTemplate(Selector.Jquery.Id(\"tmplId\"))\n .Html())\n .AsHtmlAttributes()\n .ToDiv())\n</code></pre>\n\n<p>Action return html</p>\n\n<p><strong>Controller</strong></p>\n\n<pre><code> [HttpGet]\n public ActionResult SomeActionMethod()\n {\n return IncView();\n }\n</code></pre>\n\n<p><strong>Razor page</strong></p>\n\n<pre><code>@(Html.When(JqueryBind.InitIncoding)\n .Do()\n .AjaxGet(Url.Action(\"SomeActionMethod\",\"SomeContoller\"))\n .OnSuccess(dsl =&gt; dsl.Self().Core().Insert.Html())\n .AsHtmlAttributes()\n .ToDiv())\n</code></pre>\n" }, { "answer_id": 17734878, "author": "Shane Kenyon", "author_id": 1158844, "author_profile": "https://Stackoverflow.com/users/1158844", "pm_score": 6, "selected": false, "text": "<p>I found a couple of issues implementing MVC ajax GET calls with JQuery that caused me headaches so sharing solutions here.</p>\n\n<ol>\n<li>Make sure to include the data type \"json\" in the ajax call. This will automatically parse the returned JSON object for you (given the server returns valid json).</li>\n<li>Include the <code>JsonRequestBehavior.AllowGet</code>; without this MVC was returning a HTTP 500 error (with <code>dataType: json</code> specified on the client).</li>\n<li>Add <code>cache: false</code> to the $.ajax call, otherwise you will ultimately get HTTP 304 responses (instead of HTTP 200 responses) and the server will not process your request.</li>\n<li>Finally, the json is case sensitive, so the casing of the elements needs to match on the server side and client side.</li>\n</ol>\n\n<p>Sample JQuery:</p>\n\n<pre><code>$.ajax({\n type: 'get',\n dataType: 'json',\n cache: false,\n url: '/MyController/MyMethod',\n data: { keyid: 1, newval: 10 },\n success: function (response, textStatus, jqXHR) {\n alert(parseInt(response.oldval) + ' changed to ' + newval); \n },\n error: function(jqXHR, textStatus, errorThrown) {\n alert('Error - ' + errorThrown);\n }\n});\n</code></pre>\n\n<p>Sample MVC code:</p>\n\n<pre><code>[HttpGet]\npublic ActionResult MyMethod(int keyid, int newval)\n{\n var oldval = 0;\n\n using (var db = new MyContext())\n {\n var dbRecord = db.MyTable.Where(t =&gt; t.keyid == keyid).FirstOrDefault();\n\n if (dbRecord != null)\n {\n oldval = dbRecord.TheValue;\n dbRecord.TheValue = newval;\n db.SaveChanges();\n }\n }\n\n return Json(new { success = true, oldval = oldval},\n JsonRequestBehavior.AllowGet);\n}\n</code></pre>\n" }, { "answer_id": 45560042, "author": "Anil Vaddepally", "author_id": 6593652, "author_profile": "https://Stackoverflow.com/users/6593652", "pm_score": 3, "selected": false, "text": "<p>PartialViewResult and JSONReuslt inherit from the base class ActionResult. so if return type is decided dynamically declare method output as ActionResult.</p>\n\n<pre><code>public ActionResult DynamicReturnType(string parameter)\n {\n if (parameter == \"JSON\")\n return Json(\"&lt;JSON&gt;\", JsonRequestBehavior.AllowGet);\n else if (parameter == \"PartialView\")\n return PartialView(\"&lt;ViewName&gt;\");\n else\n return null;\n\n\n }\n</code></pre>\n" }, { "answer_id": 46094924, "author": "sakthi", "author_id": 5311353, "author_profile": "https://Stackoverflow.com/users/5311353", "pm_score": 2, "selected": false, "text": "<pre><code> public ActionResult GetExcelColumn()\n { \n List&lt;string&gt; lstAppendColumn = new List&lt;string&gt;();\n lstAppendColumn.Add(\"First\");\n lstAppendColumn.Add(\"Second\");\n lstAppendColumn.Add(\"Third\");\n return Json(new { lstAppendColumn = lstAppendColumn, Status = \"Success\" }, JsonRequestBehavior.AllowGet);\n }\n }\n</code></pre>\n" }, { "answer_id": 49531015, "author": "Mannan Bahelim", "author_id": 5326667, "author_profile": "https://Stackoverflow.com/users/5326667", "pm_score": 1, "selected": false, "text": "<p>Flexible approach to produce different outputs based on the request</p>\n\n<pre><code>public class AuctionsController : Controller\n{\n public ActionResult Auction(long id)\n {\n var db = new DataContext();\n var auction = db.Auctions.Find(id);\n\n // Respond to AJAX requests\n if (Request.IsAjaxRequest())\n return PartialView(\"Auction\", auction);\n\n // Respond to JSON requests\n if (Request.IsJsonRequest())\n return Json(auction);\n\n // Default to a \"normal\" view with layout\n return View(\"Auction\", auction);\n }\n}\n</code></pre>\n\n<p>The <code>Request.IsAjaxRequest()</code> method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header is <code>XMLHttpRequest</code>, which is automatically appended by most browsers and AJAX frameworks.</p>\n\n<p>Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:</p>\n\n<pre><code>using System;\nusing System.Web;\n\npublic static class JsonRequestExtensions\n{\n public static bool IsJsonRequest(this HttpRequestBase request)\n {\n return string.Equals(request[\"format\"], \"json\");\n }\n}\n</code></pre>\n\n<p>Source : <a href=\"https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering\" rel=\"nofollow noreferrer\">https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30544/" ]
I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?
In your action method, return Json(object) to return JSON to your page. ``` public ActionResult SomeActionMethod() { return Json(new {foo="bar", baz="Blech"}); } ``` Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as ``` <%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %> ``` SomeMethod would be a javascript method that then evaluates the Json object returned. If you want to return a plain string, you can just use the ContentResult: ``` public ActionResult SomeActionMethod() { return Content("hello world!"); } ``` ContentResult by default returns a text/plain as its contentType. This is overloadable so you can also do: ``` return Content("<xml>This is poorly formatted xml.</xml>", "text/xml"); ```
227,627
<p>I have this 'simplified' fortran code</p> <pre><code>real B(100, 200) real A(100,200) ... initialize B array code. do I = 1, 100 do J = 1, 200 A(J,I) = B(J,I) end do end do </code></pre> <p>One of the programming gurus warned me, that fortran accesses data efficiently in column order, while c accesses data efficiently in row order. He suggested that I take a good hard look at the code, and be prepared to switch loops around to maintain the speed of the old program.</p> <p>Being the lazy programmer that I am, and recognizing the days of effort involved, and the mistakes I am likely to make, I started wondering if there might a #define technique that would let me convert this code safely, and easily.</p> <p>Do you have any suggestions?</p>
[ { "answer_id": 227649, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>Are you sure your FORTRAN guys did things right? </p>\n\n<p>The code snippet you originally posted is already accessing the arrays in row-major order (which is 'inefficient' for FORTRAN, 'efficient' for C).</p>\n\n<p>As illustrated by the snippet of code and as mentioned in your question, getting this 'correct' can be error prone. Worry about getting the FORTRAN code ported to C first without worrying about details like this. When the port is working - then you can worry about changing column-order accesses to row-order accesses (if it even really matters after the port is working).</p>\n" }, { "answer_id": 227680, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>One of my first programming jobs out of college was to fix a long-running C app that had been ported from FORTRAN. The arrays were much larger than yours and it was taking something around 27 hours per run. After fixing it, they ran in about 2.5 hours... pretty sweet!</p>\n\n<p><em>(OK, it really wasn't assigned, but I was curious and found a big problem with their code. Some of the old timers didn't like me much despite this fix.)</em></p>\n\n<p>It would seem that the same issue is found here.</p>\n\n<pre><code>real B(100, 200) \nreal A(100,200)\n\n... initialize B array code.\n\ndo I = 1, 100\n do J = 1, 200\n A(I,J) = B(I,J)\n end do\nend do\n</code></pre>\n\n<p>Your looping (to be good FORTRAN) would be:</p>\n\n<pre><code>real B(100, 200) \nreal A(100,200)\n\n... initialize B array code.\n\ndo J = 1, 200\n do I = 1, 100\n A(I,J) = B(I,J)\n end do\nend do\n</code></pre>\n\n<p>Otherwise you are marching through the arrays in row-major, which could be highly inefficient.</p>\n\n<p>At least I believe that's how it would be in FORTRAN - it's been a long time.</p>\n\n<hr>\n\n<p>Saw you updated the code... </p>\n\n<p>Now, you'd want to swap the loop control variables so that you iterate on the rows and then inside that iterate on the columns if you are converting to C.</p>\n" }, { "answer_id": 229932, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": true, "text": "<p>In C, multi-dimensional arrays work like this:</p>\n\n<pre><code>#define array_length(a) (sizeof(a)/sizeof((a)[0]))\nfloat a[100][200];\na[x][y] == ((float *)a)[array_length(a[0])*x + y];\n</code></pre>\n\n<p>In other words, they're really flat arrays and <code>[][]</code> is just syntactic sugar.</p>\n\n<p>Suppose you do this:</p>\n\n<pre><code>#define at(a, i, j) ((typeof(**(a)) *)a)[(i) + array_length((a)[0])*(j)]\nfloat a[100][200];\nfloat b[100][200];\nfor (i = 0; i &lt; 100; i++)\n for (j = 0; j &lt; 200; j++)\n at(a, j, i) = at(b, j, i);\n</code></pre>\n\n<p>You're walking sequentially through memory, and pretending that <code>a</code> and <code>b</code> are actually laid out in column-major order. It's kind of horrible in that <code>a[x][y] != at(a, x, y) != a[y][x]</code>, but as long as you remember that it's tricked out like this, you'll be fine.</p>\n\n<h2>Edit</h2>\n\n<p>Man, I feel dumb. The intention of this definition is to make <code>at(a, x, y) == at[y][x]</code>, and it does. So the much simpler and easier to understand</p>\n\n<pre><code>#define at(a, i, j) (a)[j][i]\n</code></pre>\n\n<p>would be better that what I suggested above.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
I have this 'simplified' fortran code ``` real B(100, 200) real A(100,200) ... initialize B array code. do I = 1, 100 do J = 1, 200 A(J,I) = B(J,I) end do end do ``` One of the programming gurus warned me, that fortran accesses data efficiently in column order, while c accesses data efficiently in row order. He suggested that I take a good hard look at the code, and be prepared to switch loops around to maintain the speed of the old program. Being the lazy programmer that I am, and recognizing the days of effort involved, and the mistakes I am likely to make, I started wondering if there might a #define technique that would let me convert this code safely, and easily. Do you have any suggestions?
In C, multi-dimensional arrays work like this: ``` #define array_length(a) (sizeof(a)/sizeof((a)[0])) float a[100][200]; a[x][y] == ((float *)a)[array_length(a[0])*x + y]; ``` In other words, they're really flat arrays and `[][]` is just syntactic sugar. Suppose you do this: ``` #define at(a, i, j) ((typeof(**(a)) *)a)[(i) + array_length((a)[0])*(j)] float a[100][200]; float b[100][200]; for (i = 0; i < 100; i++) for (j = 0; j < 200; j++) at(a, j, i) = at(b, j, i); ``` You're walking sequentially through memory, and pretending that `a` and `b` are actually laid out in column-major order. It's kind of horrible in that `a[x][y] != at(a, x, y) != a[y][x]`, but as long as you remember that it's tricked out like this, you'll be fine. Edit ---- Man, I feel dumb. The intention of this definition is to make `at(a, x, y) == at[y][x]`, and it does. So the much simpler and easier to understand ``` #define at(a, i, j) (a)[j][i] ``` would be better that what I suggested above.
227,634
<p>I am copying a repository by using svnsync and am receiving this error on the same revision every time.</p> <blockquote> <p>Transmitting file data ...svnsync: REPORT of '<a href="https://svn1.avlux.net/xxxxxx.net" rel="nofollow noreferrer">https://svn1.avlux.net/xxxxxx.net</a>': Could not read response body: Secure connection truncated <a href="https://svn1.avlux.net" rel="nofollow noreferrer">https://svn1.avlux.net</a>)</p> </blockquote> <p>It is a large revision and I don't have admin access to the server. Is there a way around this, even if it involves checking out and copying the revision manually?</p>
[ { "answer_id": 228427, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 3, "selected": true, "text": "<p>Are you just trying to copy the repo once or are you trying to setup an ongoing mirroring scheme?</p>\n\n<p>If it's the former you could let sync go until it fails, then do a diff between the revision it failed on and the previous revision and output that to a file. So if the rev that failed was 135 it would be something like this:</p>\n\n<pre><code>svn diff -r134:135 http://your/repo/url &gt; patch.diff\n</code></pre>\n\n<p>Then you can apply this patch file to a working copy of the new repo.</p>\n\n<pre><code>patch -p0 -i patch.diff\n</code></pre>\n\n<p>Then just commit the changes to that working copy and kick off svnsync again.</p>\n\n<p>This is pretty hackish, but it might work.</p>\n\n<p>NOTE: I didn't test any of the commands, there might be some syntax errors, but the general approach should work in theory.</p>\n" }, { "answer_id": 19575963, "author": "Yoram A", "author_id": 2917494, "author_profile": "https://Stackoverflow.com/users/2917494", "pm_score": 0, "selected": false, "text": "<p>I manage to resolved the issue by:\n- Update (Apache and svn to latest)\n- Turn on svn V2 protocol (apache config under the location)\n SVNAdvertiseV2Protocol On</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233/" ]
I am copying a repository by using svnsync and am receiving this error on the same revision every time. > > Transmitting file data ...svnsync: REPORT of '<https://svn1.avlux.net/xxxxxx.net>': Could not read response body: Secure connection truncated <https://svn1.avlux.net>) > > > It is a large revision and I don't have admin access to the server. Is there a way around this, even if it involves checking out and copying the revision manually?
Are you just trying to copy the repo once or are you trying to setup an ongoing mirroring scheme? If it's the former you could let sync go until it fails, then do a diff between the revision it failed on and the previous revision and output that to a file. So if the rev that failed was 135 it would be something like this: ``` svn diff -r134:135 http://your/repo/url > patch.diff ``` Then you can apply this patch file to a working copy of the new repo. ``` patch -p0 -i patch.diff ``` Then just commit the changes to that working copy and kick off svnsync again. This is pretty hackish, but it might work. NOTE: I didn't test any of the commands, there might be some syntax errors, but the general approach should work in theory.
227,667
<p>What type of exception is caught by the beanshell catch(ex): Exception or Throwable?.</p> <p>Example:</p> <pre><code>try { .... } catch (ex) { } </code></pre>
[ { "answer_id": 227911, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>Throwable is a superclass (essentially) of Exception--anything that Exception catches will also be caught by Throwable. In general usage they are the same, you rarely (if ever) see other throwable types.</p>\n" }, { "answer_id": 232275, "author": "Bob Cross", "author_id": 5812, "author_profile": "https://Stackoverflow.com/users/5812", "pm_score": 3, "selected": false, "text": "<p>That loosely typed catch will catch everything \"<a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html\" rel=\"nofollow noreferrer\">Throwable</a>.\" That will include <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Error.html\" rel=\"nofollow noreferrer\">Errors</a>, <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Exception.html\" rel=\"nofollow noreferrer\">Exceptions</a> and their myriad children. You can easily confirm this with:</p>\n\n<pre><code>try {\n new Throwable(\"Something Exceptional\");\n} catch (ex) {\n System.err.println(ex.getMessage());\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What type of exception is caught by the beanshell catch(ex): Exception or Throwable?. Example: ``` try { .... } catch (ex) { } ```
That loosely typed catch will catch everything "[Throwable](http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html)." That will include [Errors](http://java.sun.com/javase/6/docs/api/java/lang/Error.html), [Exceptions](http://java.sun.com/javase/6/docs/api/java/lang/Exception.html) and their myriad children. You can easily confirm this with: ``` try { new Throwable("Something Exceptional"); } catch (ex) { System.err.println(ex.getMessage()); } ```
227,674
<p>I've got a few very short audio clips (less than a second long) to be played on various events (button hover, click, etc). However, there is usually a significant lag between the action and the actual playing of the sound. I have tried both embedding the sound in the .swf, and loading it externally at the start, but both lead to the same results. Likewise, I've tried with compressed and uncompressed audio.</p> <p>What it <em>seems</em> like is that the audio buffers are just a lot longer than I need them to be, like perhaps Flash is optimized more towards playing longer sounds without any stutter at the expense of a little more latency in starting sounds. Could this be it? Is there any way to change them? Since what I'm working on will never need to play sounds more than a second or so long and will always be loaded completely at the start, it wouldn't hurt it at all to have really short buffers.</p> <p>One other possible thing that might be the cause: if I use .wav files when using loadSound()... I can't get it to actually play the sounds. There's no errors, and everything returns as it should, but no actual sound is played, which is why I have them as .mp3 currently. Perhaps when using .mp3 audio (or any compressed audio), there just will be lag in decoding it? The reason I still have doubts about this, though, is that when embedding them in the .swf as .wav files (by importing them into the library), they still have the same latency on playback.</p> <p>Just for a sanity check, I'll include the code I've got, minus irrelevant parts and error checking. First, loading them at runtime:</p> <pre><code>var soundArray:Array = new Array(); loadSound( "click", "sounds/buttondroop4.mp3" ); loadSound( "hover", "sounds/Dink-Public_D-146.mp3" ); function loadSound( name:String, url:String ):void { var req:URLRequest = new URLRequest( url ); soundArray[ name ] = new Sound( req ); soundArray[ name ].addEventListener( Event.COMPLETE, soundLoaded ); } function soundLoaded( event:Event ):void { for( var name:String in soundArray ) { if( event.target == soundArray[name] ) { trace( "Loaded sound [" + name + "]" ); return; } } } function playSound( name:String ):void { for( var nameSrc:String in soundArray ) { if( name == nameSrc ) { var channel:SoundChannel = soundArray[ name ].play(); return; } } } // Sometime later, well after soundLoaded() callback is triggered... playSound( "click" ); playSound( "hover" ); </code></pre> <p>And an alternate way, embedding them in the library as classes and going from there:</p> <pre><code>var sClick:soundClick = new soundClick(); var sHover:soundHover = new soundHover(); sClick.play(); sHover.play(); </code></pre> <p>The sound files are tiny, less than 10kb generally. The lag is apparent enough that one of the first complaints someone had when looking at it was that the sound effects on button hovers seemed delayed, so it wasn't just me being picky. I feel like I must just be doing something wrong; there's too many flash things out there that have snappy sound effects without anywhere near this kind of lag.</p> <p>edit: In response to the first response about sound files themselves, I've already checked, and the sound starts immediately at the start of the file (even clipping out everything but the very first millisecond of sound, I can still hear the start of the 'tick' noise it makes).</p>
[ { "answer_id": 228384, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 2, "selected": false, "text": "<p>Well, my first-blush answer is that when I've done things like this, normally I find that sound files have a certain amount of lead time built in. You could check in a sound editor, but What I've done in the past is to import the sound into the Flash IDE, make an empty movie clip, and put the sound on frame 1 of the clip. Then, but editing the frame sound you get a nice little interface to drag the start/end points of the sound playback. Then I used to either attach/remove the clip to play the sound, or leave it somewhere and use frame commands.</p>\n\n<p>If you're already sure that the lead time is in flash and not the audio then I have no tips or tricks, beyond reasonably obvious things like playing click sounds on key down instead of up...</p>\n" }, { "answer_id": 238176, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 4, "selected": true, "text": "<p>It's a little thing but:</p>\n\n<pre><code>function playSound( name:String ):void\n{\n for( var nameSrc:String in soundArray )\n {\n if( name == nameSrc )\n {\n var channel:SoundChannel = soundArray[ name ].play();\n return;\n }\n }\n}\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>function playSound(name:String):void\n{\n if(soundArray[name])\n {\n soundArray[name].play();\n }\n}\n</code></pre>\n\n<p>There is no need for a loop look up since that is what the hash table is for. Also, you shouldn't use an Array at all for that since an Array is an ordered set which is indexed using integers. You want to use an Object (or Dictionary) in this case and name it soundMap (since it maps sound names to sound objects).</p>\n\n<p>As for sound latency -- there should be none. I've done quite a bit of sound in Flash (including tons of one off rollover and rollout sounds) and it has never been an issue. However Flash Player 10 has a new <a href=\"http://www.kaourantin.net/2008/05/adobe-is-making-some-noise-part-1.html\" rel=\"nofollow noreferrer\">low-level sound API</a> which is described by one of the Adobe engineers in that article. A solution involving that is a bit of a sledge hammer but perhaps you are looking for millisecond accuracy.</p>\n\n<p>The advice fenomas gives is wise: check the mp3 file for deadspace at the start and end and trim it as close as possible. Also - what is the path from the event handler to your play statement? Are there any possible blocks there? What is the format of the mp3? Flash works best with specific encodings (44.1 hHz and 128 bit I believe).</p>\n" }, { "answer_id": 369099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I <em>had</em> the exact same problem... until I noticed that the problem was only occurring only while previewing within Flash. Try running the complied swf (it worked for me).</p>\n" }, { "answer_id": 1149008, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I was having bad sound lancency (about 1 full second) with Flash Player 10.0.2.x. The lantency was the same when stopping the sound channel. </p>\n\n<p>I just upgraded to 10.0.22.x and the problem is gone. </p>\n" }, { "answer_id": 1328202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I'm having the same problem. Came across this.\nApparently if you keep the sound player \"going\" silently in the background, it doesn't need to \"restart\" for small sounds. Haven't tried it yet...</p>\n\n<p><a href=\"http://www.ghostwire.com/blog/archives/as3-fixing-the-lag-that-arises-when-playing-a-short-sound-effect/\" rel=\"nofollow noreferrer\">http://www.ghostwire.com/blog/archives/as3-fixing-the-lag-that-arises-when-playing-a-short-sound-effect/</a></p>\n" }, { "answer_id": 7262437, "author": "Pup", "author_id": 125505, "author_profile": "https://Stackoverflow.com/users/125505", "pm_score": 2, "selected": false, "text": "<p>One solution might be to use an ActionScript library that reads sound files as binary data.</p>\n\n<p>StandingWave<br>\n<a href=\"https://github.com/maxl0rd/standingwave3\" rel=\"nofollow\">https://github.com/maxl0rd/standingwave3</a><br>\n<a href=\"http://maxl0rd.github.com/standingwave3/\" rel=\"nofollow\">http://maxl0rd.github.com/standingwave3/</a> </p>\n\n<p>Also, make sure to check audio settings of the environment around your SWF. I was debugging my app for hours until realizing the latency came from my bluetooth headphone connection.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9330/" ]
I've got a few very short audio clips (less than a second long) to be played on various events (button hover, click, etc). However, there is usually a significant lag between the action and the actual playing of the sound. I have tried both embedding the sound in the .swf, and loading it externally at the start, but both lead to the same results. Likewise, I've tried with compressed and uncompressed audio. What it *seems* like is that the audio buffers are just a lot longer than I need them to be, like perhaps Flash is optimized more towards playing longer sounds without any stutter at the expense of a little more latency in starting sounds. Could this be it? Is there any way to change them? Since what I'm working on will never need to play sounds more than a second or so long and will always be loaded completely at the start, it wouldn't hurt it at all to have really short buffers. One other possible thing that might be the cause: if I use .wav files when using loadSound()... I can't get it to actually play the sounds. There's no errors, and everything returns as it should, but no actual sound is played, which is why I have them as .mp3 currently. Perhaps when using .mp3 audio (or any compressed audio), there just will be lag in decoding it? The reason I still have doubts about this, though, is that when embedding them in the .swf as .wav files (by importing them into the library), they still have the same latency on playback. Just for a sanity check, I'll include the code I've got, minus irrelevant parts and error checking. First, loading them at runtime: ``` var soundArray:Array = new Array(); loadSound( "click", "sounds/buttondroop4.mp3" ); loadSound( "hover", "sounds/Dink-Public_D-146.mp3" ); function loadSound( name:String, url:String ):void { var req:URLRequest = new URLRequest( url ); soundArray[ name ] = new Sound( req ); soundArray[ name ].addEventListener( Event.COMPLETE, soundLoaded ); } function soundLoaded( event:Event ):void { for( var name:String in soundArray ) { if( event.target == soundArray[name] ) { trace( "Loaded sound [" + name + "]" ); return; } } } function playSound( name:String ):void { for( var nameSrc:String in soundArray ) { if( name == nameSrc ) { var channel:SoundChannel = soundArray[ name ].play(); return; } } } // Sometime later, well after soundLoaded() callback is triggered... playSound( "click" ); playSound( "hover" ); ``` And an alternate way, embedding them in the library as classes and going from there: ``` var sClick:soundClick = new soundClick(); var sHover:soundHover = new soundHover(); sClick.play(); sHover.play(); ``` The sound files are tiny, less than 10kb generally. The lag is apparent enough that one of the first complaints someone had when looking at it was that the sound effects on button hovers seemed delayed, so it wasn't just me being picky. I feel like I must just be doing something wrong; there's too many flash things out there that have snappy sound effects without anywhere near this kind of lag. edit: In response to the first response about sound files themselves, I've already checked, and the sound starts immediately at the start of the file (even clipping out everything but the very first millisecond of sound, I can still hear the start of the 'tick' noise it makes).
It's a little thing but: ``` function playSound( name:String ):void { for( var nameSrc:String in soundArray ) { if( name == nameSrc ) { var channel:SoundChannel = soundArray[ name ].play(); return; } } } ``` Should be: ``` function playSound(name:String):void { if(soundArray[name]) { soundArray[name].play(); } } ``` There is no need for a loop look up since that is what the hash table is for. Also, you shouldn't use an Array at all for that since an Array is an ordered set which is indexed using integers. You want to use an Object (or Dictionary) in this case and name it soundMap (since it maps sound names to sound objects). As for sound latency -- there should be none. I've done quite a bit of sound in Flash (including tons of one off rollover and rollout sounds) and it has never been an issue. However Flash Player 10 has a new [low-level sound API](http://www.kaourantin.net/2008/05/adobe-is-making-some-noise-part-1.html) which is described by one of the Adobe engineers in that article. A solution involving that is a bit of a sledge hammer but perhaps you are looking for millisecond accuracy. The advice fenomas gives is wise: check the mp3 file for deadspace at the start and end and trim it as close as possible. Also - what is the path from the event handler to your play statement? Are there any possible blocks there? What is the format of the mp3? Flash works best with specific encodings (44.1 hHz and 128 bit I believe).
227,701
<p>I can't for the life of me find a form that doesn't email the results that you submit.</p> <p>I'm looking to find a form that I can have users enter simple data that i can then spit back out at them in different arrangements. If they submit First and Last, I'll spit out, amongst other things, [email protected]. I'm willing to scrounge the code manually to do this, but I cant find a simple form that would allow me to do this. </p> <p><strong>Edit:</strong> PHP or similar simple languages. I've never touched .NET before.</p>
[ { "answer_id": 227707, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 0, "selected": false, "text": "<p>What language/platform/environment are you working in?</p>\n\n<p>I guess you might be looking for a hosted script or webform (the way that people will host web-to-mail scripts I suppose) but I doubt there would be one out there that does this.</p>\n\n<p>But if you have a specific framework to work in, e.g. PHP or .net, please update the question and let us know which.</p>\n" }, { "answer_id": 227891, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "<p>Thing that simple doens't even need server-side support.</p>\n\n<pre><code>&lt;form onsubmit=\"magic(this);return false\"&gt;\n &lt;p&gt;&lt;label&gt;First &lt;input name=first/&gt;&lt;/label&gt;\n &lt;p&gt;&lt;label&gt;Last &lt;input name=last/&gt;&lt;/label&gt;\n &lt;input type=\"submit\"&gt;\n\n &lt;div id=\"output\"&gt;&lt;/div&gt;\n&lt;/form&gt; \n\n&lt;script type=\"text/javascript\"&gt;\n var output = document.getElementById('output');\n function toHTML(text)\n {\n return text.replace(/&lt;/g,'&amp;lt;');\n }\n\n function magic(form)\n {\n output.innerHTML = toHTML(form.first.value + form.last.value) + '@domain.com';\n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 227899, "author": "alex77", "author_id": 1555, "author_profile": "https://Stackoverflow.com/users/1555", "pm_score": 2, "selected": false, "text": "<p>Form:</p>\n\n<pre><code>&lt;form action=\"process.php\" method=\"post\"&gt;\n First: &lt;input type=\"text\" name=\"first\" /&gt;\n Last: &lt;input type=\"text\" name=\"last\" /&gt;\n &lt;input type=\"submit\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Next page:</p>\n\n<pre><code>&lt;?php\n\n$first = $_POST['first'];\n$last = $_POST['last']\n\necho $first . \".\" . $last . \"@domain.com\";\n?&gt;\n</code></pre>\n\n<p>See <a href=\"http://www.w3schools.com/php/php_forms.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/php/php_forms.asp</a> for more examples and explanation</p>\n" }, { "answer_id": 227920, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 1, "selected": false, "text": "<p>Regardless of how you get it, <em>always</em> remember to <strong>never trust user input</strong>.</p>\n\n<pre><code>&lt;?php\n\n$sfirst = htmlentities($_POST['first']);\n$slast = htmlentities($_POST['last']);\n\necho $first . \".\" . $last . \"@domain.com\";\n?&gt;\n</code></pre>\n\n<p>Also, running a validator on the final result may be helpful. But please don't write your own email address validator.</p>\n" }, { "answer_id": 261216, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 0, "selected": false, "text": "<p>If I get your question right, sounds like this might do what you need..</p>\n\n<p><b>Note:</b> This PHP code doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields, including multiple-choice fields (like checkboxes), and spits out their values.</p>\n\n<pre><code>&lt;?php\n// loop through every form field\nwhile( list( $field, $value ) = each( $_POST )) {\n // display values\n if( is_array( $value )) {\n // if checkbox (or other multiple value fields)\n while( list( $arrayField, $arrayValue ) = each( $value ) {\n echo \"&lt;p&gt;\" . $arrayValue . \"&lt;/p&gt;\\n\";\n }\n } else {\n echo \"&lt;p&gt;\" . $value . \"&lt;/p&gt;\\n\";\n }\n}\n?&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I can't for the life of me find a form that doesn't email the results that you submit. I'm looking to find a form that I can have users enter simple data that i can then spit back out at them in different arrangements. If they submit First and Last, I'll spit out, amongst other things, [email protected]. I'm willing to scrounge the code manually to do this, but I cant find a simple form that would allow me to do this. **Edit:** PHP or similar simple languages. I've never touched .NET before.
Form: ``` <form action="process.php" method="post"> First: <input type="text" name="first" /> Last: <input type="text" name="last" /> <input type="submit" /> </form> ``` Next page: ``` <?php $first = $_POST['first']; $last = $_POST['last'] echo $first . "." . $last . "@domain.com"; ?> ``` See <http://www.w3schools.com/php/php_forms.asp> for more examples and explanation
227,708
<p>I would like to apply some logic to a page containing a CheckBoxList control when the user checks or unchecks individual checkbox items. Say, for instance to dynamically show or hide a related control.</p> <p>I came up with a way using ASP.Net 2.0 callback mechanism (AJAX) with a combination of client-side Javascript and server-side logic in the code-behind. However, this solution is not very bullet-proof (i.e. most likely suffers from timing issues). It is not portable, because the code needs to know the sequential ids of individual items, etc.</p> <p>The code I came up with is separated in two functions, one handling the <code>onclick</code> event, and the other processing the returned callback string :</p> <pre><code>&lt;script type="text/javascript"&gt; function OnCheckBoxClicked() { // gathers the semi-colon separated list of labels, // associated with the currently checked items var texts = ''; // iterate over each individual checkbox item // items in a checkboxlist are sequential, so // stop iteration at the first missing sequence number for (var index = 0; index &lt; 99; index++) { var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index); if (checkbox == null) break; if (checkbox.checked) { // find label associated with the current checkbox item var labels = document.getElementsByTagName('label'); for (var index_ = 0; index_ &lt; labels.length; index_ ++) { if (labels[index_].htmlFor == checkbox.id) { texts = texts + labels[index_].innerHTML + ';'; break; } } } } // perform callback request // result will be processed by the UpdateCheckBoxes function WebForm_DoCallback('__Page', '_checkbox' + texts, UpdateCheckBoxes, 'checkbox', null, true /* synchronous */); } &lt;/script&gt; </code></pre> <p>In this example, my checkboxes match categories of a blog post.</p> <p>I need to process the resulting callback string as containing a list of semicolon-separated names of checkboxes to check/uncheck, in order to make sure that related parent/child categories are synchronized correctly. This string results from logic executed on the server.</p> <p>In other cases, the resulting callback string might be something else.</p> <pre><code>&lt;script type="text/javascript"&gt; function UpdateCheckBoxes(returnmessage, context) { if (returnmessage == null || returnmessage == '') return ; // iterate over each individual checkbox item // items in a checkboxlist are sequential, so // stop iteration at the first missing sequence number for (var index = 0; index &lt; 99; index++) { var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index); if (checkbox == null) break; // find label associated with the current checkbox item var label = ''; var labels = document.getElementsByTagName('label'); for (var index_ = 0; index_ &lt; labels.length; index_ ++) { if (labels[index_].htmlFor == checkbox.id) { label = ';' + labels[index_].innerHTML + ';'; break; } } // perform custom processing based on the contents // of the returned callback string // for instance, here we check whether the returnmessage // contains the string ';' + label + ';' if (returnmessage.indexOf(label, 1) &gt; 0) { // do something } } } &lt;/script&gt; </code></pre> <p>Isn't there a more elegant solution to this problem?</p>
[ { "answer_id": 228448, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>I'd do a couple of things. One, I'd figure out a way to pass the value that needs to be passed back to the client-side onclick handler. Depending on how you are populating your CheckBoxList, this might be as simple as adding an \"onclick\" attribute to the ListItem for that checkbox that calls your function with the same value assigned to the label, say 'OnCheckBoxClicked(this,'Label'). That would eliminate the need to derive the label, although you could probably do this on the client side as well pretty easily by referencing the previous element of the checkbox if you just passed a reference to it (or parent, maybe, depends on whether the label precedes the input or the input is contained in it).</p>\n\n<p>Two, I would also change it so that it only passes back the current item that is being clicked and handle them one at a time.</p>\n\n<p>Assuming that you checkboxes (when rendered) look something like:</p>\n\n<pre><code> &lt;label for=\"something\"&gt;CheckBox 1&lt;/label&gt;\n &lt;input type='checkbox' id='ctl00_....' value='1' onclick=\"OnCheckBoxClicked(this,'CheckBox_1');\" /&gt;\n</code></pre>\n\n<p>Your functions might look like:</p>\n\n<pre><code>function OnCheckBoxClicked(checkbox,identifier)\n{\n // do something based on the checkbox clicked\n\n WebForm_DoCallback('__Page', identifer, UpdateCheckBoxes, {checkbox: checkbox.id, label: identifier } , null, true /* synchronous */);\n}\n\nfunction UpdateCheckBoxes(result,context)\n{\n var checkbox = document.getElementById(context.checkbox);\n var identifier = context.label;\n\n if (result) // AJAX method now returns true/false as context holds info on controls\n {\n ... do something...\n }\n}\n</code></pre>\n" }, { "answer_id": 228469, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 0, "selected": false, "text": "<p>you can add an event to the checkbox control on the onclick() event. and send the id of the control as a parameter and then update the attributes of the desired control</p>\n\n<pre><code>&lt;input type='checkbox' id='ctl00_....' value='1' onclick=\"OnCheckBoxClicked('ctrl_toUpdateID');\" /&gt;\n\n\n\n&lt;script type=\"text/javascript\"&gt;\n\nfunction OnCheckBoxClicked(ctrlID)\n{\n var ctrl = document.getElementById(ctrlID);\n if(ctrl.getAttribute('disabled')\n ctrl.removeAttribute('disabled')\nelse\n ctrl.setAttribute('disabled','disabled')\n\n\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18865/" ]
I would like to apply some logic to a page containing a CheckBoxList control when the user checks or unchecks individual checkbox items. Say, for instance to dynamically show or hide a related control. I came up with a way using ASP.Net 2.0 callback mechanism (AJAX) with a combination of client-side Javascript and server-side logic in the code-behind. However, this solution is not very bullet-proof (i.e. most likely suffers from timing issues). It is not portable, because the code needs to know the sequential ids of individual items, etc. The code I came up with is separated in two functions, one handling the `onclick` event, and the other processing the returned callback string : ``` <script type="text/javascript"> function OnCheckBoxClicked() { // gathers the semi-colon separated list of labels, // associated with the currently checked items var texts = ''; // iterate over each individual checkbox item // items in a checkboxlist are sequential, so // stop iteration at the first missing sequence number for (var index = 0; index < 99; index++) { var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index); if (checkbox == null) break; if (checkbox.checked) { // find label associated with the current checkbox item var labels = document.getElementsByTagName('label'); for (var index_ = 0; index_ < labels.length; index_ ++) { if (labels[index_].htmlFor == checkbox.id) { texts = texts + labels[index_].innerHTML + ';'; break; } } } } // perform callback request // result will be processed by the UpdateCheckBoxes function WebForm_DoCallback('__Page', '_checkbox' + texts, UpdateCheckBoxes, 'checkbox', null, true /* synchronous */); } </script> ``` In this example, my checkboxes match categories of a blog post. I need to process the resulting callback string as containing a list of semicolon-separated names of checkboxes to check/uncheck, in order to make sure that related parent/child categories are synchronized correctly. This string results from logic executed on the server. In other cases, the resulting callback string might be something else. ``` <script type="text/javascript"> function UpdateCheckBoxes(returnmessage, context) { if (returnmessage == null || returnmessage == '') return ; // iterate over each individual checkbox item // items in a checkboxlist are sequential, so // stop iteration at the first missing sequence number for (var index = 0; index < 99; index++) { var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index); if (checkbox == null) break; // find label associated with the current checkbox item var label = ''; var labels = document.getElementsByTagName('label'); for (var index_ = 0; index_ < labels.length; index_ ++) { if (labels[index_].htmlFor == checkbox.id) { label = ';' + labels[index_].innerHTML + ';'; break; } } // perform custom processing based on the contents // of the returned callback string // for instance, here we check whether the returnmessage // contains the string ';' + label + ';' if (returnmessage.indexOf(label, 1) > 0) { // do something } } } </script> ``` Isn't there a more elegant solution to this problem?
I'd do a couple of things. One, I'd figure out a way to pass the value that needs to be passed back to the client-side onclick handler. Depending on how you are populating your CheckBoxList, this might be as simple as adding an "onclick" attribute to the ListItem for that checkbox that calls your function with the same value assigned to the label, say 'OnCheckBoxClicked(this,'Label'). That would eliminate the need to derive the label, although you could probably do this on the client side as well pretty easily by referencing the previous element of the checkbox if you just passed a reference to it (or parent, maybe, depends on whether the label precedes the input or the input is contained in it). Two, I would also change it so that it only passes back the current item that is being clicked and handle them one at a time. Assuming that you checkboxes (when rendered) look something like: ``` <label for="something">CheckBox 1</label> <input type='checkbox' id='ctl00_....' value='1' onclick="OnCheckBoxClicked(this,'CheckBox_1');" /> ``` Your functions might look like: ``` function OnCheckBoxClicked(checkbox,identifier) { // do something based on the checkbox clicked WebForm_DoCallback('__Page', identifer, UpdateCheckBoxes, {checkbox: checkbox.id, label: identifier } , null, true /* synchronous */); } function UpdateCheckBoxes(result,context) { var checkbox = document.getElementById(context.checkbox); var identifier = context.label; if (result) // AJAX method now returns true/false as context holds info on controls { ... do something... } } ```
227,711
<p>I found <a href="http://www.jenitennison.com/xslt/grouping/muenchian.html" rel="noreferrer">this page</a> describing the Muenchian method, but I think I'm applying it wrong.</p> <p>Consider that this would return a set of ages:</p> <pre><code>/doc/class/person/descriptive[(@name='age')]/value </code></pre> <blockquote> <p>1..2..2..2..3..3..4..7</p> </blockquote> <p>But I would like a nodeset only one node for each age.</p> <blockquote> <p>1..2..3..4..7</p> </blockquote> <p>Each of these seem to return all of the values, instead of unique values:</p> <pre><code>/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value /doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)] </code></pre> <p>What am I missing?</p>
[ { "answer_id": 227765, "author": "JacobE", "author_id": 30056, "author_profile": "https://Stackoverflow.com/users/30056", "pm_score": 1, "selected": false, "text": "<p>Aren't you missing a reference to 'descriptive' right after the preceding-value? Some thing like the following:</p>\n\n<pre><code>/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::descriptive[@name='age']/value)]/value\n</code></pre>\n\n<p>(Haven't tested it)</p>\n" }, { "answer_id": 227805, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 6, "selected": true, "text": "<p>Here's an example:</p>\n\n<pre><code>&lt;root&gt;\n &lt;item type='test'&gt;A&lt;/item&gt;\n &lt;item type='test'&gt;B&lt;/item&gt;\n &lt;item type='test'&gt;C&lt;/item&gt;\n &lt;item type='test'&gt;A&lt;/item&gt;\n &lt;item type='other'&gt;A&lt;/item&gt;\n &lt;item type='test'&gt;B&lt;/item&gt;\n &lt;item type='other'&gt;D&lt;/item&gt;\n &lt;item type=''&gt;A&lt;/item&gt;\n&lt;/root&gt;\n</code></pre>\n\n<p>And the XPath:</p>\n\n<pre><code>//preceding::item/preceding::item[not(.=preceding-sibling::item)]/text()\n</code></pre>\n\n<p>Results:\nA B C D</p>\n\n<p><strong>EDIT</strong>:\nAs mousio commented this doesn't capture the last item in a list if it's the only time it appears. Taking that and Fëanor's comment into account, here's a better solution:</p>\n\n<pre><code>/root/item[not(.=preceding-sibling::item)]\n</code></pre>\n" }, { "answer_id": 230028, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 4, "selected": false, "text": "<p>Here is the Muenchian version of BQ's answer using his data:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n &lt;xsl:output indent=\"yes\" method=\"text\"/&gt;\n &lt;xsl:key name=\"item-by-value\" match=\"item\" use=\".\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:apply-templates select=\"/root/item\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"item\"&gt;\n &lt;xsl:if test=\"generate-id() = generate-id(key('item-by-value', normalize-space(.)))\"&gt;\n &lt;xsl:value-of select=\".\"/&gt;\n &lt;xsl:text&gt;\n&lt;/xsl:text&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"text()\"&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>This transform gives</p>\n\n<p>A<br/>\n B<br/>\n C<br/>\n D</p>\n\n<ol>\n<li>The <code>key()</code> lookup above in the template for <code>item</code> returns a nodeset containing all the <code>item</code> elements with the same string value as the context node. </li>\n<li>If you apply a function that expects a single node to a nodeset, it will operate on the first node in that nodeset. </li>\n<li>All calls to <code>generate-id()</code> are guaranteed to generate the same ID for a given node during a single pass through a document. </li>\n<li>Therefore, the test will be true if the context node is the same node as the first one returned by the <code>key()</code> call.</li>\n</ol>\n" }, { "answer_id": 1112524, "author": "matpie", "author_id": 51021, "author_profile": "https://Stackoverflow.com/users/51021", "pm_score": 2, "selected": false, "text": "<p>The Muenchian method uses keys to create a unique list of items from the node set. For your data, the key would look like this:</p>\n\n<pre><code>&lt;!-- Set the name to whatever you want --&gt;\n&lt;xsl:key name=\"PeopleAges\" match=\"/doc/class/person/descriptive[@name = 'age']/value\" use=\".\" /&gt;\n</code></pre>\n\n<p>From there, I would personally use <code>xsl:apply-templates</code> but you can use the following <code>select</code> attribute in other places:</p>\n\n<pre><code>&lt;!-- you can change `apply-templates` to: `copy-of` or `for-each`. --&gt;\n&lt;xsl:apply-templates select=\"/doc/class/person/descriptive[@name = 'age']/value[count(. | key('PeopleAges', .)[1]) = 1]\" /&gt;\n</code></pre>\n\n<p>The accompanying match for the above is much simpler:</p>\n\n<pre><code>&lt;xsl:template match=\"person/descriptive[@name = 'age']/value\"&gt;\n &lt;strong&gt;Age: &lt;/strong&gt;&lt;xsl:value-of select=\".\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 21256063, "author": "Grégory", "author_id": 3218843, "author_profile": "https://Stackoverflow.com/users/3218843", "pm_score": 3, "selected": false, "text": "<p>For those who still look for a select distinct in XSLT:</p>\n\n<p>With XSLT 2.0,\nyou can use\n\"distinct-values(/doc/class/person/descriptive[(@name='age')]/value)\"</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525/" ]
I found [this page](http://www.jenitennison.com/xslt/grouping/muenchian.html) describing the Muenchian method, but I think I'm applying it wrong. Consider that this would return a set of ages: ``` /doc/class/person/descriptive[(@name='age')]/value ``` > > 1..2..2..2..3..3..4..7 > > > But I would like a nodeset only one node for each age. > > 1..2..3..4..7 > > > Each of these seem to return all of the values, instead of unique values: ``` /doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value /doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)] ``` What am I missing?
Here's an example: ``` <root> <item type='test'>A</item> <item type='test'>B</item> <item type='test'>C</item> <item type='test'>A</item> <item type='other'>A</item> <item type='test'>B</item> <item type='other'>D</item> <item type=''>A</item> </root> ``` And the XPath: ``` //preceding::item/preceding::item[not(.=preceding-sibling::item)]/text() ``` Results: A B C D **EDIT**: As mousio commented this doesn't capture the last item in a list if it's the only time it appears. Taking that and Fëanor's comment into account, here's a better solution: ``` /root/item[not(.=preceding-sibling::item)] ```
227,729
<p>I am a self taught vb6 programmer who uses DAO. Below is an example of a typical piece of code that I could churn out:</p> <pre><code>Sub cmdMultiplier_Click() 'Button on form, user interface ' dim Rec1 as recordset dim strSQL as string strSQL = "select * from tblCustomers where ID = " &amp; CurrentCustomerID 'inline SQL ' set rec1 = GlobalDataBase.openrecordset(strSQL) ' Data access ' if rec1.bof &lt;&gt; true or rec1.eof &lt;&gt; true then if rec1.fields("Category").value = 1 then PriceMultiplier = 0.9 ' Business Logic ' else priceMultiplier = 1 end if end if End Sub </code></pre> <p>Please pretend that the above is the entire source code of a CRUD application. I know this design is bad, everything is mixed up together. Ideally it should have three distinct layers, user interface, business logic and data access. I sort-of get why this is desirable but I don't know how it's done and I suspect that's why I don't fully get why such a separation is good. I think I'd be a lot further down the road if someone could refactor the above ridiculously trivial example into 3 tiers. </p>
[ { "answer_id": 227764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>What is the purpose of the button?</p>\n\n<p>My first steps would be:</p>\n\n<ul>\n<li>extract the part accessing the database. (warning: air code ahead)</li>\n</ul>\n\n<pre><code>function getCustomer(CurrentCustomerID as Long)\n\nstrSQL = \"select * from tblCustomers where ID = \" &amp; CurrentCustomerID\nset rec1 = GlobalDataBase.openrecordset(strSQL)\nresult = 1\n\nif rec1.recordcount &gt;0 then\n getCustomer = rec1\nelse\n getCustomer = false\nendif\nend function\n</code></pre>\n\n<ul>\n<li>compose the business logic function:</li>\n</ul>\n\n<pre><code>function getCustomerDiscount(customerID as Long)\n\ncustomer = getCustomer(customerID)\n\nres = 1\nif customer then\n if customer(\"category\")=1) then\n res = .9\n endif\nendif\n\ngetcustomerdiscount = res\n\nend function\n</code></pre>\n\n<ul>\n<li>then, change the button:</li>\n</ul>\n\n<pre><code>Sub cmdMultiplier_Click() \n pricemultiplier = getcustomerdiscount(currentcustomerid)\nend sub\n</code></pre>\n" }, { "answer_id": 228085, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<p>Typically you will have your UI code responding to the events raised by the user, in this case the Button Click.</p>\n\n<p>After that it really depends on how your program is designed, the most basic design would be to reference a Customer instance and it would contain a multiplier property.\nYour customer object is populated from data in your DAL.</p>\n\n<p>Validation for UI would go in UI layer, business validation rules could go into your business object, and then your DAL is your persistence layer.</p>\n\n<p>Here is a very basic pseudo-code example:</p>\n\n<pre><code>btnClick\n Dim Cust as New Customer(ID)\n multplr = Cust.DiscountMultiplier\nEnd Click\n\nClass Customer\n Sub New(ID)\n Data = DAL.GetCustomerData(ID)\n Me.Name = Data(\"Name\")\n Me.Address = Data(\"Address\")\n Me.DiscountMultiplier = Data(\"DiscountMultiplier\")\n End Sub\n Property ID\n Property Name\n Property Address\n Property DiscountMultiplier\n Return _discountMultiplier\n End\nEnd Class\n\n\nClass DAL\n Function GetCustomerData(ID)\n SQL = \"Paramaterized SQL\"\n Return Data\n End Function\nEnd Class\n</code></pre>\n" }, { "answer_id": 228359, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": true, "text": "<p>a trivial example, yes, but with all the basic elements - they just belong in 3 different classes (see below). The main reason for this is the \"separation of concerns\" principle, i.e. the GUI is only concerned with GUI things, the Biz Logic layer is only concerned with the business rules, and the data-access layer is only concerned with data representations. This allows each layer to be maintained independently and reused across applications:</p>\n\n<pre><code>'in Form class - button handler\nSub cmdMultiplier_Click()\n PriceMultiplier = ComputePriceMultiplier(CurrentCustomerId)\nEnd Sub\n\n'in Biz Logic class\nFunction ComputePriceMultiplier(custId as Integer) as Double\n Dim cust as Customer = GetCustomer(custId)\n if cust.Category = 1 then 'please ignore magic number, real code uses enums\n return 0.9\n end if\n return 1\nEnd Function\n\n'in Data Access Layer class\nFunction GetCustomer(custId as Integer) as Customer\n Dim cust as Customer = New Customer 'all fields/properties to default values\n Dim strSQL as String = \"select * from tblCustomers where ID = \" &amp; custId\n set rec1 = GlobalDataBase.openrecordset(strSQL) ' Data access '\n if rec1.bof &lt;&gt; true or rec1.eof &lt;&gt; true then\n cust.SetPropertiesFromRecord(rec1)\n end if\n return cust\nEnd Function\n</code></pre>\n\n<p>[a 'real' application would cache the current customer, have constants or stored procedures for the customer query, etc.; ignored for brevity]</p>\n\n<p>Contrast this with your original everything-in-the-button-handler example (which is appallingly common in VB code because it is so easy to do it that way) - if you needed the price-multiplier rule in another application, you'd have to copy, paste, and edit the code into that application's button-handler. Now there would be two places to maintain the same business rule, and two places where the same customer query was executed.</p>\n" }, { "answer_id": 228446, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 1, "selected": false, "text": "<p>Knowing how to refactor is a good thing. From now you will know how to separate layers.<br>\nHowever, I think your time will be better spend to upgrade the tools you are using at the same time. Do you have consider to do it with VB.Net ?</p>\n\n<p>A way to do it will preserving your existing code base is to code the Data layer and BR in VB.Net. Then to expose the BR through COM Interface (this is a check box option in the project). You can then use the new BR from your current interface.</p>\n\n<p>Once all BR and DAL done, you will be a step away to a complete new platform.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6164/" ]
I am a self taught vb6 programmer who uses DAO. Below is an example of a typical piece of code that I could churn out: ``` Sub cmdMultiplier_Click() 'Button on form, user interface ' dim Rec1 as recordset dim strSQL as string strSQL = "select * from tblCustomers where ID = " & CurrentCustomerID 'inline SQL ' set rec1 = GlobalDataBase.openrecordset(strSQL) ' Data access ' if rec1.bof <> true or rec1.eof <> true then if rec1.fields("Category").value = 1 then PriceMultiplier = 0.9 ' Business Logic ' else priceMultiplier = 1 end if end if End Sub ``` Please pretend that the above is the entire source code of a CRUD application. I know this design is bad, everything is mixed up together. Ideally it should have three distinct layers, user interface, business logic and data access. I sort-of get why this is desirable but I don't know how it's done and I suspect that's why I don't fully get why such a separation is good. I think I'd be a lot further down the road if someone could refactor the above ridiculously trivial example into 3 tiers.
a trivial example, yes, but with all the basic elements - they just belong in 3 different classes (see below). The main reason for this is the "separation of concerns" principle, i.e. the GUI is only concerned with GUI things, the Biz Logic layer is only concerned with the business rules, and the data-access layer is only concerned with data representations. This allows each layer to be maintained independently and reused across applications: ``` 'in Form class - button handler Sub cmdMultiplier_Click() PriceMultiplier = ComputePriceMultiplier(CurrentCustomerId) End Sub 'in Biz Logic class Function ComputePriceMultiplier(custId as Integer) as Double Dim cust as Customer = GetCustomer(custId) if cust.Category = 1 then 'please ignore magic number, real code uses enums return 0.9 end if return 1 End Function 'in Data Access Layer class Function GetCustomer(custId as Integer) as Customer Dim cust as Customer = New Customer 'all fields/properties to default values Dim strSQL as String = "select * from tblCustomers where ID = " & custId set rec1 = GlobalDataBase.openrecordset(strSQL) ' Data access ' if rec1.bof <> true or rec1.eof <> true then cust.SetPropertiesFromRecord(rec1) end if return cust End Function ``` [a 'real' application would cache the current customer, have constants or stored procedures for the customer query, etc.; ignored for brevity] Contrast this with your original everything-in-the-button-handler example (which is appallingly common in VB code because it is so easy to do it that way) - if you needed the price-multiplier rule in another application, you'd have to copy, paste, and edit the code into that application's button-handler. Now there would be two places to maintain the same business rule, and two places where the same customer query was executed.
227,731
<p>I need to do some large integer math. Are there any classes or structs out there that represent a 128-bit integer and implement all of the usual operators?</p> <p>BTW, I realize that <code>decimal</code> can be used to represent a 96-bit int.</p>
[ { "answer_id": 227757, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>No, there's nothing in .NET &lt;= 3.5. I'm hoping/expecting that <a href=\"https://web.archive.org/web/20070120081853/http://blogs.msdn.com/bclteam/archive/2007/01/16/introducing-system-numeric-biginteger-inbar-gazit.aspx\" rel=\"nofollow noreferrer\">BigInteger</a> will make its return in .NET 4.0. (It was <a href=\"https://web.archive.org/web/20080107113836/http://blogs.msdn.com/bclteam/archive/2008/01/04/where-did-biginteger-go-melitta-andersen.aspx\" rel=\"nofollow noreferrer\">cut from .NET 3.5</a>.)</p>\n" }, { "answer_id": 227759, "author": "Craig", "author_id": 2047, "author_profile": "https://Stackoverflow.com/users/2047", "pm_score": -1, "selected": false, "text": "<p>I believe Mono has a BigInteger implementation that you should be able to track down the source for.</p>\n" }, { "answer_id": 227795, "author": "Larsenal", "author_id": 337, "author_profile": "https://Stackoverflow.com/users/337", "pm_score": 7, "selected": true, "text": "<p><strong>It's here in <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-6.0\" rel=\"nofollow noreferrer\">System.Numerics</a></strong>. &quot;The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.&quot;</p>\n<pre><code>var i = System.Numerics.BigInteger.Parse(&quot;10000000000000000000000000000000&quot;);\n</code></pre>\n" }, { "answer_id": 228874, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": "<p>If you don't mind making reference to the J# library (vjslib.dll included with VS by default) there is already and implementation of BigInteger in .NET</p>\n\n<pre><code>using java.math;\n\npublic static void Main(){\n BigInteger biggy = new BigInteger(....)\n\n}\n</code></pre>\n" }, { "answer_id": 5384298, "author": "Charles Burns", "author_id": 161816, "author_profile": "https://Stackoverflow.com/users/161816", "pm_score": 3, "selected": false, "text": "<p><code>BigInteger</code> is now a standard part of C# and friends in .NET 4.0. See: <a href=\"http://weblogs.asp.net/gunnarpeipman/archive/2009/05/23/net-framework-4-0-introducing-biginteger.aspx\" rel=\"nofollow noreferrer\">Gunnar Peipman's ASP.NET blog</a>.</p>\n<p>Note that the CPU can generally work with ordinary integers much more quickly and in constant time, especially when using the usual math operators (+, -, /, ...) because these operators typically map directly to single CPU instructions.</p>\n<p>With <code>BigInteger</code>, even the most basic math operations are much slower function calls to methods whose runtime varies with the size of the number. This is because <code>BigInteger</code> implements arbitrary precision arithmetic, which adds considerable but necessary overhead.\nThe benefit is that BigIntegers are not limited to 64 or even 128 bits, but by available system memory (or about 2<sup>64</sup> bits of precision, whichever comes first).<br />\nRead <a href=\"https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 20600584, "author": "Lessneek", "author_id": 240947, "author_profile": "https://Stackoverflow.com/users/240947", "pm_score": 2, "selected": false, "text": "<p>C# PCL library for computations with big numbers such as Int128 and Int256.\n<a href=\"https://github.com/lessneek/BigMath\" rel=\"nofollow noreferrer\">https://github.com/lessneek/BigMath</a></p>\n" }, { "answer_id": 28258429, "author": "Rick Sladkey", "author_id": 553613, "author_profile": "https://Stackoverflow.com/users/553613", "pm_score": 6, "selected": false, "text": "<p>While <code>BigInteger</code> is the best solution for most applications, if you have performance critical numerical computations, you can use the complete <code>Int128</code> and <code>UInt128</code> implementations in my <a href=\"https://github.com/ricksladkey/dirichlet-numerics\"><strong>Dirichlet.Numerics</strong></a> library. These types are useful if <code>Int64</code> and <code>UInt64</code> are too small but <code>BigInteger</code> is too slow.</p>\n" }, { "answer_id": 48994866, "author": "Brett Allen", "author_id": 224111, "author_profile": "https://Stackoverflow.com/users/224111", "pm_score": 2, "selected": false, "text": "<p>GUID is backed by a 128 bit integer in .NET framework; though it doesn't come with any of the typical integer type methods.</p>\n\n<p>I've written a handler for GUID before to treat it as a 128 bit integer, but this was for a company I worked for ~8 years ago. I no longer have access to the source code.</p>\n\n<p>So if you need native support for a 128 bit integer, and don't want to rely on BigInteger for whatever reason, you could probably hack GUID to server your purposes.</p>\n" }, { "answer_id": 73005626, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.int128?view=net-7.0\" rel=\"noreferrer\"><code>System.Int128</code></a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.uint128?view=net-7.0\" rel=\"noreferrer\"><code>System.UInt128</code></a> have been available since .NET Core 7.0 Preview 5</p>\n<p>They were implemented in <a href=\"https://github.com/dotnet/runtime/issues/67151\" rel=\"noreferrer\">Add support for Int128 and UInt128 data types</a></p>\n<p>I don't know why they aren't in the <a href=\"https://devblogs.microsoft.com/dotnet/announcing-dotnet-7-preview-5/\" rel=\"noreferrer\">.NET 7 Preview 5</a> <a href=\"https://github.com/dotnet/core/issues/7441\" rel=\"noreferrer\">announcement</a> but in the upcoming .NET 7 Preview 6 announcement there'll also be <a href=\"https://github.com/dotnet/core/issues/7454\" rel=\"noreferrer\"><code>Int128Converter</code> and <code>UInt128Converter</code></a> for the new types in Preview 5</p>\n<p>They didn't have <a href=\"https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/#types-without-language-support\" rel=\"noreferrer\">C# support</a> yet though, just like <code>System.Half</code>, so you'll have to use <code>Int128</code> explicitly instead of using a native C# keyword</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
I need to do some large integer math. Are there any classes or structs out there that represent a 128-bit integer and implement all of the usual operators? BTW, I realize that `decimal` can be used to represent a 96-bit int.
**It's here in [System.Numerics](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-6.0)**. "The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds." ``` var i = System.Numerics.BigInteger.Parse("10000000000000000000000000000000"); ```
227,762
<p>I am working on an embedded systems project and have run into an issue of the compiler being programatically embedded in the Paradigm C++ IDE. I would like to be able to automate building.</p> <p>The processor is the AMD186ES. I am not working with the OS - just baremetal stuff. I need to generate real-mode 16-bit 8086 machine code from C++. </p> <p>My googling indicates that G++ can build such code. </p> <p>My questions are: </p> <p>Can g++ be configured to build this machine code?</p> <p>Are there other C++ compilers that can do it as well?</p>
[ { "answer_id": 227786, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 4, "selected": false, "text": "<p>Your best bet is probably <a href=\"http://www.openwatcom.org/index.php/Main_Page\" rel=\"noreferrer\">OpenWatcom</a>, which includes a C++ compiler. Back in the early-to-mid 90s, I believe this was the best C/C++ compiler around. It was open-sourced a few years ago.</p>\n" }, { "answer_id": 227800, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>Doesn't your chip vendor (AMD, I guess) have any pointers to compilers for the chip?</p>\n\n<p>If not, you may be able to use some 16-bit DOS compilers - but you'll have several potential big problems:</p>\n\n<ol>\n<li>getting a library for the compiler that is not dependent on the BIOS or MS-DOS</li>\n<li>debugging</li>\n<li>linkers for embedded systems usually have specific support for locating code in specific memory regions. That's not usually included in compilers for DOS, but you may be able to find some sort of linker/locator that'll do the trick for you.</li>\n</ol>\n\n<p>A couple of compilers that are still supported and generate 16-bit code are:</p>\n\n<ul>\n<li><a href=\"http://www.digitalmars.com/\" rel=\"noreferrer\">Digital Mars</a></li>\n<li><a href=\"http://www.openwatcom.org/index.php/Detailed_Contents#A_Wide_Range_of_Host_and_Target_Platforms\" rel=\"noreferrer\">Open Watcom</a></li>\n</ul>\n" }, { "answer_id": 227801, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.google.co.uk/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=woR&amp;q=gcc+cross+compilation+for+embedded+systems&amp;btnG=Search&amp;meta=\" rel=\"nofollow noreferrer\">This google search</a> shows a series of links for setting gcc up as a cross compiler. To get it to target something other than a standard ELF binary you can frig the output. <a href=\"http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html\" rel=\"nofollow noreferrer\">This link</a> discusses excluding the standard libraries and customising the output format. You may have to do some fiddling to get it to work.</p>\n\n<p>As an alternative <a href=\"http://www.openwatcom.org/index.php/Main_Page\" rel=\"nofollow noreferrer\">openwatcom.org</a> has an open-source version of the Watcom C compiler, which might also be able to do what you want.</p>\n" }, { "answer_id": 227824, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "<p>Take a look at <a href=\"http://homepage.ntlworld.com/robert.debath/\" rel=\"noreferrer\">bcc</a>, which is a 16-bit x86 C compiler. For example, there are also <a href=\"http://packages.debian.org/bcc\" rel=\"noreferrer\">Debian packages for it</a>.</p>\n" }, { "answer_id": 227826, "author": "call me Steve", "author_id": 24334, "author_profile": "https://Stackoverflow.com/users/24334", "pm_score": 2, "selected": false, "text": "<p>Not sure but I think old version of borland c++ was able to do that.\nyou can download version 5.5 t : <a href=\"http://cc.codegear.com/free/cppbuilder\" rel=\"nofollow noreferrer\">here</a>\ngood luck</p>\n" }, { "answer_id": 227828, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 0, "selected": false, "text": "<p>It has been a long time since I've looked at Paradigm stuff (are they still around?) -- are you sure they don't have command-line equivalents for the compiler? My recollection is that they were built on top of Borland's compiler toolchain... So maybe an old copy of Borland compilers might do the trick?</p>\n\n<p>--\nAh, looking a little futher, I find that Paradigm is still around (www.devtools.com) selling X86 tools. (Must be a cash cow!)</p>\n\n<p>Their professional product includes scripting... Depending on the amount of work you plan to do, it just might be worth it to bite the bullet and buy their full offering...</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 236309, "author": "plan9assembler", "author_id": 1710672, "author_profile": "https://Stackoverflow.com/users/1710672", "pm_score": 1, "selected": false, "text": "<p>80186 free C compiler:</p>\n\n<p><a href=\"http://coding.derkeiler.com/Archive/General/comp.arch.embedded/2005-09/msg01063.html\" rel=\"nofollow noreferrer\">http://coding.derkeiler.com/Archive/General/comp.arch.embedded/2005-09/msg01063.html</a></p>\n" }, { "answer_id": 12829806, "author": "Hawken", "author_id": 800270, "author_profile": "https://Stackoverflow.com/users/800270", "pm_score": 4, "selected": true, "text": "<p>I am currently using gnu <code>as</code> (part of binutils and the assembler used for gcc) and I have successfully been assembling 16bit assembly code with the following:</p>\n\n<pre><code>as &lt;file&gt;\nld --oformat binary -Ttext 0x0 -e start &lt;file&gt;\n</code></pre>\n\n<p>with my assembly files starting out with:</p>\n\n<pre><code>.code16\n.globl start\n.text\nstart:\n</code></pre>\n\n<p>since its plain binary omitting the lines,</p>\n\n<pre><code>.globl start\nstart:\n</code></pre>\n\n<p>will simply yield an warning, even though flat binaries need no entry point.</p>\n\n<hr>\n\n<p>something I learned the hard way;</p>\n\n<pre><code>-Ttext 0x0\n</code></pre>\n\n<p>is critical, otherwise the <code>.text</code> segment is pushed outside of 16bit addressing range (don't ask me why)</p>\n\n<p>I am personally still learning assembly, so this is just my way, not necessarily the best way.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> If you are writing boot code, you should change </p>\n\n<pre><code>-Ttext 0x0\n</code></pre>\n\n<p>to</p>\n\n<pre><code>-Ttext 0x7c00\n</code></pre>\n\n<p>this will offset your memory addresses by <code>0x7c00</code> since boot code is usually loaded at <code>0x7c00</code> by the BIOS.</p>\n" }, { "answer_id": 16326472, "author": "Janus Troelsen", "author_id": 309483, "author_profile": "https://Stackoverflow.com/users/309483", "pm_score": 3, "selected": false, "text": "<p>There's a patch for GCC 4.3: <strong><a href=\"http://gcc.gnu.org/ml/gcc-patches/2007-07/msg02108.html\" rel=\"nofollow noreferrer\">New back end ia16: 16-bit Intel x86</a></strong></p>\n\n<p>And <a href=\"http://gcc.gnu.org/ml/gcc-patches/2007-08/msg02195.html\" rel=\"nofollow noreferrer\">here's an update for it</a>. Note that it probably doesn't work very well, for example, the updated post says: \"Constructors and destructors are now supported, but for some reason they\n only work on the elks configuration.\"</p>\n\n<p>This Docker container has a build of it: <a href=\"https://registry.hub.docker.com/u/ysangkok/ia16-gcc-rask\" rel=\"nofollow noreferrer\">https://registry.hub.docker.com/u/ysangkok/ia16-gcc-rask</a></p>\n\n<p>I didn't manage to make DOS binaries yet: <a href=\"https://stackoverflow.com/questions/30191000/how-do-i-assemble-gas-assembly-and-link-it-with-the-open-watcom-c-library\">How do I assemble GAS assembly and link it with the Open Watcom C library?</a></p>\n" }, { "answer_id": 25473833, "author": "Janus Troelsen", "author_id": 309483, "author_profile": "https://Stackoverflow.com/users/309483", "pm_score": 2, "selected": false, "text": "<p>The most recent as per 2014 is <strong><a href=\"https://github.com/lkundrak/dev86\" rel=\"nofollow\">Dev86</a></strong>.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
I am working on an embedded systems project and have run into an issue of the compiler being programatically embedded in the Paradigm C++ IDE. I would like to be able to automate building. The processor is the AMD186ES. I am not working with the OS - just baremetal stuff. I need to generate real-mode 16-bit 8086 machine code from C++. My googling indicates that G++ can build such code. My questions are: Can g++ be configured to build this machine code? Are there other C++ compilers that can do it as well?
I am currently using gnu `as` (part of binutils and the assembler used for gcc) and I have successfully been assembling 16bit assembly code with the following: ``` as <file> ld --oformat binary -Ttext 0x0 -e start <file> ``` with my assembly files starting out with: ``` .code16 .globl start .text start: ``` since its plain binary omitting the lines, ``` .globl start start: ``` will simply yield an warning, even though flat binaries need no entry point. --- something I learned the hard way; ``` -Ttext 0x0 ``` is critical, otherwise the `.text` segment is pushed outside of 16bit addressing range (don't ask me why) I am personally still learning assembly, so this is just my way, not necessarily the best way. --- **EDIT:** If you are writing boot code, you should change ``` -Ttext 0x0 ``` to ``` -Ttext 0x7c00 ``` this will offset your memory addresses by `0x7c00` since boot code is usually loaded at `0x7c00` by the BIOS.
227,775
<p>Let's say I have a class in my web app called class "Foo". It has an initialise() method that is called when the bean is created using Spring. The initialise() method then tries to load an external service and assign it to a field. If the service could not be contacted, the field will be set to null. </p> <pre><code>private Service service; public void initialise() { // load external service // set field to the loaded service if contacted // set to field to null if service could not be contacted } </code></pre> <p>When someone calls the method get() on the class "Foo" the service will be invoked if it was started in the initialise() method. If the field for the service is null, I want to try and load the external service.</p> <pre><code>public String get() { if (service == null) { // try and load the service again } // perform operation on the service is service is not null } </code></pre> <p>Is it possible that I may have sync issues if I would do something like this?</p>
[ { "answer_id": 227812, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>Yes, you will have a sync problem.</p>\n\n<p>Lets assume you have single servlet:</p>\n\n<pre><code>public class FooServlet extends HttpServlet {\n\n private MyBean myBean;\n\n public void init() {\n myBean = (MyBean) WebApplicationContextUtils.\n getRequiredWebApplicationContext(getServletContext()).getBean(\"myBean\");\n }\n\n public void doGet(HttpRequest request, HttpResponse response) {\n String string = myBean.get();\n ....\n }\n\n}\n\nclass MyBean {\n public String get() {\n if (service == null) {\n // try and load the service again\n }\n // perform operation on the service is service is not null\n }\n}\n</code></pre>\n\n<p>And your bean definition looks like:</p>\n\n<pre><code>&lt;bean id=\"myBean\" class=\"com.foo.MyBean\" init-method=\"initialise\" /&gt;\n</code></pre>\n\n<p>The problem is that your servlet instance is used by multiple request threads. Hence, the code block guarded by service == null may be entered by multiple threads. </p>\n\n<p>The best fix (avoiding double-checked-locking etc) is:</p>\n\n<pre><code>class MyBean {\n public synchronized String get() {\n if (service == null) {\n // try and load the service again\n }\n // perform operation on the service is service is not null\n }\n}\n</code></pre>\n\n<p>Hope this makes sense. Drop a comment if not.</p>\n" }, { "answer_id": 227964, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 2, "selected": true, "text": "<p><em>toolkit</em>'s answer is correct. To solve the problem, just declare your Foo's initialise() method to be synchronized. You could refactor Foo as:</p>\n\n<pre><code>private Service service;\n\npublic synchronized void initialise() {\n if (service == null) {\n // load external service\n // set field to the loaded service if contacted\n }\n}\n\npublic String get() {\n if (service == null) { \n initialise(); // try and load the service again\n }\n // perform operation on the service is service is not null\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30563/" ]
Let's say I have a class in my web app called class "Foo". It has an initialise() method that is called when the bean is created using Spring. The initialise() method then tries to load an external service and assign it to a field. If the service could not be contacted, the field will be set to null. ``` private Service service; public void initialise() { // load external service // set field to the loaded service if contacted // set to field to null if service could not be contacted } ``` When someone calls the method get() on the class "Foo" the service will be invoked if it was started in the initialise() method. If the field for the service is null, I want to try and load the external service. ``` public String get() { if (service == null) { // try and load the service again } // perform operation on the service is service is not null } ``` Is it possible that I may have sync issues if I would do something like this?
*toolkit*'s answer is correct. To solve the problem, just declare your Foo's initialise() method to be synchronized. You could refactor Foo as: ``` private Service service; public synchronized void initialise() { if (service == null) { // load external service // set field to the loaded service if contacted } } public String get() { if (service == null) { initialise(); // try and load the service again } // perform operation on the service is service is not null } ```
227,790
<p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p> <p>Example:</p> <pre><code>def burninate(b): c = [] for i in range(3): c.append(b.pop()) return c a = range(6) d = burninate(a) print a, d </code></pre> <p>Output: [0, 1, 2] [5, 4, 3]<br> Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p> <p>Thanks!</p>
[ { "answer_id": 227802, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 3, "selected": false, "text": "<p>You can call <code>burninate()</code> with a copy of the list like this:</p>\n\n<p><code>d = burninate(a[:])</code></p>\n\n<p>or,</p>\n\n<p><code>d = burninate(list(a))</code></p>\n\n<p>The other alternative is to make a copy of the list in your method:</p>\n\n<pre><code>def burninate(b):\n c=[]\n b=b[:]\n for i in range(3):\n c.append(b.pop())\n return c\n\n&gt;&gt;&gt; a = range(6)\n&gt;&gt;&gt; b = burninate(a)\n&gt;&gt;&gt; print a, b\n&gt;&gt;&gt; [0, 1, 2, 3, 4, 5] [5, 4, 3]\n</code></pre>\n" }, { "answer_id": 227810, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>A slightly more readable way to do the same thing is:</p>\n\n<pre><code>d = burninate(list(a))\n</code></pre>\n\n<p>Here, the <code>list()</code> constructor creates a new list based on <code>a</code>.</p>\n" }, { "answer_id": 227850, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>Other versions:</p>\n\n<pre><code>def burninate(b):\n c = []\n for i in range(1, 4):\n c.append(b[-i])\n return c\n</code></pre>\n\n<pre><code>def burninate(b):\n c = b[-4:-1]\n c.reverse()\n return c\n</code></pre>\n\n<p>And someday you will love list comprehensions:</p>\n\n<pre><code>def burninate(b):\n return [b[-i] for i in range(1,4)]\n</code></pre>\n" }, { "answer_id": 227854, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 3, "selected": false, "text": "<p>A more general solution would be to <code>import copy</code>, and use <code>copy.copy()</code> on the parameter.</p>\n" }, { "answer_id": 227855, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 5, "selected": true, "text": "<p>As other answers have suggested, you can provide your function with a copy of the list.</p>\n\n<p>As an alternative, your function could take a copy of the argument:</p>\n\n<pre><code>def burninate(b):\n c = []\n b = list(b)\n for i in range(3):\n c.append(b.pop())\n return c\n</code></pre>\n\n<p>Basically, you need to be clear in your mind (and in your documentation) whether your function will change its arguments. In my opinion, functions that return computed values should not change their arguments, and functions that change their arguments should not return anything. See python's [].sort(), [].extend(), {}.update(), etc. for examples. Obviously there are exceptions (like .pop()).</p>\n\n<p>Also, depending on your particular case, you could rewrite the function to avoid using pop() or other functions that modify the argument. e.g.</p>\n\n<pre><code>def burninante(b):\n return b[:-4:-1] # return the last three elements in reverse order\n</code></pre>\n" }, { "answer_id": 227875, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 0, "selected": false, "text": "<pre><code>burninate = lambda x: x[:-4:-1]</code></pre>\n" }, { "answer_id": 523600, "author": "Alexandre Hamez", "author_id": 21584, "author_profile": "https://Stackoverflow.com/users/21584", "pm_score": 1, "selected": false, "text": "<p>You can use copy.deepcopy()</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5625/" ]
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one? Example: ``` def burninate(b): c = [] for i in range(3): c.append(b.pop()) return c a = range(6) d = burninate(a) print a, d ``` Output: [0, 1, 2] [5, 4, 3] Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3] Thanks!
As other answers have suggested, you can provide your function with a copy of the list. As an alternative, your function could take a copy of the argument: ``` def burninate(b): c = [] b = list(b) for i in range(3): c.append(b.pop()) return c ``` Basically, you need to be clear in your mind (and in your documentation) whether your function will change its arguments. In my opinion, functions that return computed values should not change their arguments, and functions that change their arguments should not return anything. See python's [].sort(), [].extend(), {}.update(), etc. for examples. Obviously there are exceptions (like .pop()). Also, depending on your particular case, you could rewrite the function to avoid using pop() or other functions that modify the argument. e.g. ``` def burninante(b): return b[:-4:-1] # return the last three elements in reverse order ```
227,807
<p>I have a Rails app that sets a cookie and does a redirect to another server once the user is logged in. However, the cookie that the Rails app sets isn't seen by the server for some reason. I've tried setting http_only to false but I still can't even see the cookie unless the domain is the same as my Rails app. Here's the code I'm using to set the cookie:</p> <pre><code>cookies[:dev_appserver_login] = { :value =&gt; "#{email}:#{nick}:#{admin}:#{hsh}", :domain =&gt; "webserver-to-redirect-to", :expires =&gt; 30.days.from_now } redirect_to session[:dest_url] </code></pre> <p>If I manually create a cookie with the <a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="nofollow noreferrer">Web Developer extension</a> in Firefox it works fine, but not when Rails does it. Any ideas?</p>
[ { "answer_id": 227878, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 4, "selected": true, "text": "<p>What are the redirecting and redirected-to servers? You can only set ‘domain’ to the current hostname or a parent domain, so if you're on a.example.com and you're redirecting to b.example.com, you have to set ‘domain’ to .example.com, <em>not</em> b.example.com as implied in the code snippet.</p>\n\n<p>(And open domains like the .com TLD aren't themselves allowed as domain values, so if you want to pass a cookie from a.example.com to b.somewhereelse.com you will need a more complicated solution probably involving changing the code on somewhereelse.com.)</p>\n" }, { "answer_id": 228088, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I still can't even see the cookie unless the domain is the same as my Rails app. </p>\n</blockquote>\n\n<p>That's how cookies are supposed to work. If you're accessing it directly by IP, then as far as the web browser is concerned, your 'domain' is just your IP, so the same rules apply.</p>\n" }, { "answer_id": 24663350, "author": "Elocution Safari", "author_id": 43670, "author_profile": "https://Stackoverflow.com/users/43670", "pm_score": 0, "selected": false, "text": "<p>You can get around this in development mode by editing your /etc/hosts file and creating host names for your apps</p>\n\n<p><code>127.0.0.1 app1.localdev.com, app2.localdev.com</code></p>\n\n<p>Then, when the cookie is created set the domain to '.localdev.com' (note the preceeding period') which will allow any app at any subdomain of localdev.com to read it. </p>\n\n<p>Another broader solution (which is better for production deploys, but more work to set up) is to set up a path proxy for the sub-app so requests to appdomain.com go to app1 and requests to appdomain.com/other-app/ are proxied to the other app. This lets them share the root domain and easily share cookies. </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I have a Rails app that sets a cookie and does a redirect to another server once the user is logged in. However, the cookie that the Rails app sets isn't seen by the server for some reason. I've tried setting http\_only to false but I still can't even see the cookie unless the domain is the same as my Rails app. Here's the code I'm using to set the cookie: ``` cookies[:dev_appserver_login] = { :value => "#{email}:#{nick}:#{admin}:#{hsh}", :domain => "webserver-to-redirect-to", :expires => 30.days.from_now } redirect_to session[:dest_url] ``` If I manually create a cookie with the [Web Developer extension](https://addons.mozilla.org/en-US/firefox/addon/60) in Firefox it works fine, but not when Rails does it. Any ideas?
What are the redirecting and redirected-to servers? You can only set ‘domain’ to the current hostname or a parent domain, so if you're on a.example.com and you're redirecting to b.example.com, you have to set ‘domain’ to .example.com, *not* b.example.com as implied in the code snippet. (And open domains like the .com TLD aren't themselves allowed as domain values, so if you want to pass a cookie from a.example.com to b.somewhereelse.com you will need a more complicated solution probably involving changing the code on somewhereelse.com.)
227,820
<p>I was just writing some quick code and noticed this complier error </p> <blockquote> <p>Using the iteration variable in a lambda expression may have unexpected results.<br> Instead, create a local variable within the loop and assign it the value of the iteration variable.</p> </blockquote> <p>I know what it means and I can easily fix it, not a big deal.<br> But I was wondering why it is a bad idea to use a iteration variable in a lambda?<br> What problems can I cause later on?</p>
[ { "answer_id": 227832, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "<p>Assuming you mean C# here.</p>\n\n<p>It's because of the way the compiler implements closures. Using an iteration variable <em>can</em> cause a problem with accessing a modified closure (note that I said 'can' not 'will' cause a problem because sometimes it doesn't happen depending on what else is in the method, and sometimes you actually want to access the modified closure).</p>\n\n<p>More info:</p>\n\n<p><a href=\"http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx</a></p>\n\n<p>Even more info:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx</a></p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx</a></p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx</a></p>\n" }, { "answer_id": 227833, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>Consider this code:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>List&lt;Action&gt; actions = new List&lt;Action&gt;();\n\nfor (int i = 0; i &lt; 10; i++)\n{\n actions.Add(() =&gt; Console.WriteLine(i));\n}\n\nforeach (Action action in actions)\n{\n action();\n}\n</code></pre>\n<p>What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's because there's just one variable which is captured by all the delegates. It's this kind of behaviour which is unexpected.</p>\n<p>EDIT: I've just seen that you're talking about VB.NET rather than C#. I believe VB.NET has even more complicated rules, due to the way variables maintain their values across iterations. <a href=\"https://devblogs.microsoft.com/vbteam/closures-in-vb-part-5-looping/\" rel=\"nofollow noreferrer\">This post by Jared Parsons</a> gives some information about the kind of difficulties involved - although it's back from 2007, so the actual behaviour may have changed since then.</p>\n" }, { "answer_id": 55317222, "author": "jrh", "author_id": 4975230, "author_profile": "https://Stackoverflow.com/users/4975230", "pm_score": 2, "selected": false, "text": "<h1>Theory of Closures in .NET</h1>\n<p><a href=\"https://web.archive.org/web/20100123174756/http://www.panopticoncentral.net/archive/2006/03/28/11552.aspx\" rel=\"nofollow noreferrer\">Local variables: scope vs. lifetime (plus closures)</a> (Archived 2010)</p>\n<p>(Emphasis mine)</p>\n<blockquote>\n<p>What happens in this case is we use a closure. A closure is just a special structure that lives outside of the method which contains the local variables that need to be referred to by other methods. <strong>When a query refers to a local variable (or parameter), that variable is captured by the closure and all references to the variable are redirected to the closure.</strong></p>\n</blockquote>\n<p>When you are thinking about how closures work in .NET, I recommend keeping these bullet points in mind, this is what the designers had to work with when they were implementing this feature:</p>\n<ul>\n<li>Note that &quot;variable capture&quot; and lambda expressions are not an IL feature, VB.NET (and C#) had to implement these features using existing tools, in this case, classes and <code>Delegate</code>s.</li>\n<li>Or to put it another way, local variables can't really be persisted beyond their scope. What the language does is make it <em>seem</em> like they can, but it's not a perfect abstraction.</li>\n<li><code>Func(Of T)</code> (i.e., <code>Delegate</code>) instances have no way to store parameters passed into them.</li>\n<li>Though, <code>Func(Of T)</code> do store the instance of the class the method is a part of. This is the avenue the .NET framework used to &quot;remember&quot; parameters passed into lambda expressions.</li>\n</ul>\n<p>Well let's take a look!</p>\n<h1>Sample Code:</h1>\n<p>So let's say you wrote some code like this:</p>\n<pre><code>' Prints 4,4,4,4\nSub VBDotNetSample()\n Dim funcList As New List(Of Func(Of Integer))\n\n For indexParameter As Integer = 0 To 3\n 'The compiler says:\n ' Warning BC42324 Using the iteration variable in a lambda expression may have unexpected results. \n ' Instead, create a local variable within the loop and assign it the value of the iteration variable\n\n funcList.Add(Function()indexParameter)\n\n Next\n\n \n For Each lambdaFunc As Func(Of Integer) In funcList\n Console.Write($&quot;{lambdaFunc()}&quot;)\n\n Next\n\nEnd Sub\n</code></pre>\n<p>You may be expecting the code to print 0,1,2,3, but it actually prints 4,4,4,4, this is because <code>indexParameter</code> has been &quot;captured&quot; in the scope of <code>Sub VBDotNetSample()</code>'s scope, and not in the <code>For</code> loop scope.</p>\n<h1>Decompiled Sample Code</h1>\n<p>Personally, I really wanted to see what kind of code the compiler generated for this, so I went ahead and used JetBrains DotPeek. I took the compiler generated code and hand translated it back to VB.NET.</p>\n<p>Comments and variable names mine. The code was simplified slightly in ways that don't affect the behavior of the code.</p>\n<pre><code>Module Decompiledcode\n ' Prints 4,4,4,4\n Sub CompilerGenerated()\n\n Dim funcList As New List(Of Func(Of Integer))\n \n '***********************************************************************************************\n ' There's only one instance of the closureHelperClass for the entire Sub\n ' That means that all the iterations of the for loop below are referencing\n ' the same class instance; that means that it can't remember the value of Local_indexParameter\n ' at each iteration, and it only remembers the last one (4).\n '***********************************************************************************************\n Dim closureHelperClass As New ClosureHelperClass_CompilerGenerated\n\n For closureHelperClass.Local_indexParameter = 0 To 3\n\n ' NOTE that it refers to the Lambda *instance* method of the ClosureHelperClass_CompilerGenerated class, \n ' Remember that delegates implicitly carry the instance of the class in their Target \n ' property, it's not just referring to the Lambda method, it's referring to the Lambda\n ' method on the closureHelperClass instance of the class!\n Dim closureHelperClassMethodFunc As Func(Of Integer) = AddressOf closureHelperClass.Lambda\n funcList.Add(closureHelperClassMethodFunc)\n \n Next\n 'closureHelperClass.Local_indexParameter is 4 now.\n\n 'Run each stored lambda expression (on the Delegate's Target, closureHelperClass)\n For Each lambdaFunc As Func(Of Integer) in funcList \n \n 'The return value will always be 4, because it's just returning closureHelperClass.Local_indexParameter.\n Dim retVal_AlwaysFour As Integer = lambdaFunc()\n\n Console.Write($&quot;{retVal_AlwaysFour}&quot;)\n\n Next\n\n End Sub\n\n Friend NotInheritable Class ClosureHelperClass_CompilerGenerated\n ' Yes the compiler really does generate a class with public fields.\n Public Local_indexParameter As Integer\n\n 'The body of your lambda expression goes here, note that this method\n 'takes no parameters and uses a field of this class (the stored parameter value) instead.\n Friend Function Lambda() As Integer\n Return Me.Local_indexParameter\n\n End Function\n\n End Class\n\nEnd Module\n</code></pre>\n<p>Note how there is only one instance of <code>closureHelperClass</code> for the entire body of <code>Sub CompilerGenerated</code>, so there is no way that the function could print the intermediate <code>For</code> loop index values of 0,1,2,3 (there's no place to store these values). The code only prints 4, the final index value (after the <code>For</code> loop) four times.</p>\n<h1>Footnotes:</h1>\n<ul>\n<li>There's an implied &quot;As of .NET 4.6.1&quot; in this post, but in my opinion it's very unlikely that these limitations would change dramatically; if you find a setup where you can't reproduce these results please leave me a comment.</li>\n</ul>\n<p>&quot;But jrh why did you post a late answer?&quot;</p>\n<ul>\n<li>The pages linked in this post are either missing or in shambles.</li>\n<li>There was no vb.net answer on this vb.net tagged question, as of the time of writing there is a C# (wrong language) answer and a mostly link only answer (with 3 dead links).</li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
I was just writing some quick code and noticed this complier error > > Using the iteration variable in a lambda expression may have unexpected results. > > Instead, create a local variable within the loop and assign it the value of the iteration variable. > > > I know what it means and I can easily fix it, not a big deal. But I was wondering why it is a bad idea to use a iteration variable in a lambda? What problems can I cause later on?
Consider this code: ```cs List<Action> actions = new List<Action>(); for (int i = 0; i < 10; i++) { actions.Add(() => Console.WriteLine(i)); } foreach (Action action in actions) { action(); } ``` What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's because there's just one variable which is captured by all the delegates. It's this kind of behaviour which is unexpected. EDIT: I've just seen that you're talking about VB.NET rather than C#. I believe VB.NET has even more complicated rules, due to the way variables maintain their values across iterations. [This post by Jared Parsons](https://devblogs.microsoft.com/vbteam/closures-in-vb-part-5-looping/) gives some information about the kind of difficulties involved - although it's back from 2007, so the actual behaviour may have changed since then.
227,856
<p>It seems that the decision to make your objects fully cognizant of their roles within the system, and still avoid having too many dependencies within the domain model on the database, and service layers?</p> <p>For example: Say that I've got an entity with a revision history, and several "lookup tables" that the data references, your entity object should have methods to get the details from some of the lookup tables, whether by providing access to the lookup table rows, or by delegating methods down to them, but in order to do so it depends on the database layer to read the data from those rows. Also, when the entity is saved, It needs to know not only how to save itself, but also to save entries into the revision history. Is it necessary to pass references to dozens of different data layer objects and service objects to the model object? This seems like it makes the logic far more complex to understand than just passing back and forth thin models to service layer objects, but I've heard many "wise men" recommending this sort of structure.</p>
[ { "answer_id": 227874, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 0, "selected": false, "text": "<p>Try the \"repository pattern\" and \"Domain driven design\". DDD suggests to define certain entities as Aggregate-roots of other objects. Each Aggregate is encapsulated. The entities are \"persistence ignorant\". All the persistence-related code is put in a repository object which manages Data-access for the entity. This way you don't have to mix persistence-related code with your business logic. If you are interested in DDD, check out eric evans book.</p>\n" }, { "answer_id": 227931, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>\"thin models to service layer objects\" is what you do when you really want to write the service layer.</p>\n\n<p>ORM is what you do when you don't want to write the service layer.</p>\n\n<p>When you work with an ORM, you are still aware of the fact that navigation <em>may</em> involve a query, but you don't dwell on it.</p>\n\n<p>Lookup tables can be a relational crutch that gets used when there isn't a very complete object model. Instead of things referencing things, you have codes, which must be looked up. In many cases, the codes devolve to little more than a static pool of strings with database keys. And the relevant methods wind up in odd places in the software.</p>\n\n<p>However, if there is a more complete object model, we have first-class <em>things</em> instead of these degenerate lookup values.</p>\n\n<p>For example, I've got some business transactions which have one of <em>n</em> different \"rate plans\" -- a kind of pricing model. Right now, the legacy relational database has the rate plan as a lookup table with a code, some pricing numbers, and (sometimes) a description.</p>\n\n<p>[Everyone knows the codes -- the codes are sacred. No one is sure what the proper descriptions should be. But they know the codes.]</p>\n\n<p>But really, a \"rate plan\" is an object that is associated with a contract; the rate plan has the method that computes the final price. When an app asks the contract for a price, the contract delegates some of the pricing work to the associated rate plan object. </p>\n\n<p>There may have been some database query going on to lookup the rate plan when producing a contract price, but that's incidental to the delegation of responsibility between the two classes.</p>\n" }, { "answer_id": 228001, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 5, "selected": true, "text": "<p>Really really good question. I have spent quite a bit of time thinking about such topics.</p>\n\n<p>You demonstrate great insight by noting the tension between an expressive domain model and separation of concerns. This is much like the tension in the question I asked about <a href=\"https://stackoverflow.com/questions/169450/arent-information-expert-tell-dont-ask-at-odds-with-single-responsibility-princ\">Tell Don't Ask and Single Responsibility Principle</a>.</p>\n\n<p>Here is my view on the topic.</p>\n\n<p>A domain model is anemic because it contains no domain logic. Other objects get and set data using an anemic domain object. What you describe doesn't sound like domain logic to me. It might be, but generally, look-up tables and other technical language is most likely terms that mean something to us but not necessarily anything to the customers. If this is incorrect, please clarify.</p>\n\n<p>Anyway, the construction and persistence of domain objects shouldn't be contained in the domain objects themselves because that isn't domain logic.</p>\n\n<p>So to answer the question, no, you shouldn't inject a whole bunch of non-domain objects/concepts like lookup tables and other infrastructure details. This is a leak of one concern into another. The Factory and Repository patterns from Domain-Driven Design are best suited to keep these concerns apart from the domain model itself.</p>\n\n<p>But note that if you don't have any domain logic, then you will end up with anemic domain objects, i.e. bags of brainless getters and setters, which is how <a href=\"http://moffdub.wordpress.com/2008/09/03/soa-is-not-an-excuse-to-write-procedural-java/\" rel=\"nofollow noreferrer\">some shops claim to do SOA / service layers</a>. </p>\n\n<p>So how do you get the best of both worlds? How do you focus your domain objects only domain logic, while keeping UI, construction, persistence, etc. out of the way? I recommend you use a technique like <a href=\"http://www.c2.com/cgi/wiki?DoubleDispatchExample\" rel=\"nofollow noreferrer\">Double Dispatch</a>, or some form of <a href=\"http://moffdub.wordpress.com/restricted-method-access/\" rel=\"nofollow noreferrer\">restricted method access</a>.</p>\n\n<p>Here's an example of Double Dispatch. Say you have this line of code:</p>\n\n<pre><code>entity.saveIn(repository);\n</code></pre>\n\n<p>In your question, saveIn() would have all sorts of knowledge about the data layer. Using Double Dispatch, saveIn() does this:</p>\n\n<pre><code>repository.saveEntity(this.foo, this.bar, this.baz);\n</code></pre>\n\n<p>And the saveEntity() method of the repository has all of the knowledge of how to save in the data layer, as it should.</p>\n\n<p>In addition to this setup, you could have:</p>\n\n<pre><code>repository.save(entity);\n</code></pre>\n\n<p>which just calls</p>\n\n<pre><code>entity.saveIn(this);\n</code></pre>\n\n<p>I re-read this and I notice that the entity is still thin because it is simply dispatching its persistence to the repository. But in this case, the entity is supposed to be thin because you didn't describe any other domain logic. In this situation, you could say \"screw Double Dispatch, give me accessors.\" </p>\n\n<p>And yeah, you could, but IMO it exposes too much of how your entity is implemented, and those accessors are distractions from domain logic. I think the only class that should have gets and sets is a class whose name ends in \"Accessor\".</p>\n\n<p>I'll wrap this up soon. Personally, I don't write my entities with saveIn() methods, because I think even just having a saveIn() method tends to litter the domain object with distractions. I use either the friend class pattern, package-private access, or possibly the <a href=\"http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html?page=3\" rel=\"nofollow noreferrer\">Builder pattern</a>.</p>\n\n<p>OK, I'm done. As I said, I've obsessed on this topic quite a bit.</p>\n" }, { "answer_id": 1890255, "author": "Steve", "author_id": 229889, "author_profile": "https://Stackoverflow.com/users/229889", "pm_score": 1, "selected": false, "text": "<p>I aggree with DeadBeef - therein lies the tension. I don't really see though how a domain model is 'anemic' simply because it doesn't save itself.</p>\n\n<p>There has to be much more to it. ie. It's anemic because the service is doing all the business rules and not the domain entity.</p>\n\n<pre><code>Service(IRepository) injected\n\nSave(){\n\nDomainEntity.DoSomething();\nRepository.Save(DomainEntity);\n\n}\n\n'Do Something' is the business logic of the domain entity.\n\n**This would be anemic**:\nService(IRepository) injected\n\nSave(){\n\nif(DomainEntity.IsSomething)\n DomainEntity.SetItProperty();\nRepository.Save(DomainEntity);\n\n}\n</code></pre>\n\n<p>See the inherit difference ? I do :) </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21973/" ]
It seems that the decision to make your objects fully cognizant of their roles within the system, and still avoid having too many dependencies within the domain model on the database, and service layers? For example: Say that I've got an entity with a revision history, and several "lookup tables" that the data references, your entity object should have methods to get the details from some of the lookup tables, whether by providing access to the lookup table rows, or by delegating methods down to them, but in order to do so it depends on the database layer to read the data from those rows. Also, when the entity is saved, It needs to know not only how to save itself, but also to save entries into the revision history. Is it necessary to pass references to dozens of different data layer objects and service objects to the model object? This seems like it makes the logic far more complex to understand than just passing back and forth thin models to service layer objects, but I've heard many "wise men" recommending this sort of structure.
Really really good question. I have spent quite a bit of time thinking about such topics. You demonstrate great insight by noting the tension between an expressive domain model and separation of concerns. This is much like the tension in the question I asked about [Tell Don't Ask and Single Responsibility Principle](https://stackoverflow.com/questions/169450/arent-information-expert-tell-dont-ask-at-odds-with-single-responsibility-princ). Here is my view on the topic. A domain model is anemic because it contains no domain logic. Other objects get and set data using an anemic domain object. What you describe doesn't sound like domain logic to me. It might be, but generally, look-up tables and other technical language is most likely terms that mean something to us but not necessarily anything to the customers. If this is incorrect, please clarify. Anyway, the construction and persistence of domain objects shouldn't be contained in the domain objects themselves because that isn't domain logic. So to answer the question, no, you shouldn't inject a whole bunch of non-domain objects/concepts like lookup tables and other infrastructure details. This is a leak of one concern into another. The Factory and Repository patterns from Domain-Driven Design are best suited to keep these concerns apart from the domain model itself. But note that if you don't have any domain logic, then you will end up with anemic domain objects, i.e. bags of brainless getters and setters, which is how [some shops claim to do SOA / service layers](http://moffdub.wordpress.com/2008/09/03/soa-is-not-an-excuse-to-write-procedural-java/). So how do you get the best of both worlds? How do you focus your domain objects only domain logic, while keeping UI, construction, persistence, etc. out of the way? I recommend you use a technique like [Double Dispatch](http://www.c2.com/cgi/wiki?DoubleDispatchExample), or some form of [restricted method access](http://moffdub.wordpress.com/restricted-method-access/). Here's an example of Double Dispatch. Say you have this line of code: ``` entity.saveIn(repository); ``` In your question, saveIn() would have all sorts of knowledge about the data layer. Using Double Dispatch, saveIn() does this: ``` repository.saveEntity(this.foo, this.bar, this.baz); ``` And the saveEntity() method of the repository has all of the knowledge of how to save in the data layer, as it should. In addition to this setup, you could have: ``` repository.save(entity); ``` which just calls ``` entity.saveIn(this); ``` I re-read this and I notice that the entity is still thin because it is simply dispatching its persistence to the repository. But in this case, the entity is supposed to be thin because you didn't describe any other domain logic. In this situation, you could say "screw Double Dispatch, give me accessors." And yeah, you could, but IMO it exposes too much of how your entity is implemented, and those accessors are distractions from domain logic. I think the only class that should have gets and sets is a class whose name ends in "Accessor". I'll wrap this up soon. Personally, I don't write my entities with saveIn() methods, because I think even just having a saveIn() method tends to litter the domain object with distractions. I use either the friend class pattern, package-private access, or possibly the [Builder pattern](http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html?page=3). OK, I'm done. As I said, I've obsessed on this topic quite a bit.
227,897
<p>I just finished a test as part of a job interview, and one question stumped me, even using Google for reference. I'd like to see what the StackOverflow crew can do with it:</p> <blockquote> <p>The <code>memset_16aligned</code> function requires a 16-byte aligned pointer passed to it, or it will crash.</p> <p>a) How would you allocate 1024 bytes of memory, and align it to a 16 byte boundary?<br /> b) Free the memory after the <code>memset_16aligned</code> has executed.</p> </blockquote> <pre><code>{ void *mem; void *ptr; // answer a) here memset_16aligned(ptr, 0, 1024); // answer b) here } </code></pre>
[ { "answer_id": 227900, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 10, "selected": true, "text": "<h3>Original answer</h3>\n\n<pre><code>{\n void *mem = malloc(1024+16);\n void *ptr = ((char *)mem+16) &amp; ~ 0x0F;\n memset_16aligned(ptr, 0, 1024);\n free(mem);\n}\n</code></pre>\n\n<h3>Fixed answer</h3>\n\n<pre><code>{\n void *mem = malloc(1024+15);\n void *ptr = ((uintptr_t)mem+15) &amp; ~ (uintptr_t)0x0F;\n memset_16aligned(ptr, 0, 1024);\n free(mem);\n}\n</code></pre>\n\n<h3>Explanation as requested</h3>\n\n<p>The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that <code>malloc()</code> is supposed to return a pointer that is sufficiently well aligned for <em>any</em> purpose. However, the meaning of 'any' is primarily for things like basic types — <code>long</code>, <code>double</code>, <code>long double</code>, <code>long long</code>, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)</p>\n\n<p>The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose <code>malloc()</code> returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, <code>~0x0F</code> has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works.</p>\n\n<p>The last step, <code>free()</code>, is easy: you always, and only, return to <code>free()</code> a value that one of <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> returned to you — anything else is a disaster. You correctly provided <code>mem</code> to hold that value — thank you. The free releases it.</p>\n\n<p>Finally, if you know about the internals of your system's <code>malloc</code> package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other <code>malloc</code> packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable.</p>\n\n<p>Someone else mentioned <code>posix_memalign()</code> as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier.</p>\n\n<p>One more comment — this code does not check that the allocation succeeded.</p>\n\n<h3>Amendment</h3>\n\n<p><a href=\"https://stackoverflow.com/users/23705/windows-programmer\">Windows Programmer</a> pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using <code>uintptr_t</code> since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of <code>PRIXPTR</code> in the <code>printf()</code> statements, it would be sufficient to <code>#include &lt;stdint.h&gt;</code> instead of using <code>#include &lt;inttypes.h&gt;</code>. <em>[This code includes the fix pointed out by <a href=\"https://stackoverflow.com/users/832878/c-r\">C.R.</a>, which was reiterating a point first made by <a href=\"https://stackoverflow.com/users/12943/bill-k\">Bill K</a> a number of years ago, which I managed to overlook until now.]</em></p>\n\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic void memset_16aligned(void *space, char byte, size_t nbytes)\n{\n assert((nbytes &amp; 0x0F) == 0);\n assert(((uintptr_t)space &amp; 0x0F) == 0);\n memset(space, byte, nbytes); // Not a custom implementation of memset()\n}\n\nint main(void)\n{\n void *mem = malloc(1024+15);\n void *ptr = (void *)(((uintptr_t)mem+15) &amp; ~ (uintptr_t)0x0F);\n printf(\"0x%08\" PRIXPTR \", 0x%08\" PRIXPTR \"\\n\", (uintptr_t)mem, (uintptr_t)ptr);\n memset_16aligned(ptr, 0, 1024);\n free(mem);\n return(0);\n}\n</code></pre>\n\n<p>And here is a marginally more generalized version, which will work for sizes which are a power of 2:</p>\n\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic void memset_16aligned(void *space, char byte, size_t nbytes)\n{\n assert((nbytes &amp; 0x0F) == 0);\n assert(((uintptr_t)space &amp; 0x0F) == 0);\n memset(space, byte, nbytes); // Not a custom implementation of memset()\n}\n\nstatic void test_mask(size_t align)\n{\n uintptr_t mask = ~(uintptr_t)(align - 1);\n void *mem = malloc(1024+align-1);\n void *ptr = (void *)(((uintptr_t)mem+align-1) &amp; mask);\n assert((align &amp; (align - 1)) == 0);\n printf(\"0x%08\" PRIXPTR \", 0x%08\" PRIXPTR \"\\n\", (uintptr_t)mem, (uintptr_t)ptr);\n memset_16aligned(ptr, 0, 1024);\n free(mem);\n}\n\nint main(void)\n{\n test_mask(16);\n test_mask(32);\n test_mask(64);\n test_mask(128);\n return(0);\n}\n</code></pre>\n\n<p>To convert <code>test_mask()</code> into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.</p>\n\n<h3>Problems with interviewers</h3>\n\n<p><a href=\"https://stackoverflow.com/users/23072/uri\">Uri</a> commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: \"How would you allocate 1024 bytes of memory\" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?</p>\n\n<p>My response won't fit into a 300-character comment...</p>\n\n<p>It depends, I suppose. I think most people (including me) took the question to mean \"How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes\". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.</p>\n\n<ul>\n<li>Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.</li>\n<li>Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned. If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.</li>\n</ul>\n\n<p>However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)</p>\n\n<h3>The world moves on</h3>\n\n<p>The title of the question has changed recently. It was <em>Solve the memory alignment in C interview question that stumped me</em>. The revised title (<em>How to allocate aligned memory only using the standard library?</em>) demands a slightly revised answer — this addendum provides it.</p>\n\n<p>C11 (ISO/IEC 9899:2011) added function <code>aligned_alloc()</code>:</p>\n\n<blockquote>\n <p><strong>7.22.3.1 The <code>aligned_alloc</code> function</strong></p>\n \n <p><strong>Synopsis</strong> </p>\n\n<pre><code>#include &lt;stdlib.h&gt;\nvoid *aligned_alloc(size_t alignment, size_t size);\n</code></pre>\n \n <p><strong>Description</strong><br>\n The <code>aligned_alloc</code> function allocates space for an object whose alignment is\n specified by <code>alignment</code>, whose size is specified by <code>size</code>, and whose value is\n indeterminate. The value of <code>alignment</code> shall be a valid alignment supported by the implementation and the value of <code>size</code> shall be an integral multiple of <code>alignment</code>.</p>\n \n <p><strong>Returns</strong><br>\n The <code>aligned_alloc</code> function returns either a null pointer or a pointer to the allocated space.</p>\n</blockquote>\n\n<p>And POSIX defines <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html\" rel=\"noreferrer\"><code>posix_memalign()</code></a>:</p>\n\n<blockquote>\n<pre><code>#include &lt;stdlib.h&gt;\n\nint posix_memalign(void **memptr, size_t alignment, size_t size);\n</code></pre>\n \n <p>DESCRIPTION</p>\n \n <p>The <code>posix_memalign()</code> function shall allocate <code>size</code> bytes aligned on a boundary specified by <code>alignment</code>, and shall return a pointer to the allocated memory in <code>memptr</code>. The value of <code>alignment</code> shall be a power of two multiple of <code>sizeof(void *)</code>.</p>\n \n <p>Upon successful completion, the value pointed to by <code>memptr</code> shall be a multiple of <code>alignment</code>.</p>\n \n <p>If the size of the space requested is 0, the behavior is implementation-defined; the value returned in <code>memptr</code> shall be either a null pointer or a unique pointer.</p>\n \n <p>The <code>free()</code> function shall deallocate memory that has previously been allocated by <code>posix_memalign()</code>.</p>\n \n <p>RETURN VALUE</p>\n \n <p>Upon successful completion, <code>posix_memalign()</code> shall return zero; otherwise, an error number shall be returned to indicate the error.</p>\n</blockquote>\n\n<p>Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.</p>\n\n<p>Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.</p>\n" }, { "answer_id": 227922, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 5, "selected": false, "text": "<p>You could also try <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html\" rel=\"nofollow noreferrer\"><code>posix_memalign()</code></a> (on POSIX platforms, of course).</p>\n" }, { "answer_id": 227940, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 3, "selected": false, "text": "<p>Perhaps they would have been satisfied with a knowledge of <a href=\"http://www.gnu.org/software/libtool/manual/libc/Aligned-Memory-Blocks.html#Aligned-Memory-Blocks\" rel=\"nofollow noreferrer\">memalign</a>? And as Jonathan Leffler points out, there are two newer preferable functions to know about.</p>\n\n<p>Oops, florin beat me to it. However, if you read the man page I linked to, you'll most likely understand the example supplied by an earlier poster.</p>\n" }, { "answer_id": 228015, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 6, "selected": false, "text": "<p>Three slightly different answers depending how you look at the question:</p>\n\n<p>1) Good enough for the exact question asked is Jonathan Leffler's solution, except that to round up to 16-aligned, you only need 15 extra bytes, not 16.</p>\n\n<p>A:</p>\n\n<pre><code>/* allocate a buffer with room to add 0-15 bytes to ensure 16-alignment */\nvoid *mem = malloc(1024+15);\nASSERT(mem); // some kind of error-handling code\n/* round up to multiple of 16: add 15 and then round down by masking */\nvoid *ptr = ((char*)mem+15) &amp; ~ (size_t)0x0F;\n</code></pre>\n\n<p>B:</p>\n\n<pre><code>free(mem);\n</code></pre>\n\n<p>2) For a more generic memory allocation function, the caller doesn't want to have to keep track of two pointers (one to use and one to free). So you store a pointer to the 'real' buffer below the aligned buffer. </p>\n\n<p>A:</p>\n\n<pre><code>void *mem = malloc(1024+15+sizeof(void*));\nif (!mem) return mem;\nvoid *ptr = ((char*)mem+sizeof(void*)+15) &amp; ~ (size_t)0x0F;\n((void**)ptr)[-1] = mem;\nreturn ptr;\n</code></pre>\n\n<p>B:</p>\n\n<pre><code>if (ptr) free(((void**)ptr)[-1]);\n</code></pre>\n\n<p>Note that unlike (1), where only 15 bytes were added to mem, this code could actually <em>reduce</em> the alignment if your implementation happens to guarantee 32-byte alignment from malloc (unlikely, but in theory a C implementation could have a 32-byte aligned type). That doesn't matter if all you do is call memset_16aligned, but if you use the memory for a struct then it could matter. </p>\n\n<p>I'm not sure off-hand what a good fix is for this (other than to warn the user that the buffer returned is not necessarily suitable for arbitrary structs) since there's no way to determine programatically what the implementation-specific alignment guarantee is. I guess at startup you could allocate two or more 1-byte buffers, and assume that the worst alignment you see is the guaranteed alignment. If you're wrong, you waste memory. Anyone with a better idea, please say so...</p>\n\n<p>[<em>Added</em>:\nThe 'standard' trick is to create a union of 'likely to be maximally aligned types' to determine the requisite alignment. The maximally aligned types are likely to be (in C99) '<code>long long</code>', '<code>long double</code>', '<code>void *</code>', or '<code>void (*)(void)</code>'; if you include <code>&lt;stdint.h&gt;</code>, you could presumably use '<code>intmax_t</code>' in place of <code>long long</code> (and, on Power 6 (AIX) machines, <code>intmax_t</code> would give you a 128-bit integer type). The alignment requirements for that union can be determined by embedding it into a struct with a single char followed by the union:</p>\n\n<pre><code>struct alignment\n{\n char c;\n union\n {\n intmax_t imax;\n long double ldbl;\n void *vptr;\n void (*fptr)(void);\n } u;\n} align_data;\nsize_t align = (char *)&amp;align_data.u.imax - &amp;align_data.c;\n</code></pre>\n\n<p>You would then use the larger of the requested alignment (in the example, 16) and the <code>align</code> value calculated above.</p>\n\n<p>On (64-bit) Solaris 10, it appears that the basic alignment for the result from <code>malloc()</code> is a multiple of 32 bytes.\n<br>\n]</p>\n\n<p>In practice, aligned allocators often take a parameter for the alignment rather than it being hardwired. So the user will pass in the size of the struct they care about (or the least power of 2 greater than or equal to that) and all will be well.</p>\n\n<p>3) Use what your platform provides: <code>posix_memalign</code> for POSIX, <code>_aligned_malloc</code> on Windows.</p>\n\n<p>4) If you use C11, then the cleanest - portable and concise - option is to use the standard library function <a href=\"http://en.cppreference.com/w/c/memory/aligned_alloc\" rel=\"noreferrer\"><code>aligned_alloc</code></a> that was introduced in this version of the language specification.</p>\n" }, { "answer_id": 228079, "author": "An̲̳̳drew", "author_id": 17035, "author_profile": "https://Stackoverflow.com/users/17035", "pm_score": 4, "selected": false, "text": "<p>Here's an alternate approach to the 'round up' part. Not the most brilliantly coded solution but it gets the job done, and this type of syntax is a bit easier to remember (plus would work for alignment values that aren't a power of 2). The <code>uintptr_t</code> cast was necessary to appease the compiler; pointer arithmetic isn't very fond of division or multiplication.</p>\n\n<pre><code>void *mem = malloc(1024 + 15);\nvoid *ptr = (void*) ((uintptr_t) mem + 15) / 16 * 16;\nmemset_16aligned(ptr, 0, 1024);\nfree(mem);\n</code></pre>\n" }, { "answer_id": 1602046, "author": "Adisak", "author_id": 14904, "author_profile": "https://Stackoverflow.com/users/14904", "pm_score": 4, "selected": false, "text": "<p>On the 16 vs 15 byte-count padding front, the actual number you need to add to get an alignment of N is <strong>max(0,N-M)</strong> where M is the natural alignment of the memory allocator (and both are powers of 2).</p>\n\n<p>Since the minimal memory alignment of any allocator is 1 byte, 15=max(0,16-1) is a conservative answer. However, if you know your memory allocator is going to give you 32-bit int aligned addresses (which is fairly common), you could have used 12 as a pad.</p>\n\n<p>This isn't important for this example but it might be important on an embedded system with 12K of RAM where every single int saved counts.</p>\n\n<p>The best way to implement it if you're actually going to try to save every byte possible is as a macro so you can feed it your native memory alignment. Again, this is probably only useful for embedded systems where you need to save every byte.</p>\n\n<p>In the example below, on most systems, the value 1 is just fine for <code>MEMORY_ALLOCATOR_NATIVE_ALIGNMENT</code>, however for our theoretical embedded system with 32-bit aligned allocations, the following could save a tiny bit of precious memory:</p>\n\n<pre><code>#define MEMORY_ALLOCATOR_NATIVE_ALIGNMENT 4\n#define ALIGN_PAD2(N,M) (((N)&gt;(M)) ? ((N)-(M)) : 0)\n#define ALIGN_PAD(N) ALIGN_PAD2((N), MEMORY_ALLOCATOR_NATIVE_ALIGNMENT)\n</code></pre>\n" }, { "answer_id": 3430102, "author": "Shao", "author_id": 413771, "author_profile": "https://Stackoverflow.com/users/413771", "pm_score": 4, "selected": false, "text": "<p>Unfortunately, in C99 it seems pretty tough to guarantee alignment of any sort in a way which would be portable across any C implementation conforming to C99. Why? Because a pointer is not guaranteed to be the \"byte address\" one might imagine with a flat memory model. Neither is the representation of <strong>uintptr_t</strong> so guaranteed, which itself is an optional type anyway.</p>\n\n<p>We might know of some implementations which use a representation for <strong>void *</strong> (and by definition, also <strong>char *</strong>) which is a simple byte address, but by C99 it is opaque to us, the programmers. An implementation might represent a pointer by a set {<em>segment</em>, <em>offset</em>} where <em>offset</em> could have who-knows-what alignment \"in reality.\" Why, a pointer could even be some form of hash table lookup value, or even a linked-list lookup value. It could encode bounds information.</p>\n\n<p>In a recent C1X draft for a C Standard, we see the <strong>_Alignas</strong> keyword. That might help a bit.</p>\n\n<p>The only guarantee C99 gives us is that the memory allocation functions will return a pointer suitable for assignment to a pointer pointing at any object type. Since we cannot specify the alignment of objects, we cannot implement our own allocation functions with responsibility for alignment in a well-defined, portable manner.</p>\n\n<p>It would be good to be wrong about this claim.</p>\n" }, { "answer_id": 3917674, "author": "neuron", "author_id": 394319, "author_profile": "https://Stackoverflow.com/users/394319", "pm_score": 2, "selected": false, "text": "<p>usage of memalign, <a href=\"http://www.gnu.org/s/libc/manual/html_node/Aligned-Memory-Blocks.html\" rel=\"nofollow\">Aligned-Memory-Blocks</a> might be a good solution for the problem.</p>\n" }, { "answer_id": 6696782, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 3, "selected": false, "text": "<p>I'm surprised noone's voted up <a href=\"https://stackoverflow.com/users/413771/shao\">Shao</a>'s <a href=\"https://stackoverflow.com/a/3430102\">answer</a> that, as I understand it, it is impossible to do what's asked in standard C99, since converting a pointer to an integral type formally is undefined behavior. (Apart from the standard allowing conversion of <code>uintptr_t</code> &lt;-> <code>void*</code>, but the standard does not seem to allow doing any manipulations of the <code>uintptr_t</code> value and then converting it back.)</p>\n" }, { "answer_id": 12260015, "author": "Ramana", "author_id": 1645623, "author_profile": "https://Stackoverflow.com/users/1645623", "pm_score": -1, "selected": false, "text": "<pre><code>long add; \nmem = (void*)malloc(1024 +15);\nadd = (long)mem;\nadd = add - (add % 16);//align to 16 byte boundary\nptr = (whatever*)(add);\n</code></pre>\n" }, { "answer_id": 15622073, "author": "resultsway", "author_id": 551514, "author_profile": "https://Stackoverflow.com/users/551514", "pm_score": 0, "selected": false, "text": "<p>You can also add some 16 bytes and then push the original ptr to 16bit aligned by adding the (16-mod) as below the pointer :</p>\n\n<pre><code>main(){\nvoid *mem1 = malloc(1024+16);\nvoid *mem = ((char*)mem1)+1; // force misalign ( my computer always aligns)\nprintf ( \" ptr = %p \\n \", mem );\nvoid *ptr = ((long)mem+16) &amp; ~ 0x0F;\nprintf ( \" aligned ptr = %p \\n \", ptr );\n\nprintf (\" ptr after adding diff mod %p (same as above ) \", (long)mem1 + (16 -((long)mem1%16)) );\n\n\nfree(mem1);\n}\n</code></pre>\n" }, { "answer_id": 20194221, "author": "Chris", "author_id": 2891833, "author_profile": "https://Stackoverflow.com/users/2891833", "pm_score": 1, "selected": false, "text": "<p>MacOS X specific: </p>\n\n<ol>\n<li>All pointers allocated with malloc are 16 bytes aligned. </li>\n<li><p>C11 is supported, so you can just call aligned_malloc (16, size). </p></li>\n<li><p>MacOS X picks code that is optimised for individual processors at boot time for memset, memcpy and memmove and that code uses tricks that you've never heard of to make it fast. 99% chance that memset runs faster than any hand-written memset16 which makes the whole question pointless. </p></li>\n</ol>\n\n<p>If you want a 100% portable solution, before C11 there is none. Because there is no portable way to test alignment of a pointer. If it doesn't have to be 100% portable, you can use</p>\n\n<pre><code>char* p = malloc (size + 15);\np += (- (unsigned int) p) % 16;\n</code></pre>\n\n<p>This assumes that the alignment of a pointer is stored in the lowest bits when converting a pointer to unsigned int. Converting to unsigned int loses information and is implementation defined, but that doesn't matter because we don't convert the result back to a pointer. </p>\n\n<p>The horrible part is of course that the original pointer must be saved somewhere to call free () with it. So all in all I would really doubt the wisdom of this design. </p>\n" }, { "answer_id": 20195009, "author": "Deepthought", "author_id": 996882, "author_profile": "https://Stackoverflow.com/users/996882", "pm_score": 0, "selected": false, "text": "<p>If there are constraints that, you cannot waste a single byte, then this solution works:\nNote: There is a case where this may be executed infinitely :D </p>\n\n<pre><code> void *mem; \n void *ptr;\ntry:\n mem = malloc(1024); \n if (mem % 16 != 0) { \n free(mem); \n goto try;\n } \n ptr = mem; \n memset_16aligned(ptr, 0, 1024);\n</code></pre>\n" }, { "answer_id": 22407273, "author": "user3415603", "author_id": 3415603, "author_profile": "https://Stackoverflow.com/users/3415603", "pm_score": 0, "selected": false, "text": "<p>For the solution i used a concept of padding which aligns the memory and do not waste the \n memory of a single byte .</p>\n\n<p>If there are constraints that, you cannot waste a single byte.\nAll pointers allocated with malloc are 16 bytes aligned.</p>\n\n<p>C11 is supported, so you can just call <code>aligned_alloc (16, size)</code>. </p>\n\n<pre><code>void *mem = malloc(1024+16);\nvoid *ptr = ((char *)mem+16) &amp; ~ 0x0F;\nmemset_16aligned(ptr, 0, 1024);\nfree(mem);\n</code></pre>\n" }, { "answer_id": 24052152, "author": "Ian Ollmann", "author_id": 3166255, "author_profile": "https://Stackoverflow.com/users/3166255", "pm_score": 3, "selected": false, "text": "<p>We do this sort of thing all the time for Accelerate.framework, a heavily vectorized OS X / iOS library, where we have to pay attention to alignment all the time. There are quite a few options, one or two of which I didn't see mentioned above.</p>\n\n<p>The fastest method for a small array like this is just stick it on the stack. With GCC / clang:</p>\n\n<pre><code> void my_func( void )\n {\n uint8_t array[1024] __attribute__ ((aligned(16)));\n ...\n }\n</code></pre>\n\n<p>No free() required. This is typically two instructions: subtract 1024 from the stack pointer, then AND the stack pointer with -alignment. Presumably the requester needed the data on the heap because its lifespan of the array exceeded the stack or recursion is at work or stack space is at a serious premium.</p>\n\n<p>On OS X / iOS all calls to malloc/calloc/etc. are always 16 byte aligned. If you needed 32 byte aligned for AVX, for example, then you can use posix_memalign:</p>\n\n<pre><code>void *buf = NULL;\nint err = posix_memalign( &amp;buf, 32 /*alignment*/, 1024 /*size*/);\nif( err )\n RunInCirclesWaivingArmsWildly();\n...\nfree(buf);\n</code></pre>\n\n<p>Some folks have mentioned the C++ interface that works similarly. </p>\n\n<p>It should not be forgotten that pages are aligned to large powers of two, so page-aligned buffers are also 16 byte aligned. Thus, mmap() and valloc() and other similar interfaces are also options. mmap() has the advantage that the buffer can be allocated preinitialized with something non-zero in it, if you want. Since these have page aligned size, you will not get the minimum allocation from these, and it will likely be subject to a VM fault the first time you touch it. </p>\n\n<p>Cheesy: Turn on guard malloc or similar. Buffers that are n*16 bytes in size such as this one will be n*16 bytes aligned, because VM is used to catch overruns and its boundaries are at page boundaries.</p>\n\n<p>Some Accelerate.framework functions take in a user supplied temp buffer to use as scratch space. Here we have to assume that the buffer passed to us is wildly misaligned and the user is actively trying to make our life hard out of spite. (Our test cases stick a guard page right before and after the temp buffer to underline the spite.) Here, we return the minimum size we need to guarantee a 16-byte aligned segment somewhere in it, and then manually align the buffer afterward. This size is desired_size + alignment - 1. So, In this case that is 1024 + 16 - 1 = 1039 bytes. Then align as so:</p>\n\n<pre><code>#include &lt;stdint.h&gt;\nvoid My_func( uint8_t *tempBuf, ... )\n{\n uint8_t *alignedBuf = (uint8_t*) \n (((uintptr_t) tempBuf + ((uintptr_t)alignment-1)) \n &amp; -((uintptr_t) alignment));\n ...\n}\n</code></pre>\n\n<p><em>Adding alignment-1 will move the pointer past the first aligned address and then ANDing with -alignment (e.g. 0xfff...ff0 for alignment=16) brings it back to the aligned address.</em> </p>\n\n<p>As described by other posts, on other operating systems without 16-byte alignment guarantees, you can call malloc with the larger size, set aside the pointer for free() later, then align as described immediately above and use the aligned pointer, much as described for our temp buffer case. </p>\n\n<p>As for aligned_memset, this is rather silly. You only have to loop in up to 15 bytes to reach an aligned address, and then proceed with aligned stores after that with some possible cleanup code at the end. You can even do the cleanup bits in vector code, either as unaligned stores that overlap the aligned region (providing the length is at least the length of a vector) or using something like movmaskdqu. Someone is just being lazy. However, it is probably a reasonable interview question if the interviewer wants to know whether you are comfortable with stdint.h, bitwise operators and memory fundamentals, so the contrived example can be forgiven. </p>\n" }, { "answer_id": 37149280, "author": "J-a-n-u-s", "author_id": 5437832, "author_profile": "https://Stackoverflow.com/users/5437832", "pm_score": 2, "selected": false, "text": "<p>The first thing that popped into my head when reading this question was to define an aligned struct, instantiate it, and then point to it.</p>\n\n<p>Is there a fundamental reason I'm missing since no one else suggested this?</p>\n\n<p>As a sidenote, since I used an array of char (assuming the system's char is 8 bits (i.e. 1 byte)), I don't see the need for the <code>__attribute__((packed))</code> necessarily (correct me if I'm wrong), but I put it in anyway.</p>\n\n<p>This works on two systems I tried it on, but it's possible that there is a compiler optimization that I'm unaware of giving me false positives vis-a-vis the efficacy of the code. I used <code>gcc 4.9.2</code> on OSX and <code>gcc 5.2.1</code> on Ubuntu.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main ()\n{\n\n void *mem;\n\n void *ptr;\n\n // answer a) here\n struct __attribute__((packed)) s_CozyMem {\n char acSpace[16];\n };\n\n mem = malloc(sizeof(struct s_CozyMem));\n ptr = mem;\n\n // memset_16aligned(ptr, 0, 1024);\n\n // Check if it's aligned\n if(((unsigned long)ptr &amp; 15) == 0) printf(\"Aligned to 16 bytes.\\n\");\n else printf(\"Rubbish.\\n\");\n\n // answer b) here\n free(mem);\n\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 58736672, "author": "stackguy", "author_id": 3624305, "author_profile": "https://Stackoverflow.com/users/3624305", "pm_score": -1, "selected": false, "text": "<pre><code>size =1024;\nalignment = 16;\naligned_size = size +(alignment -(size % alignment));\nmem = malloc(aligned_size);\nmemset_16aligned(mem, 0, 1024);\nfree(mem);\n</code></pre>\n\n<p>Hope this one is the simplest implementation, let me know your comments.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63/" ]
I just finished a test as part of a job interview, and one question stumped me, even using Google for reference. I'd like to see what the StackOverflow crew can do with it: > > The `memset_16aligned` function requires a 16-byte aligned pointer passed to it, or it will crash. > > > a) How would you allocate 1024 bytes of memory, and align it to a 16 byte boundary? > > b) Free the memory after the `memset_16aligned` has executed. > > > ``` { void *mem; void *ptr; // answer a) here memset_16aligned(ptr, 0, 1024); // answer b) here } ```
### Original answer ``` { void *mem = malloc(1024+16); void *ptr = ((char *)mem+16) & ~ 0x0F; memset_16aligned(ptr, 0, 1024); free(mem); } ``` ### Fixed answer ``` { void *mem = malloc(1024+15); void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F; memset_16aligned(ptr, 0, 1024); free(mem); } ``` ### Explanation as requested The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that `malloc()` is supposed to return a pointer that is sufficiently well aligned for *any* purpose. However, the meaning of 'any' is primarily for things like basic types — `long`, `double`, `long double`, `long long`, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.) The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose `malloc()` returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, `~0x0F` has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works. The last step, `free()`, is easy: you always, and only, return to `free()` a value that one of `malloc()`, `calloc()` or `realloc()` returned to you — anything else is a disaster. You correctly provided `mem` to hold that value — thank you. The free releases it. Finally, if you know about the internals of your system's `malloc` package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other `malloc` packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable. Someone else mentioned `posix_memalign()` as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier. One more comment — this code does not check that the allocation succeeded. ### Amendment [Windows Programmer](https://stackoverflow.com/users/23705/windows-programmer) pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using `uintptr_t` since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of `PRIXPTR` in the `printf()` statements, it would be sufficient to `#include <stdint.h>` instead of using `#include <inttypes.h>`. *[This code includes the fix pointed out by [C.R.](https://stackoverflow.com/users/832878/c-r), which was reiterating a point first made by [Bill K](https://stackoverflow.com/users/12943/bill-k) a number of years ago, which I managed to overlook until now.]* ``` #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static void memset_16aligned(void *space, char byte, size_t nbytes) { assert((nbytes & 0x0F) == 0); assert(((uintptr_t)space & 0x0F) == 0); memset(space, byte, nbytes); // Not a custom implementation of memset() } int main(void) { void *mem = malloc(1024+15); void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F); printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr); memset_16aligned(ptr, 0, 1024); free(mem); return(0); } ``` And here is a marginally more generalized version, which will work for sizes which are a power of 2: ``` #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static void memset_16aligned(void *space, char byte, size_t nbytes) { assert((nbytes & 0x0F) == 0); assert(((uintptr_t)space & 0x0F) == 0); memset(space, byte, nbytes); // Not a custom implementation of memset() } static void test_mask(size_t align) { uintptr_t mask = ~(uintptr_t)(align - 1); void *mem = malloc(1024+align-1); void *ptr = (void *)(((uintptr_t)mem+align-1) & mask); assert((align & (align - 1)) == 0); printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr); memset_16aligned(ptr, 0, 1024); free(mem); } int main(void) { test_mask(16); test_mask(32); test_mask(64); test_mask(128); return(0); } ``` To convert `test_mask()` into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers. ### Problems with interviewers [Uri](https://stackoverflow.com/users/23072/uri) commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer? My response won't fit into a 300-character comment... It depends, I suppose. I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited. * Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful. * Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned. If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator. However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.) ### The world moves on The title of the question has changed recently. It was *Solve the memory alignment in C interview question that stumped me*. The revised title (*How to allocate aligned memory only using the standard library?*) demands a slightly revised answer — this addendum provides it. C11 (ISO/IEC 9899:2011) added function `aligned_alloc()`: > > **7.22.3.1 The `aligned_alloc` function** > > > **Synopsis** > > > > ``` > #include <stdlib.h> > void *aligned_alloc(size_t alignment, size_t size); > > ``` > > **Description** > > The `aligned_alloc` function allocates space for an object whose alignment is > specified by `alignment`, whose size is specified by `size`, and whose value is > indeterminate. The value of `alignment` shall be a valid alignment supported by the implementation and the value of `size` shall be an integral multiple of `alignment`. > > > **Returns** > > The `aligned_alloc` function returns either a null pointer or a pointer to the allocated space. > > > And POSIX defines [`posix_memalign()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html): > > > ``` > #include <stdlib.h> > > int posix_memalign(void **memptr, size_t alignment, size_t size); > > ``` > > DESCRIPTION > > > The `posix_memalign()` function shall allocate `size` bytes aligned on a boundary specified by `alignment`, and shall return a pointer to the allocated memory in `memptr`. The value of `alignment` shall be a power of two multiple of `sizeof(void *)`. > > > Upon successful completion, the value pointed to by `memptr` shall be a multiple of `alignment`. > > > If the size of the space requested is 0, the behavior is implementation-defined; the value returned in `memptr` shall be either a null pointer or a unique pointer. > > > The `free()` function shall deallocate memory that has previously been allocated by `posix_memalign()`. > > > RETURN VALUE > > > Upon successful completion, `posix_memalign()` shall return zero; otherwise, an error number shall be returned to indicate the error. > > > Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered. Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.
227,907
<p>I am trying to debug an ActiveResource call that is not working.</p> <p>What's the best way to view the HTTP response to the request ActiveResource is making?</p>
[ { "answer_id": 227908, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 0, "selected": false, "text": "<p>Maybe the best way is to use a traffic sniffer.</p>\n\n<p>(Which would totally work...except in my case the traffic I want to see is encrypted. D'oh!)</p>\n" }, { "answer_id": 228292, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 0, "selected": false, "text": "<p>Or my method of getting into things when I don't know the exact internals is literally just to throw in a \"debugger\" statement, start up the server using \"script/server --debugger\" and then step through the code until I'm at the place I want, then start some inspecting right there in IRB.....that might help (hey Luke btw)</p>\n" }, { "answer_id": 228393, "author": "Matthew Smith", "author_id": 20889, "author_profile": "https://Stackoverflow.com/users/20889", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a> because you can start it listening on the web browser client end (usually your development machine) and then do a page request. Then you can find the HTTP packets, right click and \"Follow Conversation\" to see the HTTP with headers going back and forth.</p>\n" }, { "answer_id": 236378, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 3, "selected": true, "text": "<p>It's easy. Just look at the response that comes back. :)</p>\n\n<p>Two options:</p>\n\n<ul>\n<li>You have the source file on your computer. Edit it. Put a <code>puts response.inspect</code> at the appropriate place. Remember to remove it.</li>\n<li>Ruby has open classes. Find the right method and redefine it to do exactly what you want, or use aliases and call chaining to do this. There's probably a method that returns the response -- grab it, print it, and then return it.</li>\n</ul>\n\n<p>Here's a silly example of the latter option.</p>\n\n<pre><code># Somewhere buried in ActiveResource:\nclass Network\n def get\n return get_request\n end\n\n def get_request\n \"I'm a request!\"\n end\nend\n\n# Somewhere in your source files:\nclass Network\n def print_request\n request = old_get_request\n puts request\n request\n end\n alias :old_get_request :get_request\n alias :get_request :print_request\nend\n</code></pre>\n\n<p>Imagine the first class definition is in the ActiveRecord source files. The second class definition is in your application somewhere.</p>\n\n<pre><code>$ irb -r openclasses.rb \n&gt;&gt; Network.new.get\nI'm a request!\n=&gt; \"I'm a request!\"\n</code></pre>\n\n<p>You can see that it prints it and then returns it. Neat, huh?</p>\n\n<p>(And although my simple example doesn't use it since it isn't using Rails, check out <code>alias_method_chain</code> to combine your alias calls.)</p>\n" }, { "answer_id": 237776, "author": "derfred", "author_id": 10286, "author_profile": "https://Stackoverflow.com/users/10286", "pm_score": 1, "selected": false, "text": "<p>This only works if you also control the server:</p>\n\n<p>Follow the server log and fish out the URL that was called:</p>\n\n<pre><code>Completed in 0.26889 (3 reqs/sec) | Rendering: 0.00036 (0%) | DB: 0.02424 (9%) | 200 OK [http://localhost/notifications/summary.xml?person_id=25738]\n</code></pre>\n\n<p>and then open that in Firefox. If the server is truely RESTful (ie. stateless) you will get the same response as ARes did.</p>\n" }, { "answer_id": 477966, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>the firefox plugin live http headers (<a href=\"http://livehttpheaders.mozdev.org/\" rel=\"nofollow noreferrer\">http://livehttpheaders.mozdev.org/</a>) is great for this. Or you can use a website tool like <a href=\"http://www.httpviewer.net/\" rel=\"nofollow noreferrer\">http://www.httpviewer.net/</a></p>\n" }, { "answer_id": 7175431, "author": "Kai Wren", "author_id": 274533, "author_profile": "https://Stackoverflow.com/users/274533", "pm_score": 4, "selected": false, "text": "<p>Monkey patch the connection to enable Net::HTTP debug mode. See <a href=\"https://gist.github.com/591601\" rel=\"noreferrer\">https://gist.github.com/591601</a> - I wrote it to solve precisely this problem. Adding this gist to your rails app will give you <code>Net::HTTP.enable_debug!</code> and <code>Net::HTTP.disable_debug!</code> that you can use to print debug info.</p>\n\n<p>Net::HTTP debug mode is insecure and shouldn't be used in production, but is extremely informative for debugging.</p>\n" }, { "answer_id": 8040859, "author": "reto", "author_id": 102200, "author_profile": "https://Stackoverflow.com/users/102200", "pm_score": 2, "selected": false, "text": "<p>Add a new file to <code>config/initializers/</code> called <code>'debug_connection.rb'</code> with the following content:</p>\n\n<pre><code>class ActiveResource::Connection\n # Creates new Net::HTTP instance for communication with\n # remote service and resources.\n def http\n http = Net::HTTP.new(@site.host, @site.port)\n http.use_ssl = @site.is_a?(URI::HTTPS)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl\n http.read_timeout = @timeout if @timeout\n # Here's the addition that allows you to see the output\n http.set_debug_output $stderr\n return http\n end\nend\n</code></pre>\n\n<p>This will print the whole network traffic to $stderr.</p>\n" }, { "answer_id": 26056094, "author": "mistertim", "author_id": 413744, "author_profile": "https://Stackoverflow.com/users/413744", "pm_score": 0, "selected": false, "text": "<p>I'd use <a href=\"http://www.circlemud.org/jelson/software/tcpflow/\" rel=\"nofollow\">TCPFlow</a> here to watch the traffic going over the wire, rather than patching my app to output it.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ]
I am trying to debug an ActiveResource call that is not working. What's the best way to view the HTTP response to the request ActiveResource is making?
It's easy. Just look at the response that comes back. :) Two options: * You have the source file on your computer. Edit it. Put a `puts response.inspect` at the appropriate place. Remember to remove it. * Ruby has open classes. Find the right method and redefine it to do exactly what you want, or use aliases and call chaining to do this. There's probably a method that returns the response -- grab it, print it, and then return it. Here's a silly example of the latter option. ``` # Somewhere buried in ActiveResource: class Network def get return get_request end def get_request "I'm a request!" end end # Somewhere in your source files: class Network def print_request request = old_get_request puts request request end alias :old_get_request :get_request alias :get_request :print_request end ``` Imagine the first class definition is in the ActiveRecord source files. The second class definition is in your application somewhere. ``` $ irb -r openclasses.rb >> Network.new.get I'm a request! => "I'm a request!" ``` You can see that it prints it and then returns it. Neat, huh? (And although my simple example doesn't use it since it isn't using Rails, check out `alias_method_chain` to combine your alias calls.)
227,909
<p>I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?</p> <p>I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.</p> <p>If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!</p>
[ { "answer_id": 227966, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 5, "selected": false, "text": "<p>Break into the debugger and then type this into the Immediate window:</p>\n\n<pre><code>.load C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\sos.dll\n</code></pre>\n\n<p>The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.</p>\n\n<p>Then type this:</p>\n\n<pre><code>System.GC.Collect()\n</code></pre>\n\n<p>That will ensure anything not reachable is collected. Then type this:</p>\n\n<pre><code>!DumpHeap -type &lt;some-type-name&gt;\n</code></pre>\n\n<p>This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:</p>\n\n<pre><code>!gcroot &lt;some-address&gt;\n</code></pre>\n" }, { "answer_id": 228592, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 3, "selected": false, "text": "<p>.NET Memory Profiler is an excellent tool, and one that I use frequently to diagnose memory leaks in WPF applications.</p>\n\n<p>As I'm sure you're aware, a good way to use it is to take a snapshot before using a particular feature, then take a second snapshot after using it, closing the window, etc. When comparing the two snapshots, you can see how many objects of a certain type are being allocated but not freed: this is a leak.</p>\n\n<p>After double-clicking on a type, the profiler will show you the shortest root paths keeping objects of that type alive. There are many different ways that .NET objects can leak in WPF, so posting the root path that you are seeing should help identify the ultimate cause. In general, however, try to understand why those objects are holding onto your object, and see if there's some way you can detach your event handlers, bindings, etc. when the window is closed.</p>\n\n<p>I recently posted a <a href=\"http://code.logos.com/blog/2008/10/detecting_bindings_that_should_be_onetime.html\" rel=\"noreferrer\">blog entry</a> about a particular <a href=\"http://support.microsoft.com/kb/938416\" rel=\"noreferrer\">memory leak</a> that can be caused by certain bindings; for that specific types of leak, the code there is useful for finding the Binding that's at fault. </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them? I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it. If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!
Break into the debugger and then type this into the Immediate window: ``` .load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll ``` The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll. Then type this: ``` System.GC.Collect() ``` That will ensure anything not reachable is collected. Then type this: ``` !DumpHeap -type <some-type-name> ``` This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this: ``` !gcroot <some-address> ```
227,924
<p>I can't see the 'Collection of Repositories" page after adding authentication and access rules to svn. 'guest' can navigate to mydomain.com/svn/public and admin can see both svn/public and svn/private, but none of the users can see /svn. </p> <p>Is it possible to have 'guest' access mydomain.com/svn and only see a /public link?</p> <p>Here's what I have setup...</p> <p><strong>subversion.conf:</strong></p> <pre><code>&lt;location /svn&gt; DAV svn SVNParentPath /home/subversion SVNListParentPath on AuthzSVNAccessFile /etc/svn-access-file AuthType Basic AuthName "Subversion Repository" AuthUserFile /etc/svn-auth-file Require valid-user &lt;/Location&gt; </code></pre> <p><strong>svn-access-file:</strong></p> <pre><code>[public:/] guest = r @admin = rw [private:/] @admin = rw [groups] admin = karl.r </code></pre> <p>Thanks.</p>
[ { "answer_id": 228955, "author": "Karl R", "author_id": 22934, "author_profile": "https://Stackoverflow.com/users/22934", "pm_score": 0, "selected": false, "text": "<p>Using &lt; location /svn/ > fixed it, all repos are now visible from /svn/ and if a guest clicks on 'private' it locks them out.</p>\n\n<p>But, it only works with that trailing slash in the url. mydomain.com/svn/ works but mydomain.com/svn does not.</p>\n" }, { "answer_id": 229104, "author": "remmelt", "author_id": 30709, "author_profile": "https://Stackoverflow.com/users/30709", "pm_score": 2, "selected": true, "text": "<p>This may not be what you're looking for, but we've stopped using the collection of repositories page altogether. Instead we use websvn: <a href=\"http://websvn.tigris.org/\" rel=\"nofollow noreferrer\">http://websvn.tigris.org/</a> screenshot: <a href=\"http://chrison.net/content/binary/websvn2.png\" rel=\"nofollow noreferrer\">http://chrison.net/content/binary/websvn2.png</a> (not my screenshot) with the Calm theme.</p>\n\n<p>Access is granted through Apache's DAV module, using this in the default site config (sites-enabled/default):</p>\n\n<pre><code>&lt;Location /websvn&gt;\n AuthType Basic\n AuthName \"Company WebSVN\"\n AuthUserFile /home/svn/dav_svn.passwd\n Require group developers\n AuthGroupFile /home/svn/dav_svn_groups\n&lt;/Location&gt;\n</code></pre>\n\n<p>You may not need the group line, substitute with valid-user where needed.</p>\n\n<p>P.S. I just noticed that our /svn/ directory is the same as yours, won't work without the trailing /. Websvn does work though, with or without trailing slash!\nFor now, I've redirected /svn to /svn/ in our httpd.conf, which relieves the problem. I've used the following redirect statement:</p>\n\n<pre><code>RedirectMatch ^(/svn)$ $1/\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22934/" ]
I can't see the 'Collection of Repositories" page after adding authentication and access rules to svn. 'guest' can navigate to mydomain.com/svn/public and admin can see both svn/public and svn/private, but none of the users can see /svn. Is it possible to have 'guest' access mydomain.com/svn and only see a /public link? Here's what I have setup... **subversion.conf:** ``` <location /svn> DAV svn SVNParentPath /home/subversion SVNListParentPath on AuthzSVNAccessFile /etc/svn-access-file AuthType Basic AuthName "Subversion Repository" AuthUserFile /etc/svn-auth-file Require valid-user </Location> ``` **svn-access-file:** ``` [public:/] guest = r @admin = rw [private:/] @admin = rw [groups] admin = karl.r ``` Thanks.
This may not be what you're looking for, but we've stopped using the collection of repositories page altogether. Instead we use websvn: <http://websvn.tigris.org/> screenshot: <http://chrison.net/content/binary/websvn2.png> (not my screenshot) with the Calm theme. Access is granted through Apache's DAV module, using this in the default site config (sites-enabled/default): ``` <Location /websvn> AuthType Basic AuthName "Company WebSVN" AuthUserFile /home/svn/dav_svn.passwd Require group developers AuthGroupFile /home/svn/dav_svn_groups </Location> ``` You may not need the group line, substitute with valid-user where needed. P.S. I just noticed that our /svn/ directory is the same as yours, won't work without the trailing /. Websvn does work though, with or without trailing slash! For now, I've redirected /svn to /svn/ in our httpd.conf, which relieves the problem. I've used the following redirect statement: ``` RedirectMatch ^(/svn)$ $1/ ```
227,928
<p>I'm building an open source project that uses python and c++ in Windows. I came to the following error message:</p> <pre><code> ImportError: No module named win32con </code></pre> <p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p> <p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p> <p>I have Python2.6, should I have that module already installed? Is that something of VC++?</p> <p>Thank you for the help.</p> <p>I got this url <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
[ { "answer_id": 227930, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 6, "selected": true, "text": "<p>This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.</p>\n\n<p><strong>Edit:</strong> I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.</p>\n" }, { "answer_id": 228679, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>Note that the <a href=\"http://sourceforge.net/project/platformdownload.php?group_id=78018\" rel=\"nofollow noreferrer\">Pywin32 download</a> page contains installers for version 2.6 (i386 and AMD64). The <a href=\"http://www.activestate.com/Products/activepython/feature_list.mhtml\" rel=\"nofollow noreferrer\">ActiveState</a> distribution is a <em>single installer that includes pywin32</em> - currently at version 2.5.2.</p>\n" }, { "answer_id": 10886718, "author": "Eric", "author_id": 6367, "author_profile": "https://Stackoverflow.com/users/6367", "pm_score": 3, "selected": false, "text": "<p>Ok I stumbled here twice for installs on two machines so here is a quick link for that ressource</p>\n\n<p><a href=\"http://sourceforge.net/projects/pywin32/files/pywin32/\">http://sourceforge.net/projects/pywin32/files/pywin32/</a></p>\n\n<p>This is the actual download page of the project and now a readme download</p>\n" }, { "answer_id": 27031096, "author": "Jerome Anthony", "author_id": 1006422, "author_profile": "https://Stackoverflow.com/users/1006422", "pm_score": 1, "selected": false, "text": "<p>The PyWin32 download references including project references are found in the <a href=\"https://pypi.python.org/pypi/pywin32\" rel=\"nofollow\">pypi</a> registry.</p>\n" }, { "answer_id": 39329641, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 6, "selected": false, "text": "<pre><code>pip install pypiwin32\n</code></pre>\n\n<p><a href=\"https://glyph.twistedmatrix.com\" rel=\"noreferrer\">Glyph</a> had packed packed it until somebody sends patch to build wheels as part of <code>pywin32</code> build process to close <a href=\"https://sourceforge.net/p/pywin32/bugs/680/\" rel=\"noreferrer\">https://sourceforge.net/p/pywin32/bugs/680/</a></p>\n" }, { "answer_id": 55544345, "author": "Emil Donkov", "author_id": 11319461, "author_profile": "https://Stackoverflow.com/users/11319461", "pm_score": -1, "selected": false, "text": "<p>navigate to: C:\\Python27\\Lib\\site-packages\\win32\\lib and copy the win32con.py file into your project directory.</p>\n" }, { "answer_id": 61448846, "author": "Thomas Ducrot", "author_id": 8047453, "author_profile": "https://Stackoverflow.com/users/8047453", "pm_score": 3, "selected": false, "text": "<p>If you have pywin32 installed you can do in python 3.7+</p>\n\n<pre><code>import win32.lib.win32con as win32con\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
I'm building an open source project that uses python and c++ in Windows. I came to the following error message: ``` ImportError: No module named win32con ``` The same happened in a "prebuilt" code that it's working ( except in my computer :P ) I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me. I have Python2.6, should I have that module already installed? Is that something of VC++? Thank you for the help. I got this url <http://sourceforge.net/projects/pywin32/> but I'm not sure what to do with the executable :S
This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project. **Edit:** I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.
227,935
<p>In response to a rightMouse event I want to call a function that displays a context menu, runs it, and responds to the selected menu item. In Windows I can use TrackPopupMenu with the TPM_RETURNCMD flag.</p> <p>What is the easiest way to implement this in Cocoa? It seems NSMenu:popUpContextMenu wants to post an event to the specified NSView. Must I create a dummy view and wait for the event before returning? If so, how do I "wait" or flush events given I am not returning to my main ?</p>
[ { "answer_id": 227975, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>The 'proper' way to do this in Cocoa is to have your menu item's target and action perform the required method. However, if you must do it within your initial call, you can use <code>[NSView nextEventMatchingMask:]</code> to continually fetch new events that interest you, handle them, and loop. Here's an example which just waits until the right mouse button is released. You'll probably want to use a more complex mask argument, and continually call <code>[NSView nextEventMatchingMask:]</code> until you get what you want.</p>\n\n<p><code><pre>\nNSEvent *localEvent = [[self window] nextEventMatchingMask: NSRightMouseUpMask];\n</pre></code></p>\n\n<p>I think you'll find the 'proper' way to go much easier.</p>\n" }, { "answer_id": 228492, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "<p>There is no direct equivalent, except in Carbon, which is deprecated.</p>\n\n<p>For detecting the right-click, follow <a href=\"http://boredzo.org/blog/archives/2007-01-07/how-to-detect-a-click\" rel=\"nofollow noreferrer\">these instructions</a>. They ensure that you will properly detect right-clicks and right-holds and display the menu when you should and not display it when you shouldn't.</p>\n\n<p>For following events, you might try <code>[[NSRunLoop currentRunLoop] runMode:NSEventTrackingRunLoopMode untilDate:[NSDate distantFuture]]</code>. You will need to call this repeatedly until the user has chosen one of the menu items.</p>\n\n<p>Using <code>nextEventMatchingMask:NSRightMouseUpMask</code> will not work in all, or even most, cases. If the user right-<em>clicks</em> on your control, the right mouse button will go up immediately after it goes down, without selecting a menu item, and the menu item selection will probably (though not necessarily) happen through the left mouse button. Better to just run the run loop repeatedly until the user either selects something or dismisses the menu.</p>\n\n<p>I don't know how to tell that the user has dismissed the menu without selecting anything.</p>\n" }, { "answer_id": 230808, "author": "AlanKley", "author_id": 8761, "author_profile": "https://Stackoverflow.com/users/8761", "pm_score": 2, "selected": true, "text": "<p>It appears that popUpContextMenu is already synchronous. Since I didn't see a way to use NSMenu without having it send a notification to an NSView I came up with a scheme that instantiates a temporary NSView. The goal is to display a popup menu and return the selected item in the context of a single function call. Following is code snippets of my proposed solution:</p>\n\n<pre><code>// Dummy View class used to receive Menu Events\n\n@interface DVFBaseView : NSView\n{\n NSMenuItem* nsMenuItem;\n}\n- (void) OnMenuSelection:(id)sender;\n- (NSMenuItem*)MenuItem;\n@end\n\n@implementation DVFBaseView\n- (NSMenuItem*)MenuItem\n{\n return nsMenuItem;\n}\n\n- (void)OnMenuSelection:(id)sender\n{\n nsMenuItem = sender;\n}\n\n@end\n\n// Calling Code (in response to rightMouseDown event in my main NSView\n\nvoid HandleRButtonDown (NSPoint pt)\n{\n NSRect graphicsRect; // contains an origin, width, height\n graphicsRect = NSMakeRect(200, 200, 50, 100);\n\n //-----------------------------\n // Create Menu and Dummy View\n //-----------------------------\n\n nsMenu = [[[NSMenu alloc] initWithTitle:@\"Contextual Menu\"] autorelease];\n nsView = [[[DVFBaseView alloc] initWithFrame:graphicsRect] autorelease];\n\n NSMenuItem* item = [nsMenu addItemWithTitle:@\"Menu Item# 1\" action:@selector(OnMenuSelection:) keyEquivalent:@\"\"];\n\n [item setTag:ID_FIRST];\n\n item = [nsMenu addItemWithTitle:@\"Menu Item #2\" action:@selector(OnMenuSelection:) keyEquivalent:@\"\"];\n\n [item setTag:ID_SECOND];\n //---------------------------------------------------------------------------------------------\n// Providing a valid windowNumber is key in getting the Menu to display in the proper location\n//---------------------------------------------------------------------------------------------\n\n int windowNumber = [(NSWindow*)myWindow windowNumber];\n NSRect frame = [(NSWindow*)myWindow frame];\n NSPoint wp = {pt.x, frame.size.height - pt.y}; // Origin in lower left\n\n NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined\n location:wp\n modifierFlags:NSApplicationDefined \n timestamp: (NSTimeInterval) 0\n windowNumber: windowNumber\n context: [NSGraphicsContext currentContext]\n subtype:0\n data1: 0\n data2: 0]; \n\n [NSMenu popUpContextMenu:nsMenu withEvent:event forView:nsView]; \n NSMenuItem* MenuItem = [nsView MenuItem];\n\n switch ([MenuItem tag])\n {\n case ID_FIRST: HandleFirstCommand(); break;\n case ID_SECOND: HandleSecondCommand(); break;\n }\n }\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
In response to a rightMouse event I want to call a function that displays a context menu, runs it, and responds to the selected menu item. In Windows I can use TrackPopupMenu with the TPM\_RETURNCMD flag. What is the easiest way to implement this in Cocoa? It seems NSMenu:popUpContextMenu wants to post an event to the specified NSView. Must I create a dummy view and wait for the event before returning? If so, how do I "wait" or flush events given I am not returning to my main ?
It appears that popUpContextMenu is already synchronous. Since I didn't see a way to use NSMenu without having it send a notification to an NSView I came up with a scheme that instantiates a temporary NSView. The goal is to display a popup menu and return the selected item in the context of a single function call. Following is code snippets of my proposed solution: ``` // Dummy View class used to receive Menu Events @interface DVFBaseView : NSView { NSMenuItem* nsMenuItem; } - (void) OnMenuSelection:(id)sender; - (NSMenuItem*)MenuItem; @end @implementation DVFBaseView - (NSMenuItem*)MenuItem { return nsMenuItem; } - (void)OnMenuSelection:(id)sender { nsMenuItem = sender; } @end // Calling Code (in response to rightMouseDown event in my main NSView void HandleRButtonDown (NSPoint pt) { NSRect graphicsRect; // contains an origin, width, height graphicsRect = NSMakeRect(200, 200, 50, 100); //----------------------------- // Create Menu and Dummy View //----------------------------- nsMenu = [[[NSMenu alloc] initWithTitle:@"Contextual Menu"] autorelease]; nsView = [[[DVFBaseView alloc] initWithFrame:graphicsRect] autorelease]; NSMenuItem* item = [nsMenu addItemWithTitle:@"Menu Item# 1" action:@selector(OnMenuSelection:) keyEquivalent:@""]; [item setTag:ID_FIRST]; item = [nsMenu addItemWithTitle:@"Menu Item #2" action:@selector(OnMenuSelection:) keyEquivalent:@""]; [item setTag:ID_SECOND]; //--------------------------------------------------------------------------------------------- // Providing a valid windowNumber is key in getting the Menu to display in the proper location //--------------------------------------------------------------------------------------------- int windowNumber = [(NSWindow*)myWindow windowNumber]; NSRect frame = [(NSWindow*)myWindow frame]; NSPoint wp = {pt.x, frame.size.height - pt.y}; // Origin in lower left NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined location:wp modifierFlags:NSApplicationDefined timestamp: (NSTimeInterval) 0 windowNumber: windowNumber context: [NSGraphicsContext currentContext] subtype:0 data1: 0 data2: 0]; [NSMenu popUpContextMenu:nsMenu withEvent:event forView:nsView]; NSMenuItem* MenuItem = [nsView MenuItem]; switch ([MenuItem tag]) { case ID_FIRST: HandleFirstCommand(); break; case ID_SECOND: HandleSecondCommand(); break; } } ```
227,939
<p>We're using HAProxy as a load balancer at the moment, and it regularly makes requests to the downstream boxes to make sure they're alive using an OPTIONS request:</p> <blockquote> <p>OPTIONS /index.html HTTP/1.0</p> </blockquote> <p>I'm working with getting nginx set up as a reverse proxy with caching (using ncache). For some reason, nginx is returning a 405 when an OPTIONS request comes in:</p> <blockquote> <p>192.168.1.10 - - [22/Oct/2008:16:36:21 -0700] "OPTIONS /index.html HTTP/1.0" 405 325 "-" "-" 192.168.1.10</p> </blockquote> <p>When hitting the downstream webserver directly, I get a proper 200 response. My question is: how to you make nginx pass that response along to HAProxy, or, how can I set the response in the nginx.conf?</p>
[ { "answer_id": 4662858, "author": "Mark Rose", "author_id": 438631, "author_profile": "https://Stackoverflow.com/users/438631", "pm_score": 2, "selected": false, "text": "<p>In the httpchk option, you can specify the HTTP method like this:</p>\n\n<pre><code>httpchk GET http://example.com/check.php\n</code></pre>\n\n<p>You can also use POST, or a plain URI like /. I have it check PHP, since PHP runs external to Nginx.</p>\n" }, { "answer_id": 9197143, "author": "rogeriopvl", "author_id": 28388, "author_profile": "https://Stackoverflow.com/users/28388", "pm_score": 6, "selected": false, "text": "<p>I'm probably late, but I had the same problem, and found two solutions to it.</p>\n\n<p>First is tricking Nginx that a 405 status is actually a 200 OK and then proxy_pass it to your HAProxy like this:</p>\n\n<pre><code>error_page 405 =200 @405;\nlocation @405 {\n root /;\n proxy_pass http://yourproxy:8080;\n}\n</code></pre>\n\n<p>The second solution is just to catch the OPTIONS request and build a response for those requests:</p>\n\n<pre><code>location / {\n if ($request_method = OPTIONS ) {\n add_header Content-Length 0;\n add_header Content-Type text/plain;\n return 200;\n }\n}\n</code></pre>\n\n<p>Just choose which one suits you better.</p>\n\n<p>I wrote this in a <a href=\"http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method\">blog post</a> where you can find more details.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30575/" ]
We're using HAProxy as a load balancer at the moment, and it regularly makes requests to the downstream boxes to make sure they're alive using an OPTIONS request: > > OPTIONS /index.html HTTP/1.0 > > > I'm working with getting nginx set up as a reverse proxy with caching (using ncache). For some reason, nginx is returning a 405 when an OPTIONS request comes in: > > 192.168.1.10 - - [22/Oct/2008:16:36:21 -0700] "OPTIONS /index.html HTTP/1.0" 405 325 "-" "-" 192.168.1.10 > > > When hitting the downstream webserver directly, I get a proper 200 response. My question is: how to you make nginx pass that response along to HAProxy, or, how can I set the response in the nginx.conf?
I'm probably late, but I had the same problem, and found two solutions to it. First is tricking Nginx that a 405 status is actually a 200 OK and then proxy\_pass it to your HAProxy like this: ``` error_page 405 =200 @405; location @405 { root /; proxy_pass http://yourproxy:8080; } ``` The second solution is just to catch the OPTIONS request and build a response for those requests: ``` location / { if ($request_method = OPTIONS ) { add_header Content-Length 0; add_header Content-Type text/plain; return 200; } } ``` Just choose which one suits you better. I wrote this in a [blog post](http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method) where you can find more details.
227,950
<p>I need to compare 2 strings as equal such as these:</p> <blockquote> <p>Lubeck == Lübeck</p> </blockquote> <p>In JavaScript.</p> <p>Why? Well, I have an auto-completion field that's going out to a Java service using Lucene, where place names are stored naturally (as Lübeck), but also indexed as normalized text, </p> <pre><code>import sun.text.Normalizer; oDoc.setNameLC = Normalizer.normalize(oLocName, Normalizer.DECOMP, 0) .toLowerCase().replaceAll("[^\\p{ASCII}]",""); </code></pre> <p>This way some-one who doesn't know to type "Mèxico" can type "mexico" and get a match which returns "Mèxico" (among a lot of other possible hits, like "Café Mèxico, Dubai, UAE").</p> <p>Now the thing is I don't have the ability to change the service to do any highlighting on the server side, therefore I am highlighting on the client JavaScript side with something like:</p> <pre><code>return result.replace( input.replace(/[aeiou]/g,"."), "&lt;b&gt;$1&lt;/b&gt;"); </code></pre> <p>It's a little more fancy because I am escaping special regex characters in the input. This is fine for simple one word matches at the beginning of a hit, but it really breaks down if you suddenly wish to support multi-word matches like "london cafe":</p> <pre><code>input = input.strip().toLowerCase(); //fyi prototype's strip is like trim re = new RegEx(input.replace(/[aeiou]/g,".").replace(/\s+/g,"|"),"gi"); return result.replace(re, "&lt;b&gt;$1&lt;/b&gt;"); </code></pre> <p>This doesn't work for say "london ca" (was typing london cafe), because it would mark "Jack London Cabin, Dawson City, Canada" as: <code>"Ja&lt;b&gt;ck&lt;/b&gt; &lt;b&gt;London&lt;/b&gt; &lt;b&gt;ca&lt;/b&gt;bin, Dawson &lt;b&gt;Ci&lt;/b&gt;ty, &lt;b&gt;Ca&lt;b/&gt;nada"</code> [note the "ck" and "Ci" particularly]</p> <p>Therefore I'm sort of looking for something that's not as crazy as:</p> <pre><code>input = input.strip().toLowerCase(); input = input.replace(/a/g,"[ÀàÁáÂâÃãÄäÅ寿ĀāĂ㥹]"); input = input.replace(/e/g,"[ÈèÉéÊêËëĒēĔĕĖėĘęĚě]"); // ditto for i, o, u, y, c, n, maybe also d, g, h, j, k, l, r, s, t, w, z re = new RegEx(input.replace(/\s+/g,"|"),"gi"); return result.replace(re, "&lt;b&gt;$1&lt;/b&gt;"); </code></pre> <p>Is there a compiled table I can refer to mapping a range of characters which are accented versions of an other character to that character, by which I don't mean the plain unicode chart. And if so, could I avoid using weird, possibly slow, RegEx statements?</p> <p><em>About the bounty:</em><br> Before I started a bounty there were two answers, the one pointing me to doing it in Ruby, and <a href="https://stackoverflow.com/questions/227950/programatic-accent-reduction-in-javascript-aka-text-normalization-or-unaccenting/228006#228006">the one</a> that <a href="https://stackoverflow.com/users/22364/mizardx">MizzardX</a> wrote which was a completion of the basic form I'd put in my question. Now don't get me wrong, I really appreciate working it out as completely as he did, but I just wished that there might be another way. It seems so far that everyone who's dropped by to look at the question and answer has decided that MizzardX covers it just fine, or that they have no different approach. I would be interested in a different approach, and if it simply isn't available before the bounty closes, MizzardX will win the bounty (though in a cruel twist, his edits mad it a community wiki answer, so I'm not sure if he'll get the bounty!)</p>
[ { "answer_id": 228006, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": true, "text": "<pre><code>/**\n * Creates a RegExp that matches the words in the search string.\n * Case and accent insensitive.\n */\nfunction make_pattern(search_string) {\n // escape meta characters\n search_string = search_string.replace(/([|()[{.+*?^$\\\\])/g,\"\\\\$1\");\n\n // split into words\n var words = search_string.split(/\\s+/);\n\n // sort by length\n var length_comp = function (a,b) {\n return b.length - a.length;\n };\n words.sort(length_comp);\n\n // replace characters by their compositors\n var accent_replacer = function(chr) {\n return accented[chr.toUpperCase()] || chr;\n }\n for (var i = 0; i &lt; words.length; i++) {\n words[i] = words[i].replace(/\\S/g,accent_replacer);\n }\n\n // join as alternatives\n var regexp = words.join(\"|\");\n return new RegExp(regexp,'g');\n}\n\nvar accented = {\n 'A': '[Aa\\xaa\\xc0-\\xc5\\xe0-\\xe5\\u0100-\\u0105\\u01cd\\u01ce\\u0200-\\u0203\\u0226\\u0227\\u1d2c\\u1d43\\u1e00\\u1e01\\u1e9a\\u1ea0-\\u1ea3\\u2090\\u2100\\u2101\\u213b\\u249c\\u24b6\\u24d0\\u3371-\\u3374\\u3380-\\u3384\\u3388\\u3389\\u33a9-\\u33af\\u33c2\\u33ca\\u33df\\u33ff\\uff21\\uff41]',\n 'B': '[Bb\\u1d2e\\u1d47\\u1e02-\\u1e07\\u212c\\u249d\\u24b7\\u24d1\\u3374\\u3385-\\u3387\\u33c3\\u33c8\\u33d4\\u33dd\\uff22\\uff42]',\n 'C': '[Cc\\xc7\\xe7\\u0106-\\u010d\\u1d9c\\u2100\\u2102\\u2103\\u2105\\u2106\\u212d\\u216d\\u217d\\u249e\\u24b8\\u24d2\\u3376\\u3388\\u3389\\u339d\\u33a0\\u33a4\\u33c4-\\u33c7\\uff23\\uff43]',\n 'D': '[Dd\\u010e\\u010f\\u01c4-\\u01c6\\u01f1-\\u01f3\\u1d30\\u1d48\\u1e0a-\\u1e13\\u2145\\u2146\\u216e\\u217e\\u249f\\u24b9\\u24d3\\u32cf\\u3372\\u3377-\\u3379\\u3397\\u33ad-\\u33af\\u33c5\\u33c8\\uff24\\uff44]',\n 'E': '[Ee\\xc8-\\xcb\\xe8-\\xeb\\u0112-\\u011b\\u0204-\\u0207\\u0228\\u0229\\u1d31\\u1d49\\u1e18-\\u1e1b\\u1eb8-\\u1ebd\\u2091\\u2121\\u212f\\u2130\\u2147\\u24a0\\u24ba\\u24d4\\u3250\\u32cd\\u32ce\\uff25\\uff45]',\n 'F': '[Ff\\u1da0\\u1e1e\\u1e1f\\u2109\\u2131\\u213b\\u24a1\\u24bb\\u24d5\\u338a-\\u338c\\u3399\\ufb00-\\ufb04\\uff26\\uff46]',\n 'G': '[Gg\\u011c-\\u0123\\u01e6\\u01e7\\u01f4\\u01f5\\u1d33\\u1d4d\\u1e20\\u1e21\\u210a\\u24a2\\u24bc\\u24d6\\u32cc\\u32cd\\u3387\\u338d-\\u338f\\u3393\\u33ac\\u33c6\\u33c9\\u33d2\\u33ff\\uff27\\uff47]',\n 'H': '[Hh\\u0124\\u0125\\u021e\\u021f\\u02b0\\u1d34\\u1e22-\\u1e2b\\u1e96\\u210b-\\u210e\\u24a3\\u24bd\\u24d7\\u32cc\\u3371\\u3390-\\u3394\\u33ca\\u33cb\\u33d7\\uff28\\uff48]',\n 'I': '[Ii\\xcc-\\xcf\\xec-\\xef\\u0128-\\u0130\\u0132\\u0133\\u01cf\\u01d0\\u0208-\\u020b\\u1d35\\u1d62\\u1e2c\\u1e2d\\u1ec8-\\u1ecb\\u2071\\u2110\\u2111\\u2139\\u2148\\u2160-\\u2163\\u2165-\\u2168\\u216a\\u216b\\u2170-\\u2173\\u2175-\\u2178\\u217a\\u217b\\u24a4\\u24be\\u24d8\\u337a\\u33cc\\u33d5\\ufb01\\ufb03\\uff29\\uff49]',\n 'J': '[Jj\\u0132-\\u0135\\u01c7-\\u01cc\\u01f0\\u02b2\\u1d36\\u2149\\u24a5\\u24bf\\u24d9\\u2c7c\\uff2a\\uff4a]',\n 'K': '[Kk\\u0136\\u0137\\u01e8\\u01e9\\u1d37\\u1d4f\\u1e30-\\u1e35\\u212a\\u24a6\\u24c0\\u24da\\u3384\\u3385\\u3389\\u338f\\u3391\\u3398\\u339e\\u33a2\\u33a6\\u33aa\\u33b8\\u33be\\u33c0\\u33c6\\u33cd-\\u33cf\\uff2b\\uff4b]',\n 'L': '[Ll\\u0139-\\u0140\\u01c7-\\u01c9\\u02e1\\u1d38\\u1e36\\u1e37\\u1e3a-\\u1e3d\\u2112\\u2113\\u2121\\u216c\\u217c\\u24a7\\u24c1\\u24db\\u32cf\\u3388\\u3389\\u33d0-\\u33d3\\u33d5\\u33d6\\u33ff\\ufb02\\ufb04\\uff2c\\uff4c]',\n 'M': '[Mm\\u1d39\\u1d50\\u1e3e-\\u1e43\\u2120\\u2122\\u2133\\u216f\\u217f\\u24a8\\u24c2\\u24dc\\u3377-\\u3379\\u3383\\u3386\\u338e\\u3392\\u3396\\u3399-\\u33a8\\u33ab\\u33b3\\u33b7\\u33b9\\u33bd\\u33bf\\u33c1\\u33c2\\u33ce\\u33d0\\u33d4-\\u33d6\\u33d8\\u33d9\\u33de\\u33df\\uff2d\\uff4d]',\n 'N': '[Nn\\xd1\\xf1\\u0143-\\u0149\\u01ca-\\u01cc\\u01f8\\u01f9\\u1d3a\\u1e44-\\u1e4b\\u207f\\u2115\\u2116\\u24a9\\u24c3\\u24dd\\u3381\\u338b\\u339a\\u33b1\\u33b5\\u33bb\\u33cc\\u33d1\\uff2e\\uff4e]',\n 'O': '[Oo\\xba\\xd2-\\xd6\\xf2-\\xf6\\u014c-\\u0151\\u01a0\\u01a1\\u01d1\\u01d2\\u01ea\\u01eb\\u020c-\\u020f\\u022e\\u022f\\u1d3c\\u1d52\\u1ecc-\\u1ecf\\u2092\\u2105\\u2116\\u2134\\u24aa\\u24c4\\u24de\\u3375\\u33c7\\u33d2\\u33d6\\uff2f\\uff4f]',\n 'P': '[Pp\\u1d3e\\u1d56\\u1e54-\\u1e57\\u2119\\u24ab\\u24c5\\u24df\\u3250\\u3371\\u3376\\u3380\\u338a\\u33a9-\\u33ac\\u33b0\\u33b4\\u33ba\\u33cb\\u33d7-\\u33da\\uff30\\uff50]',\n 'Q': '[Qq\\u211a\\u24ac\\u24c6\\u24e0\\u33c3\\uff31\\uff51]',\n 'R': '[Rr\\u0154-\\u0159\\u0210-\\u0213\\u02b3\\u1d3f\\u1d63\\u1e58-\\u1e5b\\u1e5e\\u1e5f\\u20a8\\u211b-\\u211d\\u24ad\\u24c7\\u24e1\\u32cd\\u3374\\u33ad-\\u33af\\u33da\\u33db\\uff32\\uff52]',\n 'S': '[Ss\\u015a-\\u0161\\u017f\\u0218\\u0219\\u02e2\\u1e60-\\u1e63\\u20a8\\u2101\\u2120\\u24ae\\u24c8\\u24e2\\u33a7\\u33a8\\u33ae-\\u33b3\\u33db\\u33dc\\ufb06\\uff33\\uff53]',\n 'T': '[Tt\\u0162-\\u0165\\u021a\\u021b\\u1d40\\u1d57\\u1e6a-\\u1e71\\u1e97\\u2121\\u2122\\u24af\\u24c9\\u24e3\\u3250\\u32cf\\u3394\\u33cf\\ufb05\\ufb06\\uff34\\uff54]',\n 'U': '[Uu\\xd9-\\xdc\\xf9-\\xfc\\u0168-\\u0173\\u01af\\u01b0\\u01d3\\u01d4\\u0214-\\u0217\\u1d41\\u1d58\\u1d64\\u1e72-\\u1e77\\u1ee4-\\u1ee7\\u2106\\u24b0\\u24ca\\u24e4\\u3373\\u337a\\uff35\\uff55]',\n 'V': '[Vv\\u1d5b\\u1d65\\u1e7c-\\u1e7f\\u2163-\\u2167\\u2173-\\u2177\\u24b1\\u24cb\\u24e5\\u2c7d\\u32ce\\u3375\\u33b4-\\u33b9\\u33dc\\u33de\\uff36\\uff56]',\n 'W': '[Ww\\u0174\\u0175\\u02b7\\u1d42\\u1e80-\\u1e89\\u1e98\\u24b2\\u24cc\\u24e6\\u33ba-\\u33bf\\u33dd\\uff37\\uff57]',\n 'X': '[Xx\\u02e3\\u1e8a-\\u1e8d\\u2093\\u213b\\u2168-\\u216b\\u2178-\\u217b\\u24b3\\u24cd\\u24e7\\u33d3\\uff38\\uff58]',\n 'Y': '[Yy\\xdd\\xfd\\xff\\u0176-\\u0178\\u0232\\u0233\\u02b8\\u1e8e\\u1e8f\\u1e99\\u1ef2-\\u1ef9\\u24b4\\u24ce\\u24e8\\u33c9\\uff39\\uff59]',\n 'Z': '[Zz\\u0179-\\u017e\\u01f1-\\u01f3\\u1dbb\\u1e90-\\u1e95\\u2124\\u2128\\u24b5\\u24cf\\u24e9\\u3390-\\u3394\\uff3a\\uff5a]'\n};\n</code></pre>\n" }, { "answer_id": 5913376, "author": "khel", "author_id": 171964, "author_profile": "https://Stackoverflow.com/users/171964", "pm_score": 5, "selected": false, "text": "<p>A more complete version with case sensitive support, ligatures and whatnot.\nOriginal source at: <a href=\"http://web.archive.org/web/20120918093154/http://lehelk.com/2011/05/06/script-to-remove-diacritics/\" rel=\"noreferrer\">http://lehelk.com/2011/05/06/script-to-remove-diacritics/</a></p>\n\n<pre><code>var defaultDiacriticsRemovalMap = [\n {'base':'A', 'letters':/[\\u0041\\u24B6\\uFF21\\u00C0\\u00C1\\u00C2\\u1EA6\\u1EA4\\u1EAA\\u1EA8\\u00C3\\u0100\\u0102\\u1EB0\\u1EAE\\u1EB4\\u1EB2\\u0226\\u01E0\\u00C4\\u01DE\\u1EA2\\u00C5\\u01FA\\u01CD\\u0200\\u0202\\u1EA0\\u1EAC\\u1EB6\\u1E00\\u0104\\u023A\\u2C6F]/g},\n {'base':'AA','letters':/[\\uA732]/g},\n {'base':'AE','letters':/[\\u00C6\\u01FC\\u01E2]/g},\n {'base':'AO','letters':/[\\uA734]/g},\n {'base':'AU','letters':/[\\uA736]/g},\n {'base':'AV','letters':/[\\uA738\\uA73A]/g},\n {'base':'AY','letters':/[\\uA73C]/g},\n {'base':'B', 'letters':/[\\u0042\\u24B7\\uFF22\\u1E02\\u1E04\\u1E06\\u0243\\u0182\\u0181]/g},\n {'base':'C', 'letters':/[\\u0043\\u24B8\\uFF23\\u0106\\u0108\\u010A\\u010C\\u00C7\\u1E08\\u0187\\u023B\\uA73E]/g},\n {'base':'D', 'letters':/[\\u0044\\u24B9\\uFF24\\u1E0A\\u010E\\u1E0C\\u1E10\\u1E12\\u1E0E\\u0110\\u018B\\u018A\\u0189\\uA779]/g},\n {'base':'DZ','letters':/[\\u01F1\\u01C4]/g},\n {'base':'Dz','letters':/[\\u01F2\\u01C5]/g},\n {'base':'E', 'letters':/[\\u0045\\u24BA\\uFF25\\u00C8\\u00C9\\u00CA\\u1EC0\\u1EBE\\u1EC4\\u1EC2\\u1EBC\\u0112\\u1E14\\u1E16\\u0114\\u0116\\u00CB\\u1EBA\\u011A\\u0204\\u0206\\u1EB8\\u1EC6\\u0228\\u1E1C\\u0118\\u1E18\\u1E1A\\u0190\\u018E]/g},\n {'base':'F', 'letters':/[\\u0046\\u24BB\\uFF26\\u1E1E\\u0191\\uA77B]/g},\n {'base':'G', 'letters':/[\\u0047\\u24BC\\uFF27\\u01F4\\u011C\\u1E20\\u011E\\u0120\\u01E6\\u0122\\u01E4\\u0193\\uA7A0\\uA77D\\uA77E]/g},\n {'base':'H', 'letters':/[\\u0048\\u24BD\\uFF28\\u0124\\u1E22\\u1E26\\u021E\\u1E24\\u1E28\\u1E2A\\u0126\\u2C67\\u2C75\\uA78D]/g},\n {'base':'I', 'letters':/[\\u0049\\u24BE\\uFF29\\u00CC\\u00CD\\u00CE\\u0128\\u012A\\u012C\\u0130\\u00CF\\u1E2E\\u1EC8\\u01CF\\u0208\\u020A\\u1ECA\\u012E\\u1E2C\\u0197]/g},\n {'base':'J', 'letters':/[\\u004A\\u24BF\\uFF2A\\u0134\\u0248]/g},\n {'base':'K', 'letters':/[\\u004B\\u24C0\\uFF2B\\u1E30\\u01E8\\u1E32\\u0136\\u1E34\\u0198\\u2C69\\uA740\\uA742\\uA744\\uA7A2]/g},\n {'base':'L', 'letters':/[\\u004C\\u24C1\\uFF2C\\u013F\\u0139\\u013D\\u1E36\\u1E38\\u013B\\u1E3C\\u1E3A\\u0141\\u023D\\u2C62\\u2C60\\uA748\\uA746\\uA780]/g},\n {'base':'LJ','letters':/[\\u01C7]/g},\n {'base':'Lj','letters':/[\\u01C8]/g},\n {'base':'M', 'letters':/[\\u004D\\u24C2\\uFF2D\\u1E3E\\u1E40\\u1E42\\u2C6E\\u019C]/g},\n {'base':'N', 'letters':/[\\u004E\\u24C3\\uFF2E\\u01F8\\u0143\\u00D1\\u1E44\\u0147\\u1E46\\u0145\\u1E4A\\u1E48\\u0220\\u019D\\uA790\\uA7A4]/g},\n {'base':'NJ','letters':/[\\u01CA]/g},\n {'base':'Nj','letters':/[\\u01CB]/g},\n {'base':'O', 'letters':/[\\u004F\\u24C4\\uFF2F\\u00D2\\u00D3\\u00D4\\u1ED2\\u1ED0\\u1ED6\\u1ED4\\u00D5\\u1E4C\\u022C\\u1E4E\\u014C\\u1E50\\u1E52\\u014E\\u022E\\u0230\\u00D6\\u022A\\u1ECE\\u0150\\u01D1\\u020C\\u020E\\u01A0\\u1EDC\\u1EDA\\u1EE0\\u1EDE\\u1EE2\\u1ECC\\u1ED8\\u01EA\\u01EC\\u00D8\\u01FE\\u0186\\u019F\\uA74A\\uA74C]/g},\n {'base':'OI','letters':/[\\u01A2]/g},\n {'base':'OO','letters':/[\\uA74E]/g},\n {'base':'OU','letters':/[\\u0222]/g},\n {'base':'P', 'letters':/[\\u0050\\u24C5\\uFF30\\u1E54\\u1E56\\u01A4\\u2C63\\uA750\\uA752\\uA754]/g},\n {'base':'Q', 'letters':/[\\u0051\\u24C6\\uFF31\\uA756\\uA758\\u024A]/g},\n {'base':'R', 'letters':/[\\u0052\\u24C7\\uFF32\\u0154\\u1E58\\u0158\\u0210\\u0212\\u1E5A\\u1E5C\\u0156\\u1E5E\\u024C\\u2C64\\uA75A\\uA7A6\\uA782]/g},\n {'base':'S', 'letters':/[\\u0053\\u24C8\\uFF33\\u1E9E\\u015A\\u1E64\\u015C\\u1E60\\u0160\\u1E66\\u1E62\\u1E68\\u0218\\u015E\\u2C7E\\uA7A8\\uA784]/g},\n {'base':'T', 'letters':/[\\u0054\\u24C9\\uFF34\\u1E6A\\u0164\\u1E6C\\u021A\\u0162\\u1E70\\u1E6E\\u0166\\u01AC\\u01AE\\u023E\\uA786]/g},\n {'base':'TZ','letters':/[\\uA728]/g},\n {'base':'U', 'letters':/[\\u0055\\u24CA\\uFF35\\u00D9\\u00DA\\u00DB\\u0168\\u1E78\\u016A\\u1E7A\\u016C\\u00DC\\u01DB\\u01D7\\u01D5\\u01D9\\u1EE6\\u016E\\u0170\\u01D3\\u0214\\u0216\\u01AF\\u1EEA\\u1EE8\\u1EEE\\u1EEC\\u1EF0\\u1EE4\\u1E72\\u0172\\u1E76\\u1E74\\u0244]/g},\n {'base':'V', 'letters':/[\\u0056\\u24CB\\uFF36\\u1E7C\\u1E7E\\u01B2\\uA75E\\u0245]/g},\n {'base':'VY','letters':/[\\uA760]/g},\n {'base':'W', 'letters':/[\\u0057\\u24CC\\uFF37\\u1E80\\u1E82\\u0174\\u1E86\\u1E84\\u1E88\\u2C72]/g},\n {'base':'X', 'letters':/[\\u0058\\u24CD\\uFF38\\u1E8A\\u1E8C]/g},\n {'base':'Y', 'letters':/[\\u0059\\u24CE\\uFF39\\u1EF2\\u00DD\\u0176\\u1EF8\\u0232\\u1E8E\\u0178\\u1EF6\\u1EF4\\u01B3\\u024E\\u1EFE]/g},\n {'base':'Z', 'letters':/[\\u005A\\u24CF\\uFF3A\\u0179\\u1E90\\u017B\\u017D\\u1E92\\u1E94\\u01B5\\u0224\\u2C7F\\u2C6B\\uA762]/g},\n {'base':'a', 'letters':/[\\u0061\\u24D0\\uFF41\\u1E9A\\u00E0\\u00E1\\u00E2\\u1EA7\\u1EA5\\u1EAB\\u1EA9\\u00E3\\u0101\\u0103\\u1EB1\\u1EAF\\u1EB5\\u1EB3\\u0227\\u01E1\\u00E4\\u01DF\\u1EA3\\u00E5\\u01FB\\u01CE\\u0201\\u0203\\u1EA1\\u1EAD\\u1EB7\\u1E01\\u0105\\u2C65\\u0250]/g},\n {'base':'aa','letters':/[\\uA733]/g},\n {'base':'ae','letters':/[\\u00E6\\u01FD\\u01E3]/g},\n {'base':'ao','letters':/[\\uA735]/g},\n {'base':'au','letters':/[\\uA737]/g},\n {'base':'av','letters':/[\\uA739\\uA73B]/g},\n {'base':'ay','letters':/[\\uA73D]/g},\n {'base':'b', 'letters':/[\\u0062\\u24D1\\uFF42\\u1E03\\u1E05\\u1E07\\u0180\\u0183\\u0253]/g},\n {'base':'c', 'letters':/[\\u0063\\u24D2\\uFF43\\u0107\\u0109\\u010B\\u010D\\u00E7\\u1E09\\u0188\\u023C\\uA73F\\u2184]/g},\n {'base':'d', 'letters':/[\\u0064\\u24D3\\uFF44\\u1E0B\\u010F\\u1E0D\\u1E11\\u1E13\\u1E0F\\u0111\\u018C\\u0256\\u0257\\uA77A]/g},\n {'base':'dz','letters':/[\\u01F3\\u01C6]/g},\n {'base':'e', 'letters':/[\\u0065\\u24D4\\uFF45\\u00E8\\u00E9\\u00EA\\u1EC1\\u1EBF\\u1EC5\\u1EC3\\u1EBD\\u0113\\u1E15\\u1E17\\u0115\\u0117\\u00EB\\u1EBB\\u011B\\u0205\\u0207\\u1EB9\\u1EC7\\u0229\\u1E1D\\u0119\\u1E19\\u1E1B\\u0247\\u025B\\u01DD]/g},\n {'base':'f', 'letters':/[\\u0066\\u24D5\\uFF46\\u1E1F\\u0192\\uA77C]/g},\n {'base':'g', 'letters':/[\\u0067\\u24D6\\uFF47\\u01F5\\u011D\\u1E21\\u011F\\u0121\\u01E7\\u0123\\u01E5\\u0260\\uA7A1\\u1D79\\uA77F]/g},\n {'base':'h', 'letters':/[\\u0068\\u24D7\\uFF48\\u0125\\u1E23\\u1E27\\u021F\\u1E25\\u1E29\\u1E2B\\u1E96\\u0127\\u2C68\\u2C76\\u0265]/g},\n {'base':'hv','letters':/[\\u0195]/g},\n {'base':'i', 'letters':/[\\u0069\\u24D8\\uFF49\\u00EC\\u00ED\\u00EE\\u0129\\u012B\\u012D\\u00EF\\u1E2F\\u1EC9\\u01D0\\u0209\\u020B\\u1ECB\\u012F\\u1E2D\\u0268\\u0131]/g},\n {'base':'j', 'letters':/[\\u006A\\u24D9\\uFF4A\\u0135\\u01F0\\u0249]/g},\n {'base':'k', 'letters':/[\\u006B\\u24DA\\uFF4B\\u1E31\\u01E9\\u1E33\\u0137\\u1E35\\u0199\\u2C6A\\uA741\\uA743\\uA745\\uA7A3]/g},\n {'base':'l', 'letters':/[\\u006C\\u24DB\\uFF4C\\u0140\\u013A\\u013E\\u1E37\\u1E39\\u013C\\u1E3D\\u1E3B\\u017F\\u0142\\u019A\\u026B\\u2C61\\uA749\\uA781\\uA747]/g},\n {'base':'lj','letters':/[\\u01C9]/g},\n {'base':'m', 'letters':/[\\u006D\\u24DC\\uFF4D\\u1E3F\\u1E41\\u1E43\\u0271\\u026F]/g},\n {'base':'n', 'letters':/[\\u006E\\u24DD\\uFF4E\\u01F9\\u0144\\u00F1\\u1E45\\u0148\\u1E47\\u0146\\u1E4B\\u1E49\\u019E\\u0272\\u0149\\uA791\\uA7A5]/g},\n {'base':'nj','letters':/[\\u01CC]/g},\n {'base':'o', 'letters':/[\\u006F\\u24DE\\uFF4F\\u00F2\\u00F3\\u00F4\\u1ED3\\u1ED1\\u1ED7\\u1ED5\\u00F5\\u1E4D\\u022D\\u1E4F\\u014D\\u1E51\\u1E53\\u014F\\u022F\\u0231\\u00F6\\u022B\\u1ECF\\u0151\\u01D2\\u020D\\u020F\\u01A1\\u1EDD\\u1EDB\\u1EE1\\u1EDF\\u1EE3\\u1ECD\\u1ED9\\u01EB\\u01ED\\u00F8\\u01FF\\u0254\\uA74B\\uA74D\\u0275]/g},\n {'base':'oi','letters':/[\\u01A3]/g},\n {'base':'ou','letters':/[\\u0223]/g},\n {'base':'oo','letters':/[\\uA74F]/g},\n {'base':'p','letters':/[\\u0070\\u24DF\\uFF50\\u1E55\\u1E57\\u01A5\\u1D7D\\uA751\\uA753\\uA755]/g},\n {'base':'q','letters':/[\\u0071\\u24E0\\uFF51\\u024B\\uA757\\uA759]/g},\n {'base':'r','letters':/[\\u0072\\u24E1\\uFF52\\u0155\\u1E59\\u0159\\u0211\\u0213\\u1E5B\\u1E5D\\u0157\\u1E5F\\u024D\\u027D\\uA75B\\uA7A7\\uA783]/g},\n {'base':'s','letters':/[\\u0073\\u24E2\\uFF53\\u00DF\\u015B\\u1E65\\u015D\\u1E61\\u0161\\u1E67\\u1E63\\u1E69\\u0219\\u015F\\u023F\\uA7A9\\uA785\\u1E9B]/g},\n {'base':'t','letters':/[\\u0074\\u24E3\\uFF54\\u1E6B\\u1E97\\u0165\\u1E6D\\u021B\\u0163\\u1E71\\u1E6F\\u0167\\u01AD\\u0288\\u2C66\\uA787]/g},\n {'base':'tz','letters':/[\\uA729]/g},\n {'base':'u','letters':/[\\u0075\\u24E4\\uFF55\\u00F9\\u00FA\\u00FB\\u0169\\u1E79\\u016B\\u1E7B\\u016D\\u00FC\\u01DC\\u01D8\\u01D6\\u01DA\\u1EE7\\u016F\\u0171\\u01D4\\u0215\\u0217\\u01B0\\u1EEB\\u1EE9\\u1EEF\\u1EED\\u1EF1\\u1EE5\\u1E73\\u0173\\u1E77\\u1E75\\u0289]/g},\n {'base':'v','letters':/[\\u0076\\u24E5\\uFF56\\u1E7D\\u1E7F\\u028B\\uA75F\\u028C]/g},\n {'base':'vy','letters':/[\\uA761]/g},\n {'base':'w','letters':/[\\u0077\\u24E6\\uFF57\\u1E81\\u1E83\\u0175\\u1E87\\u1E85\\u1E98\\u1E89\\u2C73]/g},\n {'base':'x','letters':/[\\u0078\\u24E7\\uFF58\\u1E8B\\u1E8D]/g},\n {'base':'y','letters':/[\\u0079\\u24E8\\uFF59\\u1EF3\\u00FD\\u0177\\u1EF9\\u0233\\u1E8F\\u00FF\\u1EF7\\u1E99\\u1EF5\\u01B4\\u024F\\u1EFF]/g},\n {'base':'z','letters':/[\\u007A\\u24E9\\uFF5A\\u017A\\u1E91\\u017C\\u017E\\u1E93\\u1E95\\u01B6\\u0225\\u0240\\u2C6C\\uA763]/g}\n];\nvar changes;\nfunction removeDiacritics (str) {\n if(!changes) {\n changes = defaultDiacriticsRemovalMap;\n }\n for(var i=0; i&lt;changes.length; i++) {\n str = str.replace(changes[i].letters, changes[i].base);\n }\n return str;\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
I need to compare 2 strings as equal such as these: > > Lubeck == Lübeck > > > In JavaScript. Why? Well, I have an auto-completion field that's going out to a Java service using Lucene, where place names are stored naturally (as Lübeck), but also indexed as normalized text, ``` import sun.text.Normalizer; oDoc.setNameLC = Normalizer.normalize(oLocName, Normalizer.DECOMP, 0) .toLowerCase().replaceAll("[^\\p{ASCII}]",""); ``` This way some-one who doesn't know to type "Mèxico" can type "mexico" and get a match which returns "Mèxico" (among a lot of other possible hits, like "Café Mèxico, Dubai, UAE"). Now the thing is I don't have the ability to change the service to do any highlighting on the server side, therefore I am highlighting on the client JavaScript side with something like: ``` return result.replace( input.replace(/[aeiou]/g,"."), "<b>$1</b>"); ``` It's a little more fancy because I am escaping special regex characters in the input. This is fine for simple one word matches at the beginning of a hit, but it really breaks down if you suddenly wish to support multi-word matches like "london cafe": ``` input = input.strip().toLowerCase(); //fyi prototype's strip is like trim re = new RegEx(input.replace(/[aeiou]/g,".").replace(/\s+/g,"|"),"gi"); return result.replace(re, "<b>$1</b>"); ``` This doesn't work for say "london ca" (was typing london cafe), because it would mark "Jack London Cabin, Dawson City, Canada" as: `"Ja<b>ck</b> <b>London</b> <b>ca</b>bin, Dawson <b>Ci</b>ty, <b>Ca<b/>nada"` [note the "ck" and "Ci" particularly] Therefore I'm sort of looking for something that's not as crazy as: ``` input = input.strip().toLowerCase(); input = input.replace(/a/g,"[ÀàÁáÂâÃãÄäÅ寿ĀāĂ㥹]"); input = input.replace(/e/g,"[ÈèÉéÊêËëĒēĔĕĖėĘęĚě]"); // ditto for i, o, u, y, c, n, maybe also d, g, h, j, k, l, r, s, t, w, z re = new RegEx(input.replace(/\s+/g,"|"),"gi"); return result.replace(re, "<b>$1</b>"); ``` Is there a compiled table I can refer to mapping a range of characters which are accented versions of an other character to that character, by which I don't mean the plain unicode chart. And if so, could I avoid using weird, possibly slow, RegEx statements? *About the bounty:* Before I started a bounty there were two answers, the one pointing me to doing it in Ruby, and [the one](https://stackoverflow.com/questions/227950/programatic-accent-reduction-in-javascript-aka-text-normalization-or-unaccenting/228006#228006) that [MizzardX](https://stackoverflow.com/users/22364/mizardx) wrote which was a completion of the basic form I'd put in my question. Now don't get me wrong, I really appreciate working it out as completely as he did, but I just wished that there might be another way. It seems so far that everyone who's dropped by to look at the question and answer has decided that MizzardX covers it just fine, or that they have no different approach. I would be interested in a different approach, and if it simply isn't available before the bounty closes, MizzardX will win the bounty (though in a cruel twist, his edits mad it a community wiki answer, so I'm not sure if he'll get the bounty!)
``` /** * Creates a RegExp that matches the words in the search string. * Case and accent insensitive. */ function make_pattern(search_string) { // escape meta characters search_string = search_string.replace(/([|()[{.+*?^$\\])/g,"\\$1"); // split into words var words = search_string.split(/\s+/); // sort by length var length_comp = function (a,b) { return b.length - a.length; }; words.sort(length_comp); // replace characters by their compositors var accent_replacer = function(chr) { return accented[chr.toUpperCase()] || chr; } for (var i = 0; i < words.length; i++) { words[i] = words[i].replace(/\S/g,accent_replacer); } // join as alternatives var regexp = words.join("|"); return new RegExp(regexp,'g'); } var accented = { 'A': '[Aa\xaa\xc0-\xc5\xe0-\xe5\u0100-\u0105\u01cd\u01ce\u0200-\u0203\u0226\u0227\u1d2c\u1d43\u1e00\u1e01\u1e9a\u1ea0-\u1ea3\u2090\u2100\u2101\u213b\u249c\u24b6\u24d0\u3371-\u3374\u3380-\u3384\u3388\u3389\u33a9-\u33af\u33c2\u33ca\u33df\u33ff\uff21\uff41]', 'B': '[Bb\u1d2e\u1d47\u1e02-\u1e07\u212c\u249d\u24b7\u24d1\u3374\u3385-\u3387\u33c3\u33c8\u33d4\u33dd\uff22\uff42]', 'C': '[Cc\xc7\xe7\u0106-\u010d\u1d9c\u2100\u2102\u2103\u2105\u2106\u212d\u216d\u217d\u249e\u24b8\u24d2\u3376\u3388\u3389\u339d\u33a0\u33a4\u33c4-\u33c7\uff23\uff43]', 'D': '[Dd\u010e\u010f\u01c4-\u01c6\u01f1-\u01f3\u1d30\u1d48\u1e0a-\u1e13\u2145\u2146\u216e\u217e\u249f\u24b9\u24d3\u32cf\u3372\u3377-\u3379\u3397\u33ad-\u33af\u33c5\u33c8\uff24\uff44]', 'E': '[Ee\xc8-\xcb\xe8-\xeb\u0112-\u011b\u0204-\u0207\u0228\u0229\u1d31\u1d49\u1e18-\u1e1b\u1eb8-\u1ebd\u2091\u2121\u212f\u2130\u2147\u24a0\u24ba\u24d4\u3250\u32cd\u32ce\uff25\uff45]', 'F': '[Ff\u1da0\u1e1e\u1e1f\u2109\u2131\u213b\u24a1\u24bb\u24d5\u338a-\u338c\u3399\ufb00-\ufb04\uff26\uff46]', 'G': '[Gg\u011c-\u0123\u01e6\u01e7\u01f4\u01f5\u1d33\u1d4d\u1e20\u1e21\u210a\u24a2\u24bc\u24d6\u32cc\u32cd\u3387\u338d-\u338f\u3393\u33ac\u33c6\u33c9\u33d2\u33ff\uff27\uff47]', 'H': '[Hh\u0124\u0125\u021e\u021f\u02b0\u1d34\u1e22-\u1e2b\u1e96\u210b-\u210e\u24a3\u24bd\u24d7\u32cc\u3371\u3390-\u3394\u33ca\u33cb\u33d7\uff28\uff48]', 'I': '[Ii\xcc-\xcf\xec-\xef\u0128-\u0130\u0132\u0133\u01cf\u01d0\u0208-\u020b\u1d35\u1d62\u1e2c\u1e2d\u1ec8-\u1ecb\u2071\u2110\u2111\u2139\u2148\u2160-\u2163\u2165-\u2168\u216a\u216b\u2170-\u2173\u2175-\u2178\u217a\u217b\u24a4\u24be\u24d8\u337a\u33cc\u33d5\ufb01\ufb03\uff29\uff49]', 'J': '[Jj\u0132-\u0135\u01c7-\u01cc\u01f0\u02b2\u1d36\u2149\u24a5\u24bf\u24d9\u2c7c\uff2a\uff4a]', 'K': '[Kk\u0136\u0137\u01e8\u01e9\u1d37\u1d4f\u1e30-\u1e35\u212a\u24a6\u24c0\u24da\u3384\u3385\u3389\u338f\u3391\u3398\u339e\u33a2\u33a6\u33aa\u33b8\u33be\u33c0\u33c6\u33cd-\u33cf\uff2b\uff4b]', 'L': '[Ll\u0139-\u0140\u01c7-\u01c9\u02e1\u1d38\u1e36\u1e37\u1e3a-\u1e3d\u2112\u2113\u2121\u216c\u217c\u24a7\u24c1\u24db\u32cf\u3388\u3389\u33d0-\u33d3\u33d5\u33d6\u33ff\ufb02\ufb04\uff2c\uff4c]', 'M': '[Mm\u1d39\u1d50\u1e3e-\u1e43\u2120\u2122\u2133\u216f\u217f\u24a8\u24c2\u24dc\u3377-\u3379\u3383\u3386\u338e\u3392\u3396\u3399-\u33a8\u33ab\u33b3\u33b7\u33b9\u33bd\u33bf\u33c1\u33c2\u33ce\u33d0\u33d4-\u33d6\u33d8\u33d9\u33de\u33df\uff2d\uff4d]', 'N': '[Nn\xd1\xf1\u0143-\u0149\u01ca-\u01cc\u01f8\u01f9\u1d3a\u1e44-\u1e4b\u207f\u2115\u2116\u24a9\u24c3\u24dd\u3381\u338b\u339a\u33b1\u33b5\u33bb\u33cc\u33d1\uff2e\uff4e]', 'O': '[Oo\xba\xd2-\xd6\xf2-\xf6\u014c-\u0151\u01a0\u01a1\u01d1\u01d2\u01ea\u01eb\u020c-\u020f\u022e\u022f\u1d3c\u1d52\u1ecc-\u1ecf\u2092\u2105\u2116\u2134\u24aa\u24c4\u24de\u3375\u33c7\u33d2\u33d6\uff2f\uff4f]', 'P': '[Pp\u1d3e\u1d56\u1e54-\u1e57\u2119\u24ab\u24c5\u24df\u3250\u3371\u3376\u3380\u338a\u33a9-\u33ac\u33b0\u33b4\u33ba\u33cb\u33d7-\u33da\uff30\uff50]', 'Q': '[Qq\u211a\u24ac\u24c6\u24e0\u33c3\uff31\uff51]', 'R': '[Rr\u0154-\u0159\u0210-\u0213\u02b3\u1d3f\u1d63\u1e58-\u1e5b\u1e5e\u1e5f\u20a8\u211b-\u211d\u24ad\u24c7\u24e1\u32cd\u3374\u33ad-\u33af\u33da\u33db\uff32\uff52]', 'S': '[Ss\u015a-\u0161\u017f\u0218\u0219\u02e2\u1e60-\u1e63\u20a8\u2101\u2120\u24ae\u24c8\u24e2\u33a7\u33a8\u33ae-\u33b3\u33db\u33dc\ufb06\uff33\uff53]', 'T': '[Tt\u0162-\u0165\u021a\u021b\u1d40\u1d57\u1e6a-\u1e71\u1e97\u2121\u2122\u24af\u24c9\u24e3\u3250\u32cf\u3394\u33cf\ufb05\ufb06\uff34\uff54]', 'U': '[Uu\xd9-\xdc\xf9-\xfc\u0168-\u0173\u01af\u01b0\u01d3\u01d4\u0214-\u0217\u1d41\u1d58\u1d64\u1e72-\u1e77\u1ee4-\u1ee7\u2106\u24b0\u24ca\u24e4\u3373\u337a\uff35\uff55]', 'V': '[Vv\u1d5b\u1d65\u1e7c-\u1e7f\u2163-\u2167\u2173-\u2177\u24b1\u24cb\u24e5\u2c7d\u32ce\u3375\u33b4-\u33b9\u33dc\u33de\uff36\uff56]', 'W': '[Ww\u0174\u0175\u02b7\u1d42\u1e80-\u1e89\u1e98\u24b2\u24cc\u24e6\u33ba-\u33bf\u33dd\uff37\uff57]', 'X': '[Xx\u02e3\u1e8a-\u1e8d\u2093\u213b\u2168-\u216b\u2178-\u217b\u24b3\u24cd\u24e7\u33d3\uff38\uff58]', 'Y': '[Yy\xdd\xfd\xff\u0176-\u0178\u0232\u0233\u02b8\u1e8e\u1e8f\u1e99\u1ef2-\u1ef9\u24b4\u24ce\u24e8\u33c9\uff39\uff59]', 'Z': '[Zz\u0179-\u017e\u01f1-\u01f3\u1dbb\u1e90-\u1e95\u2124\u2128\u24b5\u24cf\u24e9\u3390-\u3394\uff3a\uff5a]' }; ```
227,973
<p>I've got an application that needs quite a bit of data (1000s of records) to do appropriate testing. The only way I've found to get a decent set of testable, sensible data is to use a <strong>subset of my production DB</strong>. I've converted this to YAML fixtures in the normal `test/fixtures' location.</p> <p>This works, but now I have a bunch of seemingly brittle tests and assertions that depend on their being a particular number of records that meet condition X...</p> <p>example</p> <pre><code>def test_children_association p = Parent.find(1) assert_equal 18, p.children.count, "Parent.children isn't providing the right records" end </code></pre> <p>This doesn't seem like a good idea to me, but <strong>I'm not sure if there is a better / accepted way</strong> to test an application that needs a large hierarchy of data.</p>
[ { "answer_id": 228944, "author": "Cameron McCloud", "author_id": 25484, "author_profile": "https://Stackoverflow.com/users/25484", "pm_score": 0, "selected": false, "text": "<p>The first thing I'd say is: what are you testing in that example? If it's an ordinary AR has_many association, then I wouldn't bother writing a test for it. All you're doing is testing that AR works.</p>\n\n<p>A better example might be if you had a very complicated query or if there was other processing involved in getting the list of children records. When you get them back, rather than testing for a count you could iterate through the returned list and verify that the children match the criteria you're using.</p>\n" }, { "answer_id": 229188, "author": "derfred", "author_id": 10286, "author_profile": "https://Stackoverflow.com/users/10286", "pm_score": 0, "selected": false, "text": "<p>what I've found most useful in this situation is not using fixtures at all but rather construct the database objects on the fly like </p>\n\n<pre><code>def test_foo\n project = Project.create valid_project.merge(....)\n *do assertions here*\nend\n</code></pre>\n\n<p>and in my test_helpers I'd have a bunch of methods:</p>\n\n<pre><code>def valid_project\n { :user_id =&gt; 23, :title =&gt; \"My Project\" }\nend\n\ndef invalid_project\n valid_project.merge(:title =&gt; nil)\nend\n</code></pre>\n\n<p>I found that the pain of having to build massive collections of test objects has led me naturally to design simpler and more versatile class structures.</p>\n" }, { "answer_id": 229485, "author": "marcumka", "author_id": 30761, "author_profile": "https://Stackoverflow.com/users/30761", "pm_score": 4, "selected": true, "text": "<p>Magic numbers in tests aren't an anti-pattern. Your tests need to be so dead-simple that you don't need to <em>test</em> them. This means you'll have some magic numbers. This means that your tests will break when you change small bits of functionality. This is good.</p>\n\n<p>Fixtures have <a href=\"http://www.floehopper.org/articles/2006/06/27/rails-fixtures-help-or-hindrance\" rel=\"noreferrer\">some problems</a>, but there are a few simple things you can do to make them easier to work with:</p>\n\n<ol>\n<li><p>Only have baseline data in your fixtures, the sort of data that most of your tests need but don't care about. This will involve a time investment up front, but it's better to take the pain early than write poor unit tests for the life of the project.</p></li>\n<li><p>Add the data to be tested in the context of the test. This improves readability of your tests and saves you from writing \"make sure nobody messed up the fixtures\" sanity checks at the beginning of your unit tests.</p></li>\n</ol>\n" }, { "answer_id": 236360, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 0, "selected": false, "text": "<p>Cameron's right: What are you testing?</p>\n\n<p>What sort of system needs 1000s of records present to test? Remember, your tests should be as tiny as possible and should be testing application behavior. There's no way it needs thousands of records for the vast majority of those tests.</p>\n\n<p>For little bits of behavior tests where you need object relationships, consider mock objects. You'll only be speccing out the exact minimum amount of behavior necessary to get your test to pass, and they won't hit the DB at all, which will amount to a huge performance gain in your test suite. The faster it is to run, the more often people will run it.</p>\n" }, { "answer_id": 236700, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 0, "selected": false, "text": "<p>I may have a unique situation here, but I really did need quite a few records for testing this app (I got it down to 150 or so). I'm analyzing historical data and have numerous levels of <code>has_many</code>. Some of my methods do custom SQL queries across several tables which I might end up modifying to use <code>ActiveRecord.find</code> but I needed to get the test running first.</p>\n\n<p>Anyway, I ended up using some <strong>ruby code to create the fixtures</strong>. The code is included in my <code>test_helper</code>; it checks the test DB to see if the data is stale (based on a time condition) and wipes and <strong>recreates the records procedurally</strong>. In this case, creating it procedurally allows me to know what the data I'm testing for <em>SHOULD</em> be, which is <strong>safer than using a subset of production data</strong> and hoping the numbers I calculate the first time are what I should test for in the future.</p>\n\n<p>I also moved to using <a href=\"http://www.thoughtbot.com/projects/shoulda/\" rel=\"nofollow noreferrer\">Shoulda</a> which along with many other useful things makes ActiveRecord Association testing as easy as:</p>\n\n<pre><code>should_have_many :children\nshould_belong_to :parent\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216/" ]
I've got an application that needs quite a bit of data (1000s of records) to do appropriate testing. The only way I've found to get a decent set of testable, sensible data is to use a **subset of my production DB**. I've converted this to YAML fixtures in the normal `test/fixtures' location. This works, but now I have a bunch of seemingly brittle tests and assertions that depend on their being a particular number of records that meet condition X... example ``` def test_children_association p = Parent.find(1) assert_equal 18, p.children.count, "Parent.children isn't providing the right records" end ``` This doesn't seem like a good idea to me, but **I'm not sure if there is a better / accepted way** to test an application that needs a large hierarchy of data.
Magic numbers in tests aren't an anti-pattern. Your tests need to be so dead-simple that you don't need to *test* them. This means you'll have some magic numbers. This means that your tests will break when you change small bits of functionality. This is good. Fixtures have [some problems](http://www.floehopper.org/articles/2006/06/27/rails-fixtures-help-or-hindrance), but there are a few simple things you can do to make them easier to work with: 1. Only have baseline data in your fixtures, the sort of data that most of your tests need but don't care about. This will involve a time investment up front, but it's better to take the pain early than write poor unit tests for the life of the project. 2. Add the data to be tested in the context of the test. This improves readability of your tests and saves you from writing "make sure nobody messed up the fixtures" sanity checks at the beginning of your unit tests.
227,994
<p>We have the following simple Stored Procedure that runs as an overnight SQL server agent job. Usually it runs in 20 minutes, but recently the MatchEvent and MatchResult tables have grown to over 9 million rows each. This has resulted in the store procedure taking over 2 hours to run, with all 8GB of memory on our SQL box being used up. This renders the database unavailable to the regular queries that are trying to access it.</p> <p>I assume the problem is that temp table is too large and is causing the memory and database unavailablity issues.</p> <p>How can I rewrite the stored procedure to make it more efficient and less memory intensive?</p> <p>Note: I have edited the SQL to indicate that there is come condition affecting the initial SELECT statement. I had previously left this out for simplicity. Also, when the query runs CPU usage is at 1-2%, but memoery, as previously stated, is maxed out</p> <p><pre><code> CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) )</p> <p>INSERT INTO #tempMatchResult SELECT MatchId FROM MatchResult WHERE SOME_CONDITION</p> <p>DELETE FROM MatchEvent WHERE<br> MatchId IN (SELECT MatchId FROM #tempMatchResult)</p> <p>DELETE FROM MatchResult WHERE MatchId In (SELECT MatchId FROM #tempMatchResult)</p> <p>DROP TABLE #tempMatchResult </pre></code></p>
[ { "answer_id": 228003, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "<p>Looking at the code above, why do you need a temp table?</p>\n\n<pre>\n<code>\nDELETE FROM MatchEvent WHERE\nMatchId IN (SELECT MatchId FROM MatchResult)\n\n\nDELETE FROM MatchResult\n-- OR Truncate can help here, if all the records are to be deleted anyways.\n</code>\n</pre>\n" }, { "answer_id": 228052, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 0, "selected": false, "text": "<p>You probably want to process this piecewise in some way. (I assume queries are a lot more complicated that you showed?) In that case, you'd want try one of these:</p>\n\n<ul>\n<li>Write your stored procedure to iterate over results. (Might still lock while processing.)</li>\n<li>Repeatedly select the N first hits, eg <code>LIMIT 100</code> and process those.</li>\n<li>Divide work by scanning regions of the table separately, using something like WHERE M &lt;= x AND x &lt; N.</li>\n<li>Run the \"midnight job\" more often. Seriously, running stuff like this every 5 mins instead can work wonders, especially if work increases non-linearly. (If not, you could still just get the work spread out over the hours of the day.)</li>\n</ul>\n\n<p>In Postgres, I've had some success using conditional indices. They work magic by applying an index if certain conditions are met. This means that you can keep the many 'resolved' and the few unresolved rows in the same table, but still get that special index over just the unresolved ones. Ymmv.</p>\n\n<p>Should be pointed out that this is where using databases gets <em>interesting</em>. You need to pay close attention to your indices and use <code>EXPLAIN</code> on your queries a lot.</p>\n\n<p>(Oh, and remember, <em>interesting</em> is a good thing in your hobbies, but not at work.)</p>\n" }, { "answer_id": 228204, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "<p>There's probably a lot of stuff going on here, and it's not all your query. </p>\n\n<p>First, I agree with the other posters. Try to rewrite this without a temp table if at all possible.</p>\n\n<p>But assuming that you need a temp table here, you have a BIG problem in that you have no PK defined on it. It's vastly going to expand the amount of time your queries will take to run. Create your table like so instead:</p>\n\n<pre><code>CREATE TABLE #tempMatchResult (\n matchId VARCHAR(50) NOT NULL PRIMARY KEY /* NOT NULL if at all possible */\n);\n\nINSERT INTO #tempMatchResult\nSELECT DISTINCT MatchId FROM MatchResult;\n</code></pre>\n\n<p>Also, make sure that your TempDB is sized correctly. Your SQL server may very well be expanding the database file dynamically on you, causing your query to suck CPU and disk time. Also, make sure your transaction log is sized correctly, and that it is not auto-growing on you. Good luck.</p>\n" }, { "answer_id": 228822, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>First, indexes are a MUST here see Dave M's answer. </p>\n\n<p>Another approach that I will sometime use when deleting very large data sets, is creating a shadow table with all the data, recreating indexes and then using sp_rename to switch it in. You have to be careful with transactions here, but depending on the amount of data being deleted this can be faster.</p>\n\n<p><em>Note</em> If there is pressure on tempdb consider using joins and not copying all the data into the temp table. </p>\n\n<p>So for example </p>\n\n<pre><code>CREATE TABLE #tempMatchResult (\n matchId VARCHAR(50) NOT NULL PRIMARY KEY /* NOT NULL if at all possible */\n);\n\nINSERT INTO #tempMatchResult\nSELECT DISTINCT MatchId FROM MatchResult;\n\nset transaction isolation level serializable\nbegin transaction \n\ncreate table MatchEventT(columns... here)\n\ninsert into MatchEventT\nselect * from MatchEvent m\nleft join #tempMatchResult t on t.MatchId = m.MatchId \nwhere t.MatchId is null \n\n-- create all the indexes for MatchEvent\n\ndrop table MatchEvent\nexec sp_rename 'MatchEventT', 'MatchEvent'\n\n-- similar code for MatchResult\n\ncommit transaction \n\n\nDROP TABLE #tempMatchResult\n</code></pre>\n" }, { "answer_id": 229048, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<h3>Avoid the temp table if possible</h3>\n\n<p>It's only using up memory.<br>\nYou could try this: </p>\n\n<pre><code>DELETE MatchEvent\nFROM MatchEvent e , \n MatchResult r\nWHERE e.MatchId = r.MatchId \n</code></pre>\n\n<h3>If you can't avoid a temp table</h3>\n\n<p>I'm going to stick my neck out here and say: <strong>you don't need an index on your temporary table</strong> because you want the temp table to be the smallest table in the equation and you want to table scan it (because all the rows are relevant). An index won't help you here. </p>\n\n<h3>Do small bits of work</h3>\n\n<p>Work on a few rows at a time.<br>\nThis will probably slow down the execution, but it should free up resources. </p>\n\n- One row at a time\n\n<pre><code>SELECT @MatchId = min(MatchId) FROM MatchResult\n\nWHILE @MatchId IS NOT NULL\nBEGIN\n DELETE MatchEvent \n WHERE Match_Id = @MatchId \n\n SELECT @MatchId = min(MatchId) FROM MatchResult WHERE MatchId &gt; @MatchId \nEND\n</code></pre>\n\n- A few rows at a time\n\n<pre><code>CREATE TABLE #tmp ( MatchId Varchar(50) ) \n\n/* get list of lowest 1000 MatchIds: */ \nINSERT #tmp \nSELECT TOP (1000) MatchId \nFROM MatchResult \nORDER BY MatchId \n\nSELECT @MatchId = min(MatchId) FROM MatchResult\n\nWHILE @MatchId IS NOT NULL\nBEGIN\n DELETE MatchEvent\n FROM MatchEvent e , \n #tmp t\n WHERE e.MatchId = t.MatchId \n\n /* get highest MatchId we've procesed: */ \n SELECT @MinMatchId = MAX( MatchId ) FROM #tmp \n\n /* get next 1000 MatchIds: */ \n INSERT #tmp \n SELECT TOP (1000) MatchId \n FROM MatchResult \n WHERE MatchId &gt; @MinMatchId\n ORDER BY MatchId \n\nEND\n</code></pre>\n\n<p>This one deletes up to 1000 rows at a time.<br>\nThe more rows you delete at a time, the more resources you will use but the faster it will tend to run (until you run out of resources!). You can experiment to find a more optimal value than 1000. </p>\n" }, { "answer_id": 13495590, "author": "Philip Wade", "author_id": 1017395, "author_profile": "https://Stackoverflow.com/users/1017395", "pm_score": 0, "selected": false, "text": "<pre><code>DELETE FROM MatchResult WHERE\nMatchId In (SELECT MatchId FROM #tempMatchResult)\n</code></pre>\n\n<p>can be replaced with </p>\n\n<pre><code>DELETE FROM MatchResult WHERE SOME_CONDITION\n</code></pre>\n" }, { "answer_id": 21703229, "author": "piers7", "author_id": 26167, "author_profile": "https://Stackoverflow.com/users/26167", "pm_score": 0, "selected": false, "text": "<p>Can you just turn cascading deletes on between matchresult and matchevent? Then you need only worry about identifying one set of data to delete, and let SQL take care of the other.</p>\n\n<p>The alternative would be to make use of the OUTPUT clause, but that's definitely more fiddle.</p>\n\n<p>Both of these would let you delete from both tables, but only have to state (and execute) your filter predicate once. This may <em>still</em> not be as performant as a batching approach as suggested by other posters, but worth considering. YMMV</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/227994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17765/" ]
We have the following simple Stored Procedure that runs as an overnight SQL server agent job. Usually it runs in 20 minutes, but recently the MatchEvent and MatchResult tables have grown to over 9 million rows each. This has resulted in the store procedure taking over 2 hours to run, with all 8GB of memory on our SQL box being used up. This renders the database unavailable to the regular queries that are trying to access it. I assume the problem is that temp table is too large and is causing the memory and database unavailablity issues. How can I rewrite the stored procedure to make it more efficient and less memory intensive? Note: I have edited the SQL to indicate that there is come condition affecting the initial SELECT statement. I had previously left this out for simplicity. Also, when the query runs CPU usage is at 1-2%, but memoery, as previously stated, is maxed out ``` CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) ) ``` INSERT INTO #tempMatchResult SELECT MatchId FROM MatchResult WHERE SOME\_CONDITION DELETE FROM MatchEvent WHERE MatchId IN (SELECT MatchId FROM #tempMatchResult) DELETE FROM MatchResult WHERE MatchId In (SELECT MatchId FROM #tempMatchResult) DROP TABLE #tempMatchResult
There's probably a lot of stuff going on here, and it's not all your query. First, I agree with the other posters. Try to rewrite this without a temp table if at all possible. But assuming that you need a temp table here, you have a BIG problem in that you have no PK defined on it. It's vastly going to expand the amount of time your queries will take to run. Create your table like so instead: ``` CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) NOT NULL PRIMARY KEY /* NOT NULL if at all possible */ ); INSERT INTO #tempMatchResult SELECT DISTINCT MatchId FROM MatchResult; ``` Also, make sure that your TempDB is sized correctly. Your SQL server may very well be expanding the database file dynamically on you, causing your query to suck CPU and disk time. Also, make sure your transaction log is sized correctly, and that it is not auto-growing on you. Good luck.
228,005
<p>I was wondering if there was an alternative to <code>itoa()</code> for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.</p>
[ { "answer_id": 228010, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm\" rel=\"noreferrer\">boost::lexical_cast</a> works pretty well.</p>\n\n<pre><code>#include &lt;boost/lexical_cast.hpp&gt;\nint main(int argc, char** argv) {\n std::string foo = boost::lexical_cast&lt;std::string&gt;(argc);\n}\n</code></pre>\n" }, { "answer_id": 228012, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": false, "text": "<p>Try sprintf():</p>\n\n<pre><code>char str[12];\nint num = 3;\nsprintf(str, \"%d\", num); // str now contains \"3\"\n</code></pre>\n\n<p>sprintf() is like printf() but outputs to a string.</p>\n\n<p>Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:</p>\n\n<pre><code>snprintf(str, sizeof(str), \"%d\", num);\n</code></pre>\n" }, { "answer_id": 228016, "author": "Iain", "author_id": 12060, "author_profile": "https://Stackoverflow.com/users/12060", "pm_score": 2, "selected": false, "text": "<p>Allocate a string of sufficient length, then use snprintf.</p>\n" }, { "answer_id": 228039, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 9, "selected": true, "text": "<p>In C++11 you can use <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"noreferrer\"><code>std::to_string</code></a>:</p>\n\n<pre><code>#include &lt;string&gt;\n\nstd::string s = std::to_string(5);\n</code></pre>\n\n<p>If you're working with prior to C++11, you could use C++ streams:</p>\n\n<pre><code>#include &lt;sstream&gt;\n\nint i = 5;\nstd::string s;\nstd::stringstream out;\nout &lt;&lt; i;\ns = out.str();\n</code></pre>\n\n<p>Taken from <a href=\"http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/\" rel=\"noreferrer\">http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/</a></p>\n" }, { "answer_id": 228040, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": -1, "selected": false, "text": "<p>Most of the above suggestions technically aren't C++, they're C solutions.</p>\n\n<p>Look into the use of <a href=\"http://www.cplusplus.com/reference/iostream/stringstream/\" rel=\"nofollow noreferrer\">std::stringstream</a>.</p>\n" }, { "answer_id": 228041, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": false, "text": "<p>Behind the scenes, lexical_cast does this:</p>\n\n<pre><code>std::stringstream str;\nstr &lt;&lt; myint;\nstd::string result;\nstr &gt;&gt; result;\n</code></pre>\n\n<p>If you don't want to \"drag in\" boost for this, then using the above is a good solution.</p>\n" }, { "answer_id": 228749, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 1, "selected": false, "text": "<p>Note that all of the <code>stringstream</code> methods <strong>may</strong> involve locking around the use of the locale object for formatting. This <strong>may</strong> be something to be wary of if you're using this conversion from multiple threads...</p>\n\n<p>See here for more. <a href=\"https://stackoverflow.com/questions/225362/convert-a-number-to-a-string-with-specified-length-in-c#226719\"><a href=\"https://stackoverflow.com/questions/225362/convert-a-number-to-a-string-with-specified-length-in-c#226719\">Convert a number to a string with specified length in C++</a></a> </p>\n" }, { "answer_id": 228827, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "<h2>Archeology</h2>\n<p>itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html\" rel=\"noreferrer\">http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html</a></p>\n<h2>The C Way</h2>\n<p>Use sprintf. Or snprintf. Or whatever tool you find.</p>\n<p>Despite the fact some functions are not in the standard, as rightly mentioned by &quot;onebyone&quot; in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).</p>\n<h2>The C++ way.</h2>\n<p>Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).</p>\n<h2>Conclusion</h2>\n<p>You're in C++, which means that you can choose the way you want it:</p>\n<ul>\n<li><p>The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.</p>\n</li>\n<li><p>The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it &quot;cool&quot; to use the faster way without really needing it).</p>\n</li>\n</ul>\n" }, { "answer_id": 230663, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 0, "selected": false, "text": "<p>On Windows CE derived platforms, there are no <code>iostream</code>s by default. The way to go there is preferaby with the <code>_itoa&lt;&gt;</code> family, usually <code>_itow&lt;&gt;</code> (since most string stuff are Unicode there anyway).</p>\n" }, { "answer_id": 900075, "author": "dcw", "author_id": 73491, "author_profile": "https://Stackoverflow.com/users/73491", "pm_score": 3, "selected": false, "text": "<p>Try <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost.Format</a> or <a href=\"http://www.fastformat.org/\" rel=\"noreferrer\">FastFormat</a>, both high-quality C++ libraries:</p>\n\n<pre><code>int i = 10;\nstd::string result;\n</code></pre>\n\n<p>WIth Boost.Format</p>\n\n<pre><code>result = str(boost::format(\"%1%\", i));\n</code></pre>\n\n<p>or FastFormat</p>\n\n<pre><code>fastformat::fmt(result, \"{0}\", i);\nfastformat::write(result, i);\n</code></pre>\n\n<p>Obviously they both do a lot more than a simple conversion of a single integer</p>\n" }, { "answer_id": 2768637, "author": "Mark Renslow", "author_id": 332781, "author_profile": "https://Stackoverflow.com/users/332781", "pm_score": 3, "selected": false, "text": "<p>You can actually convert anything to a string with one cleverly written template function. This code example uses a loop to create subdirectories in a Win-32 system. The string concatenation operator, operator+, is used to concatenate a root with a suffix to generate directory names. The suffix is created by converting the loop control variable, i, to a C++ string, using the template function, and concatenating that with another string.</p>\n\n<pre><code>//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College\n//C++ instructor and Network Dean of Information Technology\n\n#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt; // string stream\n#include &lt;direct.h&gt;\n\nusing namespace std;\n\nstring intToString(int x)\n{\n/**************************************/\n/* This function is similar to itoa() */\n/* \"integer to alpha\", a non-standard */\n/* C language function. It takes an */\n/* integer as input and as output, */\n/* returns a C++ string. */\n/* itoa() returned a C-string (null- */\n/* terminated) */\n/* This function is not needed because*/\n/* the following template function */\n/* does it all */\n/**************************************/ \n string r;\n stringstream s;\n\n s &lt;&lt; x;\n r = s.str();\n\n return r;\n\n}\n\ntemplate &lt;class T&gt;\nstring toString( T argument)\n{\n/**************************************/\n/* This template shows the power of */\n/* C++ templates. This function will */\n/* convert anything to a string! */\n/* Precondition: */\n/* operator&lt;&lt; is defined for type T */\n/**************************************/\n string r;\n stringstream s;\n\n s &lt;&lt; argument;\n r = s.str();\n\n return r;\n\n}\n\nint main( )\n{\n string s;\n\n cout &lt;&lt; \"What directory would you like me to make?\";\n\n cin &gt;&gt; s;\n\n try\n {\n mkdir(s.c_str());\n }\n catch (exception&amp; e) \n {\n cerr &lt;&lt; e.what( ) &lt;&lt; endl;\n }\n\n chdir(s.c_str());\n\n //Using a loop and string concatenation to make several sub-directories\n for(int i = 0; i &lt; 10; i++)\n {\n s = \"Dir_\";\n s = s + toString(i);\n mkdir(s.c_str());\n }\n system(\"PAUSE\");\n return EXIT_SUCCESS;\n}\n</code></pre>\n" }, { "answer_id": 6494263, "author": "Kendra", "author_id": 817552, "author_profile": "https://Stackoverflow.com/users/817552", "pm_score": 2, "selected": false, "text": "<pre><code>int number = 123;\n\nstringstream = s;\n\ns &lt;&lt; number;\n\ncout &lt;&lt; ss.str() &lt;&lt; endl;\n</code></pre>\n" }, { "answer_id": 7223104, "author": "jm1234567890", "author_id": 283271, "author_profile": "https://Stackoverflow.com/users/283271", "pm_score": 3, "selected": false, "text": "<p>I use these templates</p>\n\n<pre><code>template &lt;typename T&gt; string toStr(T tmp)\n{\n ostringstream out;\n out &lt;&lt; tmp;\n return out.str();\n}\n\n\ntemplate &lt;typename T&gt; T strTo(string tmp)\n{\n T output;\n istringstream in(tmp);\n in &gt;&gt; output;\n return output;\n}\n</code></pre>\n" }, { "answer_id": 10642026, "author": "Vasaka", "author_id": 672985, "author_profile": "https://Stackoverflow.com/users/672985", "pm_score": 4, "selected": false, "text": "<p>С++11 finally resolves this providing <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"nofollow\"><code>std::to_string</code></a>.\nAlso <code>boost::lexical_cast</code> is handy tool for older compilers.</p>\n" }, { "answer_id": 13203143, "author": "Tag318", "author_id": 1795447, "author_profile": "https://Stackoverflow.com/users/1795447", "pm_score": 4, "selected": false, "text": "<p>We can define our own <code>iota</code> function in c++ as:</p>\n\n<pre><code>string itoa(int a)\n{\n string ss=\"\"; //create empty string\n while(a)\n {\n int x=a%10;\n a/=10;\n char i='0';\n i=i+x;\n ss=i+ss; //append new character at the front of the string!\n }\n return ss;\n}\n</code></pre>\n\n<p>Don't forget to <code>#include &lt;string&gt;</code>.</p>\n" }, { "answer_id": 23371483, "author": "vitaut", "author_id": 471164, "author_profile": "https://Stackoverflow.com/users/471164", "pm_score": 2, "selected": false, "text": "<p>If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the <code>format_int</code> method from the <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">{fmt}</a> library:</p>\n\n<pre><code>fmt::format_int(42).str(); // convert to std::string\nfmt::format_int(42).c_str(); // convert and get as a C string\n // (mind the lifetime, same as std::string::c_str())\n</code></pre>\n\n<p>According to the <a href=\"http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html\" rel=\"nofollow noreferrer\">integer to string conversion benchmarks</a> from Boost Karma, this method several times faster than glibc's <code>sprintf</code> or <code>std::stringstream</code>. It is even faster than Boost Karma's own <code>int_generator</code> as was confirm by an <a href=\"https://github.com/ruslo/int-dec-format-tests/blob/545dcc6e2e558bc6146c368ef4265351fedd528a/results/macosx-clang-intel-core-i5-2.3GHz.txt\" rel=\"nofollow noreferrer\">independent benchmark</a>.</p>\n\n<p>Disclaimer: I'm the author of this library.</p>\n" }, { "answer_id": 24505125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I wrote this <strong>thread-safe</strong> function some time ago, and am very happy with the results and feel the algorithm is lightweight and lean, with performance that is about 3X the standard MSVC _itoa() function. </p>\n\n<p>Here's the link. <a href=\"https://stackoverflow.com/questions/21501815/optimal-base-10-only-itoa-function\">Optimal Base-10 only itoa() function?</a> Performance is at least 10X that of sprintf(). The benchmark is also the function's QA test, as follows. </p>\n\n<pre><code>start = clock();\nfor (int i = LONG_MIN; i &lt; LONG_MAX; i++) {\n if (i != atoi(_i32toa(buff, (int32_t)i))) {\n printf(\"\\nError for %i\", i);\n }\n if (!i) printf(\"\\nAt zero\");\n}\nprintf(\"\\nElapsed time was %f milliseconds\", (double)clock() - (double)(start));\n</code></pre>\n\n<p>There are some silly suggestions made about using the caller's storage that would leave the result floating somewhere in a buffer in the caller's address space. Ignore them. The code I listed works perfectly, as the benchmark/QA code demonstrates. </p>\n\n<p>I believe this code is lean enough to use in an embedded environment. YMMV, of course.</p>\n" }, { "answer_id": 24619502, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 2, "selected": false, "text": "<p>The best answer, IMO, is the function provided here:</p>\n\n<p><a href=\"http://www.jb.man.ac.uk/~slowe/cpp/itoa.html\" rel=\"nofollow\">http://www.jb.man.ac.uk/~slowe/cpp/itoa.html</a></p>\n\n<p>It mimics the non-ANSI function provided by many libs.</p>\n\n<pre><code>char* itoa(int value, char* result, int base);\n</code></pre>\n\n<p>It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
I was wondering if there was an alternative to `itoa()` for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use [`std::to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string): ``` #include <string> std::string s = std::to_string(5); ``` If you're working with prior to C++11, you could use C++ streams: ``` #include <sstream> int i = 5; std::string s; std::stringstream out; out << i; s = out.str(); ``` Taken from <http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/>
228,025
<p>How do you insert/update a column through Linq To SQL and Linq To SQL use the default values? In particular I'm concerned with a timestamp field.</p> <p>I've tried setting that column to readonly and autogenerated, so it stopped trying to put in DateTime.MinValue, but it doesn't seem to be updating on updates.</p>
[ { "answer_id": 228080, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "<p>The database default value would only insert the value on creating the row. It would do nothing for update, unless you want to add a triggger.</p>\n\n<p>Alternately, you can add a partial method to your DataContext class. Add a new file you your project:</p>\n\n<pre><code>public partial class YourDatabaseDataContext\n{\n partial void InsertYourTable(YourTable instance)\n {\n instance.LastUpdateTime = DateTime.Now;\n\n this.ExecuteDynamicInsert(instance);\n }\n\n partial void UpdateYourTable(YourTable instance)\n {\n instance.LastUpdateTime = DateTime.Now;\n\n this.ExecuteDynamicUpdate(instance);\n }\n</code></pre>\n" }, { "answer_id": 228093, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>You need to set IsVersion=true for a timestamp column. See the reference for <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute_properties.aspx\" rel=\"noreferrer\">ColumnAttribute</a>.</p>\n\n<p>In the DBML designer for my timestamp columns the properties are set to</p>\n\n<pre><code>AutoGenerated=true\nAutoSync=Always\nNullable, Primary Key, and ReadOnly = false\nSQLDataType = rowversion not null\nTimestamp = true\nUpdateCheck = never\n</code></pre>\n\n<p>I'm assuming that you really mean timestamp and not datetime. If the latter, ignore this.</p>\n" }, { "answer_id": 229326, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": false, "text": "<p>Seems like you just forgot to set <strong>AutoSync</strong> to <strong>always</strong> for the property.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050/" ]
How do you insert/update a column through Linq To SQL and Linq To SQL use the default values? In particular I'm concerned with a timestamp field. I've tried setting that column to readonly and autogenerated, so it stopped trying to put in DateTime.MinValue, but it doesn't seem to be updating on updates.
The database default value would only insert the value on creating the row. It would do nothing for update, unless you want to add a triggger. Alternately, you can add a partial method to your DataContext class. Add a new file you your project: ``` public partial class YourDatabaseDataContext { partial void InsertYourTable(YourTable instance) { instance.LastUpdateTime = DateTime.Now; this.ExecuteDynamicInsert(instance); } partial void UpdateYourTable(YourTable instance) { instance.LastUpdateTime = DateTime.Now; this.ExecuteDynamicUpdate(instance); } ```
228,036
<p>I have the following problem using template instantiation [*]. </p> <p>file <strong>foo.h</strong></p> <pre><code>class Foo { public: template &lt;typename F&gt; void func(F f) private: int member_; }; </code></pre> <p>file <strong>foo.cc</strong></p> <pre><code>template &lt;typename F&gt; Foo::func(F f) { f(member_); } </code></pre> <p>file <strong>caller.cc</strong></p> <pre><code>Foo::func(boost::bind(&amp;Bar::bar_func, bar_instance, _1)); </code></pre> <p>While this compiles fine, the linker complains about an undefined symbol:</p> <p><code>void Foo::func&lt;boost::_bi::bind_t...&gt;</code></p> <p>How can I instantiate the <em>function</em> <code>Foo::func</code>? Since it takes a function as argument, I am little bit confused. I tried to add an instantiation function in <strong>foo.cc</strong>, as I am used to with regular <em>non-function</em> types:</p> <pre><code>instantiate() { template&lt;&gt; void Foo::func&lt;boost::function&lt;void(int)&gt; &gt;(boost::function&lt;void(int)&gt;); } </code></pre> <p>Obviously, this does not work. I would appreciate if someone can point me in the right direction.</p> <p>Thanks!</p> <p>[*] Yes, I read the parashift FAQ lite.</p>
[ { "answer_id": 228048, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>Are you including foo.cc into caller.cc. Instantiation is something that happens at compile time -- when the compiler sees the call in caller it makes instantiated versions of the templates but needs to have the full definition available.</p>\n" }, { "answer_id": 228065, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 4, "selected": true, "text": "<p>The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. </p>\n\n<p>If you're using Visual C++, and any other compiler that can't do this, you may as well put the function definition in the header.</p>\n\n<p>Don't worry about duplicate definitions if the header is included by multiple .cc files. The compiler marks template-generated methods with a special attribute so the linker knows to throw away duplicates instead of complaining. This is one reason why C++ has the \"one definition rule\".</p>\n\n<p><strong>Edit:</strong> The above comments apply in the general case where your template must be capable of linking given any type parameters. If you know a closed set of types that clients will use, you can ensure they are available by using explicit instantiation in the template's implementation file, which will cause the compiler to generate definitions for other files to link against. But in the general case where your template needs to work with types possibly only known to the client, then there is little point in separating the template into a header file and and implementation file; any client needs to include both parts anyway. If you want to isolate clients from complex dependencies, hide those dependencies behind non-templated functions and then call into them from the template code.</p>\n" }, { "answer_id": 228370, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 1, "selected": false, "text": "<p>I think what they're both referring to is that template function definitions (not just declarations) have to be included in the file where they're used. Template functions don't actually exist unless/until they're used; if you put them in a separate cc file, then the compiler doesn't know about them in the other cc files, unless you explicitly <code>#include</code> that cc file into either the header file or the file that's calling them, due to the way the parser works.</p>\n\n<p>(That's why template function definitions are generally kept in the header files, as Earwicker described.)</p>\n\n<p>Any clearer?</p>\n" }, { "answer_id": 228372, "author": "SCFrench", "author_id": 4928, "author_profile": "https://Stackoverflow.com/users/4928", "pm_score": 0, "selected": false, "text": "<p>I believe Earwicker is correct. The problem with explicitly instantiating the template member function func in this case is that the type returned by boost::bind is implementation dependent. It is <em>not</em> a boost::function. A boost::function can <em>contain</em> a boost:bind because it has a template assignment operator that deduces the type of the right-hand side (the boost::bind result). In this particular use of func in caller.cc, with this particular implementation of boost, the type of the boost::bind is actually they type mentioned in the linker error between the &lt; and > (ie. <code>boost::_bi::bind_t...</code>). But explicitly instantiating func for that type probably will have portability problems.</p>\n" }, { "answer_id": 228581, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>Splitting it into files Like you want:<br>\nNot that I recommend this. Just showing that it is possible.</p>\n\n<p>plop.h</p>\n\n<pre><code>#include &lt;iostream&gt;\nclass Foo\n{\npublic:\n Foo(): member_(15){}\n\n\n // Note No definition of this in a header file.\n // It is defined in plop.cpp and a single instantiation forced\n // Without actually using it.\n template &lt;typename F&gt;\n void func(F f);\n\nprivate:\n int member_;\n};\n\n\nstruct Bar\n{\n void bar_func(int val) { std::cout &lt;&lt; val &lt;&lt; \"\\n\"; }\n};\n\nstruct Tar\n{\n void tar_func(int val) { std::cout &lt;&lt; \"This should not print because of specialisation of func\\n\";}\n};\n</code></pre>\n\n<p>Plop.cpp</p>\n\n<pre><code>#include \"plop.h\"\n#include &lt;boost/bind.hpp&gt;\n#include &lt;iostream&gt;\n\ntemplate &lt;typename F&gt;\nvoid Foo::func(F f)\n{\n f(member_);\n}\n\n// Gnarly typedef\ntypedef boost::_bi::bind_t&lt;void, boost::_mfi::mf1&lt;void, Bar, int&gt;, boost::_bi::list2&lt;boost::_bi::value&lt;Bar&gt;, boost::arg&lt;1&gt; (*)()&gt; &gt; myFunc;\n\n// Force the compiler to generate an instantiation of Foo::func()\ntemplate void Foo::func&lt;myFunc&gt;(myFunc f);\n\n// Note this is not a specialization as that requires the &lt;&gt; after template.\n// See main.cpp for an example of specialization.\n</code></pre>\n\n<p>main.cpp</p>\n\n<pre><code>#include \"plop.h\"\n#include &lt;boost/bind.hpp&gt;\n#include &lt;iostream&gt;\n\n// Gnarly typedef\ntypedef boost::_bi::bind_t&lt;void, boost::_mfi::mf1&lt;void, Tar, int&gt;, boost::_bi::list2&lt;boost::_bi::value&lt;Tar&gt;, boost::arg&lt;1&gt; (*)()&gt; &gt; myTar;\n\n// Specialization of Foo::func()\ntemplate&lt;&gt; void Foo::func&lt;myTar&gt;(myTar f)\n{\n std::cout &lt;&lt; \"Special\\n\";\n}\n// Note. This is not instantiated unless it is used.\n// But because it is used in main() we get a version.\n\nint main(int argc,char* argv[])\n{\n Foo f;\n Bar b;\n Tar t;\n\n f.func(boost::bind(&amp;Bar::bar_func, b, _1)); // Uses instantiation from plop.cpp\n f.func(boost::bind(&amp;Tar::tar_func, t, _1)); // Uses local specialization\n}\n</code></pre>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1170277/" ]
I have the following problem using template instantiation [\*]. file **foo.h** ``` class Foo { public: template <typename F> void func(F f) private: int member_; }; ``` file **foo.cc** ``` template <typename F> Foo::func(F f) { f(member_); } ``` file **caller.cc** ``` Foo::func(boost::bind(&Bar::bar_func, bar_instance, _1)); ``` While this compiles fine, the linker complains about an undefined symbol: `void Foo::func<boost::_bi::bind_t...>` How can I instantiate the *function* `Foo::func`? Since it takes a function as argument, I am little bit confused. I tried to add an instantiation function in **foo.cc**, as I am used to with regular *non-function* types: ``` instantiate() { template<> void Foo::func<boost::function<void(int)> >(boost::function<void(int)>); } ``` Obviously, this does not work. I would appreciate if someone can point me in the right direction. Thanks! [\*] Yes, I read the parashift FAQ lite.
The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. If you're using Visual C++, and any other compiler that can't do this, you may as well put the function definition in the header. Don't worry about duplicate definitions if the header is included by multiple .cc files. The compiler marks template-generated methods with a special attribute so the linker knows to throw away duplicates instead of complaining. This is one reason why C++ has the "one definition rule". **Edit:** The above comments apply in the general case where your template must be capable of linking given any type parameters. If you know a closed set of types that clients will use, you can ensure they are available by using explicit instantiation in the template's implementation file, which will cause the compiler to generate definitions for other files to link against. But in the general case where your template needs to work with types possibly only known to the client, then there is little point in separating the template into a header file and and implementation file; any client needs to include both parts anyway. If you want to isolate clients from complex dependencies, hide those dependencies behind non-templated functions and then call into them from the template code.
228,038
<p>I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:</p> <pre><code>public string Reverse(string text) { char[] cArray = text.ToCharArray(); string reverse = String.Empty; for (int i = cArray.Length - 1; i &gt; -1; i--) { reverse += cArray[i]; } return reverse; } </code></pre> <p>Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?</p>
[ { "answer_id": 228055, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 4, "selected": false, "text": "<p>Have a look at the wikipedia entry <a href=\"http://en.wikipedia.org/wiki/Extension_method\" rel=\"noreferrer\">here</a>. They implement the String.Reverse extension method. This allows you to write code like this:</p>\n\n<pre><code>string s = \"olleh\";\ns.Reverse();\n</code></pre>\n\n<p>They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:</p>\n\n<pre><code>public static string Reverse(this string input)\n{\n char[] chars = input.ToCharArray();\n Array.Reverse(chars);\n return new String(chars);\n}\n</code></pre>\n" }, { "answer_id": 228056, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": false, "text": "<p>Firstly you don't need to call <code>ToCharArray</code> as a string can already be indexed as a char array, so this will save you an allocation.</p>\n\n<p>The next optimisation is to use a <code>StringBuilder</code> to prevent unnecessary allocations (as strings are immutable, concatenating them makes a copy of the string each time). To further optimise this we pre-set the length of the <code>StringBuilder</code> so it won't need to expand its buffer.</p>\n\n<pre><code>public string Reverse(string text)\n{\n if (string.IsNullOrEmpty(text))\n {\n return text;\n }\n\n StringBuilder builder = new StringBuilder(text.Length);\n for (int i = text.Length - 1; i &gt;= 0; i--)\n {\n builder.Append(text[i]);\n }\n\n return builder.ToString();\n}\n</code></pre>\n\n<p><strong>Edit: Performance Data</strong></p>\n\n<p>I tested this function and the function using <code>Array.Reverse</code> with the following simple program, where <code>Reverse1</code> is one function and <code>Reverse2</code> is the other:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var text = \"abcdefghijklmnopqrstuvwxyz\";\n\n // pre-jit\n text = Reverse1(text); \n text = Reverse2(text);\n\n // test\n var timer1 = Stopwatch.StartNew();\n for (var i = 0; i &lt; 10000000; i++)\n {\n text = Reverse1(text);\n }\n\n timer1.Stop();\n Console.WriteLine(\"First: {0}\", timer1.ElapsedMilliseconds);\n\n var timer2 = Stopwatch.StartNew();\n for (var i = 0; i &lt; 10000000; i++)\n {\n text = Reverse2(text);\n }\n\n timer2.Stop();\n Console.WriteLine(\"Second: {0}\", timer2.ElapsedMilliseconds);\n\n Console.ReadLine();\n}\n</code></pre>\n\n<p>It turns out that for short strings the <code>Array.Reverse</code> method is around twice as quick as the one above, and for longer strings the difference is even more pronounced. So given that the <code>Array.Reverse</code> method is both simpler and faster I'd recommend you use that rather than this one. I leave this one up here just to show that it isn't the way you should do it (much to my surprise!)</p>\n" }, { "answer_id": 228060, "author": "PeteT", "author_id": 16989, "author_profile": "https://Stackoverflow.com/users/16989", "pm_score": 11, "selected": true, "text": "<pre><code>public static string Reverse( string s )\n{\n char[] charArray = s.ToCharArray();\n Array.Reverse(charArray);\n return new string(charArray);\n}\n</code></pre>\n" }, { "answer_id": 228062, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 7, "selected": false, "text": "<p>This is turning out to be a surprisingly tricky question. </p>\n\n<p>I would recommend using Array.Reverse for most cases as it is coded natively and it is very simple to maintain and understand. </p>\n\n<p>It seems to outperform StringBuilder in all the cases I tested. </p>\n\n<pre><code>public string Reverse(string text)\n{\n if (text == null) return null;\n\n // this was posted by petebob as well \n char[] array = text.ToCharArray();\n Array.Reverse(array);\n return new String(array);\n}\n</code></pre>\n\n<p>There is a second approach that can be faster for certain string lengths which <a href=\"http://www.sqljunkies.com/WebLog/amachanic/archive/2006/07/17/22253.aspx\" rel=\"noreferrer\">uses Xor</a>. </p>\n\n<pre><code> public static string ReverseXor(string s)\n {\n if (s == null) return null;\n char[] charArray = s.ToCharArray();\n int len = s.Length - 1;\n\n for (int i = 0; i &lt; len; i++, len--)\n {\n charArray[i] ^= charArray[len];\n charArray[len] ^= charArray[i];\n charArray[i] ^= charArray[len];\n }\n\n return new string(charArray);\n }\n</code></pre>\n\n<p><strong>Note</strong> If you want to support the full Unicode UTF16 charset <a href=\"https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string-in-c-20#228460\">read this</a>. And use the implementation there instead. It can be further optimized by using one of the above algorithms and running through the string to clean it up after the chars are reversed.</p>\n\n<p>Here is a performance comparison between the StringBuilder, Array.Reverse and Xor method. </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\n\nnamespace ConsoleApplication4\n{\n class Program\n {\n delegate string StringDelegate(string s);\n\n static void Benchmark(string description, StringDelegate d, int times, string text)\n {\n Stopwatch sw = new Stopwatch();\n sw.Start();\n for (int j = 0; j &lt; times; j++)\n {\n d(text);\n }\n sw.Stop();\n Console.WriteLine(\"{0} Ticks {1} : called {2} times.\", sw.ElapsedTicks, description, times);\n }\n\n public static string ReverseXor(string s)\n {\n char[] charArray = s.ToCharArray();\n int len = s.Length - 1;\n\n for (int i = 0; i &lt; len; i++, len--)\n {\n charArray[i] ^= charArray[len];\n charArray[len] ^= charArray[i];\n charArray[i] ^= charArray[len];\n }\n\n return new string(charArray);\n }\n\n public static string ReverseSB(string text)\n {\n StringBuilder builder = new StringBuilder(text.Length);\n for (int i = text.Length - 1; i &gt;= 0; i--)\n {\n builder.Append(text[i]);\n }\n return builder.ToString();\n }\n\n public static string ReverseArray(string text)\n {\n char[] array = text.ToCharArray();\n Array.Reverse(array);\n return (new string(array));\n }\n\n public static string StringOfLength(int length)\n {\n Random random = new Random();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; length; i++)\n {\n sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));\n }\n return sb.ToString();\n }\n\n static void Main(string[] args)\n {\n\n int[] lengths = new int[] {1,10,15,25,50,75,100,1000,100000};\n\n foreach (int l in lengths)\n {\n int iterations = 10000;\n string text = StringOfLength(l);\n Benchmark(String.Format(\"String Builder (Length: {0})\", l), ReverseSB, iterations, text);\n Benchmark(String.Format(\"Array.Reverse (Length: {0})\", l), ReverseArray, iterations, text);\n Benchmark(String.Format(\"Xor (Length: {0})\", l), ReverseXor, iterations, text);\n\n Console.WriteLine(); \n }\n\n Console.Read();\n }\n }\n}\n</code></pre>\n\n<p>Here are the results: </p>\n\n<pre><code>26251 Ticks String Builder (Length: 1) : called 10000 times.\n33373 Ticks Array.Reverse (Length: 1) : called 10000 times.\n20162 Ticks Xor (Length: 1) : called 10000 times.\n\n51321 Ticks String Builder (Length: 10) : called 10000 times.\n37105 Ticks Array.Reverse (Length: 10) : called 10000 times.\n23974 Ticks Xor (Length: 10) : called 10000 times.\n\n66570 Ticks String Builder (Length: 15) : called 10000 times.\n26027 Ticks Array.Reverse (Length: 15) : called 10000 times.\n24017 Ticks Xor (Length: 15) : called 10000 times.\n\n101609 Ticks String Builder (Length: 25) : called 10000 times.\n28472 Ticks Array.Reverse (Length: 25) : called 10000 times.\n35355 Ticks Xor (Length: 25) : called 10000 times.\n\n161601 Ticks String Builder (Length: 50) : called 10000 times.\n35839 Ticks Array.Reverse (Length: 50) : called 10000 times.\n51185 Ticks Xor (Length: 50) : called 10000 times.\n\n230898 Ticks String Builder (Length: 75) : called 10000 times.\n40628 Ticks Array.Reverse (Length: 75) : called 10000 times.\n78906 Ticks Xor (Length: 75) : called 10000 times.\n\n312017 Ticks String Builder (Length: 100) : called 10000 times.\n52225 Ticks Array.Reverse (Length: 100) : called 10000 times.\n110195 Ticks Xor (Length: 100) : called 10000 times.\n\n2970691 Ticks String Builder (Length: 1000) : called 10000 times.\n292094 Ticks Array.Reverse (Length: 1000) : called 10000 times.\n846585 Ticks Xor (Length: 1000) : called 10000 times.\n\n305564115 Ticks String Builder (Length: 100000) : called 10000 times.\n74884495 Ticks Array.Reverse (Length: 100000) : called 10000 times.\n125409674 Ticks Xor (Length: 100000) : called 10000 times.\n</code></pre>\n\n<p>It seems that Xor can be faster for short strings. </p>\n" }, { "answer_id": 228063, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 2, "selected": false, "text": "<p>\"Better way\" depends on what is more important to you in your situation, performance, elegance, maintainability etc.</p>\n\n<p>Anyway, here's an approach using Array.Reverse:</p>\n\n<pre><code>string inputString=\"The quick brown fox jumps over the lazy dog.\";\nchar[] charArray = inputString.ToCharArray(); \nArray.Reverse(charArray); \n\nstring reversed = new string(charArray);\n</code></pre>\n" }, { "answer_id": 228084, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 4, "selected": false, "text": "<p>Try using Array.Reverse</p>\n\n<pre><code>\npublic string Reverse(string str)\n{\n char[] array = str.ToCharArray();\n Array.Reverse(array);\n return new string(array);\n}\n</code></pre>\n" }, { "answer_id": 228094, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 2, "selected": false, "text": "<p>Had to submit a recursive example:</p>\n\n<pre><code>private static string Reverse(string str)\n{\n if (str.IsNullOrEmpty(str) || str.Length == 1)\n return str;\n else\n return str[str.Length - 1] + Reverse(str.Substring(0, str.Length - 1));\n}\n</code></pre>\n" }, { "answer_id": 228166, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Sorry for long post, but this might be interesting</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n public static string ReverseUsingArrayClass(string text)\n {\n char[] chars = text.ToCharArray();\n Array.Reverse(chars);\n return new string(chars);\n }\n\n public static string ReverseUsingCharacterBuffer(string text)\n {\n char[] charArray = new char[text.Length];\n int inputStrLength = text.Length - 1;\n for (int idx = 0; idx &lt;= inputStrLength; idx++) \n {\n charArray[idx] = text[inputStrLength - idx]; \n }\n return new string(charArray);\n }\n\n public static string ReverseUsingStringBuilder(string text)\n {\n if (string.IsNullOrEmpty(text))\n {\n return text;\n }\n\n StringBuilder builder = new StringBuilder(text.Length);\n for (int i = text.Length - 1; i &gt;= 0; i--)\n {\n builder.Append(text[i]);\n }\n\n return builder.ToString();\n }\n\n private static string ReverseUsingStack(string input)\n {\n Stack&lt;char&gt; resultStack = new Stack&lt;char&gt;();\n foreach (char c in input)\n {\n resultStack.Push(c);\n }\n\n StringBuilder sb = new StringBuilder();\n while (resultStack.Count &gt; 0)\n {\n sb.Append(resultStack.Pop());\n }\n return sb.ToString();\n }\n\n public static string ReverseUsingXOR(string text)\n {\n char[] charArray = text.ToCharArray();\n int length = text.Length - 1;\n for (int i = 0; i &lt; length; i++, length--)\n {\n charArray[i] ^= charArray[length];\n charArray[length] ^= charArray[i];\n charArray[i] ^= charArray[length];\n }\n\n return new string(charArray);\n }\n\n\n static void Main(string[] args)\n {\n string testString = string.Join(\";\", new string[] {\n new string('a', 100), \n new string('b', 101), \n new string('c', 102), \n new string('d', 103), \n });\n int cycleCount = 100000;\n\n Stopwatch stopwatch = new Stopwatch();\n stopwatch.Start();\n for (int i = 0; i &lt; cycleCount; i++) \n {\n ReverseUsingCharacterBuffer(testString);\n }\n stopwatch.Stop();\n Console.WriteLine(\"ReverseUsingCharacterBuffer: \" + stopwatch.ElapsedMilliseconds + \"ms\");\n\n stopwatch.Reset();\n stopwatch.Start();\n for (int i = 0; i &lt; cycleCount; i++) \n {\n ReverseUsingArrayClass(testString);\n }\n stopwatch.Stop();\n Console.WriteLine(\"ReverseUsingArrayClass: \" + stopwatch.ElapsedMilliseconds + \"ms\");\n\n stopwatch.Reset();\n stopwatch.Start();\n for (int i = 0; i &lt; cycleCount; i++) \n {\n ReverseUsingStringBuilder(testString);\n }\n stopwatch.Stop();\n Console.WriteLine(\"ReverseUsingStringBuilder: \" + stopwatch.ElapsedMilliseconds + \"ms\");\n\n stopwatch.Reset();\n stopwatch.Start();\n for (int i = 0; i &lt; cycleCount; i++) \n {\n ReverseUsingStack(testString);\n }\n stopwatch.Stop();\n Console.WriteLine(\"ReverseUsingStack: \" + stopwatch.ElapsedMilliseconds + \"ms\");\n\n stopwatch.Reset();\n stopwatch.Start();\n for (int i = 0; i &lt; cycleCount; i++) \n {\n ReverseUsingXOR(testString);\n }\n stopwatch.Stop();\n Console.WriteLine(\"ReverseUsingXOR: \" + stopwatch.ElapsedMilliseconds + \"ms\"); \n }\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<ul>\n<li>ReverseUsingCharacterBuffer: 346ms </li>\n<li>ReverseUsingArrayClass: 87ms</li>\n<li>ReverseUsingStringBuilder: 824ms</li>\n<li>ReverseUsingStack: 2086ms</li>\n<li>ReverseUsingXOR: 319ms</li>\n</ul>\n" }, { "answer_id": 228376, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": false, "text": "<p>If you want to play a really dangerous game, then this is by far the fastest way there is (around four times faster than the <code>Array.Reverse</code> method). It's an in-place reverse using pointers.</p>\n\n<p>Note that I really do not recommend this for any use, ever (<a href=\"https://stackoverflow.com/questions/229346/why-should-i-never-use-an-unsafe-block-to-modify-a-string\">have a look here for some reasons why you should not use this method</a>), but it's just interesting to see that it can be done, and that strings aren't really immutable once you turn on unsafe code.</p>\n\n<pre><code>public static unsafe string Reverse(string text)\n{\n if (string.IsNullOrEmpty(text))\n {\n return text;\n }\n\n fixed (char* pText = text)\n {\n char* pStart = pText;\n char* pEnd = pText + text.Length - 1;\n for (int i = text.Length / 2; i &gt;= 0; i--)\n {\n char temp = *pStart;\n *pStart++ = *pEnd;\n *pEnd-- = temp;\n }\n\n return text;\n }\n}\n</code></pre>\n" }, { "answer_id": 228460, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 6, "selected": false, "text": "<p>If the string contains Unicode data (strictly speaking, non-BMP characters) the other methods that have been posted will corrupt it, because you cannot swap the order of high and low surrogate code units when reversing the string. (More information about this can be found on <a href=\"http://code.logos.com/blog/2008/10/how_to_reverse_a_unicode_string_in_c.html\" rel=\"noreferrer\">my blog</a>.)</p>\n\n<p>The following code sample will correctly reverse a string that contains non-BMP characters, e.g., \"\\U00010380\\U00010381\" (Ugaritic Letter Alpa, Ugaritic Letter Beta).</p>\n\n<pre><code>public static string Reverse(this string input)\n{\n if (input == null)\n throw new ArgumentNullException(\"input\");\n\n // allocate a buffer to hold the output\n char[] output = new char[input.Length];\n for (int outputIndex = 0, inputIndex = input.Length - 1; outputIndex &lt; input.Length; outputIndex++, inputIndex--)\n {\n // check for surrogate pair\n if (input[inputIndex] &gt;= 0xDC00 &amp;&amp; input[inputIndex] &lt;= 0xDFFF &amp;&amp;\n inputIndex &gt; 0 &amp;&amp; input[inputIndex - 1] &gt;= 0xD800 &amp;&amp; input[inputIndex - 1] &lt;= 0xDBFF)\n {\n // preserve the order of the surrogate pair code units\n output[outputIndex + 1] = input[inputIndex];\n output[outputIndex] = input[inputIndex - 1];\n outputIndex++;\n inputIndex--;\n }\n else\n {\n output[outputIndex] = input[inputIndex];\n }\n }\n\n return new string(output);\n}\n</code></pre>\n" }, { "answer_id": 2439839, "author": "Saeed", "author_id": 293114, "author_profile": "https://Stackoverflow.com/users/293114", "pm_score": -1, "selected": false, "text": "<pre><code>public string rev(string str)\n{\n if (str.Length &lt;= 0)\n return string.Empty;\n else\n return str[str.Length-1]+ rev(str.Substring(0,str.Length-1));\n}\n</code></pre>\n" }, { "answer_id": 3047997, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 4, "selected": false, "text": "<p>Greg Beech posted an <code>unsafe</code> option that is indeed as fast as it gets (it's an in-place reversal); but, as he indicated in his answer, it's <strong><a href=\"http://philosopherdeveloper.com/posts/are-strings-really-immutable-in-net.html\" rel=\"noreferrer\">a completely disastrous idea</a></strong>.</p>\n\n<p>That said, I'm surprised there is so much of a consensus that <code>Array.Reverse</code> is the fastest method. There's still an <code>unsafe</code> approach that returns a reversed copy of a string (no in-place reversal shenanigans) <strong>significantly faster than the <code>Array.Reverse</code> method</strong> for small strings:</p>\n\n<pre><code>public static unsafe string Reverse(string text)\n{\n int len = text.Length;\n\n // Why allocate a char[] array on the heap when you won't use it\n // outside of this method? Use the stack.\n char* reversed = stackalloc char[len];\n\n // Avoid bounds-checking performance penalties.\n fixed (char* str = text)\n {\n int i = 0;\n int j = i + len - 1;\n while (i &lt; len)\n {\n reversed[i++] = str[j--];\n }\n }\n\n // Need to use this overload for the System.String constructor\n // as providing just the char* pointer could result in garbage\n // at the end of the string (no guarantee of null terminator).\n return new string(reversed, 0, len);\n}\n</code></pre>\n\n<p><a href=\"http://charter.herokuapp.com/MZ02Y32T/performance-of-selected-string-reversal-methods-lower-is-better\" rel=\"noreferrer\">Here are some benchmark results</a>.</p>\n\n<p></p>\n\n<p>You can see that the performance gain shrinks and then disappears against the <code>Array.Reverse</code> method as the strings get larger. For small- to medium-sized strings, though, it's tough to beat this method.</p>\n" }, { "answer_id": 4891003, "author": "Zamir", "author_id": 602149, "author_profile": "https://Stackoverflow.com/users/602149", "pm_score": 2, "selected": false, "text": "<p>How about:</p>\n\n<pre><code> private string Reverse(string stringToReverse)\n {\n char[] rev = stringToReverse.Reverse().ToArray();\n return new string(rev); \n }\n</code></pre>\n" }, { "answer_id": 8419391, "author": "richardtallent", "author_id": 16306, "author_profile": "https://Stackoverflow.com/users/16306", "pm_score": 5, "selected": false, "text": "<p>Ok, in the interest of \"don't repeat yourself,\" I offer the following solution:</p>\n\n<pre><code>public string Reverse(string text)\n{\n return Microsoft.VisualBasic.Strings.StrReverse(text);\n}\n</code></pre>\n\n<p>My understanding is that this implementation, available by default in VB.NET, properly handles Unicode characters.</p>\n" }, { "answer_id": 9307098, "author": "mike01010", "author_id": 480118, "author_profile": "https://Stackoverflow.com/users/480118", "pm_score": 2, "selected": false, "text": "<p>If it ever came up in an interview and you were told you can't use Array.Reverse, i think this might be one of the fastest. It does not create new strings and iterates only over half of the array (i.e O(n/2) iterations)</p>\n\n<pre><code> public static string ReverseString(string stringToReverse)\n {\n char[] charArray = stringToReverse.ToCharArray();\n int len = charArray.Length-1;\n int mid = len / 2;\n\n for (int i = 0; i &lt; mid; i++)\n {\n char tmp = charArray[i];\n charArray[i] = charArray[len - i];\n charArray[len - i] = tmp;\n }\n return new string(charArray);\n }\n</code></pre>\n" }, { "answer_id": 10345725, "author": "Shrini", "author_id": 1360399, "author_profile": "https://Stackoverflow.com/users/1360399", "pm_score": 1, "selected": false, "text": "<pre><code>public static string Reverse2(string x)\n {\n char[] charArray = new char[x.Length];\n int len = x.Length - 1;\n for (int i = 0; i &lt;= len; i++)\n charArray[i] = x[len - i];\n return new string(charArray);\n }\n</code></pre>\n" }, { "answer_id": 12328464, "author": "Marcel Valdez Orozco", "author_id": 697862, "author_profile": "https://Stackoverflow.com/users/697862", "pm_score": 3, "selected": false, "text": "<pre><code>public string Reverse(string input)\n{\n char[] output = new char[input.Length];\n\n int forwards = 0;\n int backwards = input.Length - 1;\n\n do\n {\n output[forwards] = input[backwards];\n output[backwards] = input[forwards];\n }while(++forwards &lt;= --backwards);\n\n return new String(output);\n}\n\npublic string DotNetReverse(string input)\n{\n char[] toReverse = input.ToCharArray();\n Array.Reverse(toReverse);\n return new String(toReverse);\n}\n\npublic string NaiveReverse(string input)\n{\n char[] outputArray = new char[input.Length];\n for (int i = 0; i &lt; input.Length; i++)\n {\n outputArray[i] = input[input.Length - 1 - i];\n }\n\n return new String(outputArray);\n} \n\npublic string RecursiveReverse(string input)\n{\n return RecursiveReverseHelper(input, 0, input.Length - 1);\n}\n\npublic string RecursiveReverseHelper(string input, int startIndex , int endIndex)\n{\n if (startIndex == endIndex)\n {\n return \"\" + input[startIndex];\n }\n\n if (endIndex - startIndex == 1)\n {\n return \"\" + input[endIndex] + input[startIndex];\n }\n\n return input[endIndex] + RecursiveReverseHelper(input, startIndex + 1, endIndex - 1) + input[startIndex];\n}\n\n\nvoid Main()\n{\n int[] sizes = new int[] { 10, 100, 1000, 10000 };\n for(int sizeIndex = 0; sizeIndex &lt; sizes.Length; sizeIndex++)\n {\n string holaMundo = \"\";\n for(int i = 0; i &lt; sizes[sizeIndex]; i+= 5)\n { \n holaMundo += \"ABCDE\";\n }\n\n string.Format(\"\\n**** For size: {0} ****\\n\", sizes[sizeIndex]).Dump();\n\n string odnuMaloh = DotNetReverse(holaMundo);\n\n var stopWatch = Stopwatch.StartNew();\n string result = NaiveReverse(holaMundo);\n (\"Naive Ticks: \" + stopWatch.ElapsedTicks).Dump();\n\n stopWatch.Restart();\n result = Reverse(holaMundo);\n (\"Efficient linear Ticks: \" + stopWatch.ElapsedTicks).Dump();\n\n stopWatch.Restart();\n result = RecursiveReverse(holaMundo);\n (\"Recursive Ticks: \" + stopWatch.ElapsedTicks).Dump();\n\n stopWatch.Restart();\n result = DotNetReverse(holaMundo);\n (\"DotNet Reverse Ticks: \" + stopWatch.ElapsedTicks).Dump();\n }\n}\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<p><strong>For size: 10</strong></p>\n\n<pre><code>Naive Ticks: 1\nEfficient linear Ticks: 0\nRecursive Ticks: 2\nDotNet Reverse Ticks: 1\n</code></pre>\n\n<p><strong>For size: 100</strong></p>\n\n<pre><code>Naive Ticks: 2\nEfficient linear Ticks: 1\nRecursive Ticks: 12\nDotNet Reverse Ticks: 1\n</code></pre>\n\n<p><strong>For size: 1000</strong></p>\n\n<pre><code>Naive Ticks: 5\nEfficient linear Ticks: 2\nRecursive Ticks: 358\nDotNet Reverse Ticks: 9\n</code></pre>\n\n<p><strong>For size: 10000</strong></p>\n\n<pre><code>Naive Ticks: 32\nEfficient linear Ticks: 28\nRecursive Ticks: 84808\nDotNet Reverse Ticks: 33\n</code></pre>\n" }, { "answer_id": 15006915, "author": "vikas", "author_id": 845912, "author_profile": "https://Stackoverflow.com/users/845912", "pm_score": 1, "selected": false, "text": "<pre><code>private static string Reverse(string str)\n {\n string revStr = string.Empty;\n for (int i = str.Length - 1; i &gt;= 0; i--)\n {\n revStr += str[i].ToString();\n }\n return revStr;\n }\n</code></pre>\n\n<p><strong>Faster than above method</strong></p>\n\n<pre><code>private static string ReverseEx(string str)\n {\n char[] chrArray = str.ToCharArray();\n int len = chrArray.Length - 1;\n char rev = 'n';\n for (int i = 0; i &lt;= len/2; i++)\n {\n rev = chrArray[i];\n chrArray[i] = chrArray[len - i];\n chrArray[len - i] = rev;\n }\n return new string(chrArray);\n }\n</code></pre>\n" }, { "answer_id": 15111719, "author": "R. Martinho Fernandes", "author_id": 46642, "author_profile": "https://Stackoverflow.com/users/46642", "pm_score": 8, "selected": false, "text": "<p>Here a solution that properly reverses the string <code>\"Les Mise\\u0301rables\"</code> as <code>\"selbare\\u0301siM seL\"</code>. This should render just like <code>selbarésiM seL</code>, not <code>selbaŕesiM seL</code> (note the position of the accent), as would the result of most implementations based on code units (<code>Array.Reverse</code>, etc) or even code points (reversing with special care for surrogate pairs).</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\n\npublic static class Test\n{\n private static IEnumerable&lt;string&gt; GraphemeClusters(this string s) {\n var enumerator = StringInfo.GetTextElementEnumerator(s);\n while(enumerator.MoveNext()) {\n yield return (string)enumerator.Current;\n }\n }\n private static string ReverseGraphemeClusters(this string s) {\n return string.Join(\"\", s.GraphemeClusters().Reverse().ToArray());\n }\n\n public static void Main()\n {\n var s = \"Les Mise\\u0301rables\";\n var r = s.ReverseGraphemeClusters();\n Console.WriteLine(r);\n }\n}\n</code></pre>\n\n<p>(And live running example here: <a href=\"https://ideone.com/DqAeMJ\">https://ideone.com/DqAeMJ</a>)</p>\n\n<p>It simply uses the .NET <a href=\"http://msdn.microsoft.com/en-us/library/x2f3k4f6.aspx\">API for grapheme cluster iteration</a>, which has been there since ever, but a bit \"hidden\" from view, it seems. </p>\n" }, { "answer_id": 15754309, "author": "B H", "author_id": 1539001, "author_profile": "https://Stackoverflow.com/users/1539001", "pm_score": 3, "selected": false, "text": "<p>Don't bother with a function, just do it in place. Note: The second line will throw an argument exception in the Immediate window of some VS versions.</p>\n\n<pre><code>string s = \"Blah\";\ns = new string(s.ToCharArray().Reverse().ToArray()); \n</code></pre>\n" }, { "answer_id": 15848573, "author": "SGRao", "author_id": 1571208, "author_profile": "https://Stackoverflow.com/users/1571208", "pm_score": 6, "selected": false, "text": "<p>If you can use LINQ (.NET Framework 3.5+) than following one liner will give you short code. Don't forget to add <code>using System.Linq;</code> to have access to <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.reverse?view=netframework-4.8\" rel=\"noreferrer\"><code>Enumerable.Reverse</code></a>:</p>\n\n<pre><code>public string ReverseString(string srtVarable)\n{\n return new string(srtVarable.Reverse().ToArray());\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>not the fastest version - according to <a href=\"https://stackoverflow.com/users/6513167/martin-niederl\">Martin Niederl</a> 5.7 times slower than the fastest choice here.</li>\n<li>this code as many other options completely ignores all sorts of multi-character combinations, so limit usage to homework assignments and strings which <em>do not</em> contain such characters. See another <a href=\"https://stackoverflow.com/a/15111719/477420\">answer</a> in this question for implementation that correctly handles such combinations.</li>\n</ul>\n" }, { "answer_id": 15908939, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": false, "text": "<pre><code>public static string Reverse(string input)\n{\n return string.Concat(Enumerable.Reverse(input));\n}\n</code></pre>\n\n<p>Of course you can extend string class with Reverse method</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string Reverse(this string input)\n {\n return string.Concat(Enumerable.Reverse(input));\n }\n}\n</code></pre>\n" }, { "answer_id": 20564284, "author": "AMIN", "author_id": 3098994, "author_profile": "https://Stackoverflow.com/users/3098994", "pm_score": -1, "selected": false, "text": "<pre><code>string A = null;\n//a now is reversed and you can use it\nA = SimulateStrReverse.StrReverse(\"your string\");\n\npublic static class SimulateStrReverse\n{\n public static string StrReverse(string expression)\n {\n if (string.IsNullOrEmpty(expression))\n return string.Empty;\n\n string reversedString = string.Empty;\n for (int charIndex = expression.Length - 1; charIndex &gt;= 0; charIndex--)\n {\n reversedString += expression[charIndex];\n }\n return reversedString;\n }\n}\n</code></pre>\n" }, { "answer_id": 21414083, "author": "Rezo Megrelidze", "author_id": 2204040, "author_profile": "https://Stackoverflow.com/users/2204040", "pm_score": 2, "selected": false, "text": "<p>Stack-based solution.</p>\n\n<pre><code> public static string Reverse(string text)\n {\n var stack = new Stack&lt;char&gt;(text);\n var array = new char[stack.Count];\n\n int i = 0;\n while (stack.Count != 0)\n {\n array[i++] = stack.Pop();\n }\n\n return new string(array);\n }\n</code></pre>\n\n<p>Or </p>\n\n<pre><code> public static string Reverse(string text)\n {\n var stack = new Stack&lt;char&gt;(text);\n return string.Join(\"\", stack);\n }\n</code></pre>\n" }, { "answer_id": 21430958, "author": "Rezo Megrelidze", "author_id": 2204040, "author_profile": "https://Stackoverflow.com/users/2204040", "pm_score": 2, "selected": false, "text": "<p>If you have a string that only contains ASCII characters, you can use this method.</p>\n\n<pre><code> public static string ASCIIReverse(string s)\n {\n byte[] reversed = new byte[s.Length];\n\n int k = 0;\n for (int i = s.Length - 1; i &gt;= 0; i--)\n {\n reversed[k++] = (byte)s[i];\n }\n\n return Encoding.ASCII.GetString(reversed);\n }\n</code></pre>\n" }, { "answer_id": 22361614, "author": "Raphael Saldanha", "author_id": 3412087, "author_profile": "https://Stackoverflow.com/users/3412087", "pm_score": 0, "selected": false, "text": "<pre><code> string original = \"Stack Overflow\";\n string reversed = new string(original.Reverse().ToArray());\n</code></pre>\n" }, { "answer_id": 22415201, "author": "TSqealBroDuh", "author_id": 2873025, "author_profile": "https://Stackoverflow.com/users/2873025", "pm_score": -1, "selected": false, "text": "<p><code>SELECT REVERSE('somestring');</code>\nDone.</p>\n" }, { "answer_id": 24499284, "author": "natenho", "author_id": 1987788, "author_profile": "https://Stackoverflow.com/users/1987788", "pm_score": 2, "selected": false, "text": "<p>I've made a C# port from <a href=\"http://referencesource.microsoft.com/#Microsoft.VisualBasic/Strings.vb\" rel=\"nofollow\">Microsoft.VisualBasic.Strings</a>. I'm not sure why they keep such useful functions (from VB) outside the System.String in Framework, but still under Microsoft.VisualBasic. Same scenario for financial functions (e.g. <code>Microsoft.VisualBasic.Financial.Pmt()</code>).</p>\n\n<pre><code>public static string StrReverse(this string expression)\n{\n if ((expression == null))\n return \"\";\n\n int srcIndex;\n\n var length = expression.Length;\n if (length == 0)\n return \"\";\n\n //CONSIDER: Get System.String to add a surrogate aware Reverse method\n\n //Detect if there are any graphemes that need special handling\n for (srcIndex = 0; srcIndex &lt;= length - 1; srcIndex++)\n {\n var ch = expression[srcIndex];\n var uc = char.GetUnicodeCategory(ch);\n if (uc == UnicodeCategory.Surrogate || uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || uc == UnicodeCategory.EnclosingMark)\n {\n //Need to use special handling\n return InternalStrReverse(expression, srcIndex, length);\n }\n }\n\n var chars = expression.ToCharArray();\n Array.Reverse(chars);\n return new string(chars);\n}\n\n///&lt;remarks&gt;This routine handles reversing Strings containing graphemes\n/// GRAPHEME: a text element that is displayed as a single character&lt;/remarks&gt;\nprivate static string InternalStrReverse(string expression, int srcIndex, int length)\n{\n //This code can only be hit one time\n var sb = new StringBuilder(length) { Length = length };\n\n var textEnum = StringInfo.GetTextElementEnumerator(expression, srcIndex);\n\n //Init enumerator position\n if (!textEnum.MoveNext())\n {\n return \"\";\n }\n\n var lastSrcIndex = 0;\n var destIndex = length - 1;\n\n //Copy up the first surrogate found\n while (lastSrcIndex &lt; srcIndex)\n {\n sb[destIndex] = expression[lastSrcIndex];\n destIndex -= 1;\n lastSrcIndex += 1;\n }\n\n //Now iterate through the text elements and copy them to the reversed string\n var nextSrcIndex = textEnum.ElementIndex;\n\n while (destIndex &gt;= 0)\n {\n srcIndex = nextSrcIndex;\n\n //Move to next element\n nextSrcIndex = (textEnum.MoveNext()) ? textEnum.ElementIndex : length;\n lastSrcIndex = nextSrcIndex - 1;\n\n while (lastSrcIndex &gt;= srcIndex)\n {\n sb[destIndex] = expression[lastSrcIndex];\n destIndex -= 1;\n lastSrcIndex -= 1;\n }\n }\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 26271208, "author": "Reasurria", "author_id": 2790482, "author_profile": "https://Stackoverflow.com/users/2790482", "pm_score": 2, "selected": false, "text": "<p>First of all what you have to understand is that str+= will resize your string memory to make space for 1 extra char. This is fine, but if you have, say, a book with 1000 pages that you want to reverse, this will take very long to execute.</p>\n\n<p>The solution that some people might suggest is using StringBuilder. What string builder does when you perform a += is that it allocates much larger chunks of memory to hold the new character so that it does not need to do a reallocation every time you add a char. </p>\n\n<p>If you really want a fast and minimal solution I'd suggest the following:</p>\n\n<pre><code> char[] chars = new char[str.Length];\n for (int i = str.Length - 1, j = 0; i &gt;= 0; --i, ++j)\n {\n chars[j] = str[i];\n }\n str = new String(chars);\n</code></pre>\n\n<p>In this solution there is one initial memory allocation when the char[] is initialized and one allocation when the string constructor builds the string from the char array. </p>\n\n<p>On my system I ran a test for you that reverses a string of 2 750 000 characters. Here are the results for 10 executions:</p>\n\n<p>StringBuilder: 190K - 200K ticks</p>\n\n<p>Char Array: 130K - 160K ticks</p>\n\n<p>I also ran a test for normal String += but I abandoned it after 10 minutes with no output.</p>\n\n<p>However, I also noticed that for smaller strings the StringBuilder is faster, so you will have to decide on the implementation based on the input.</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 26439257, "author": "Mehdi Khademloo", "author_id": 4038978, "author_profile": "https://Stackoverflow.com/users/4038978", "pm_score": 4, "selected": false, "text": "<p>The easy and nice answer is using the Extension Method:</p>\n\n<pre><code>static class ExtentionMethodCollection\n{\n public static string Inverse(this string @base)\n {\n return new string(@base.Reverse().ToArray());\n }\n}\n</code></pre>\n\n<p>and here's the output: </p>\n\n<pre><code>string Answer = \"12345\".Inverse(); // = \"54321\"\n</code></pre>\n" }, { "answer_id": 27171827, "author": "Mark Henry", "author_id": 4295340, "author_profile": "https://Stackoverflow.com/users/4295340", "pm_score": -1, "selected": false, "text": "<p>Reverse a String without even using a new string. Lets say</p>\n\n<pre><code>String input = \"Mark Henry\";\n//Just to convert into char array. One can simply take input in char array.\nChar[] array = input.toCharArray(input);\nint a = input.length;\n\nfor(int i=0; i&lt;(array.length/2 -1) ; i++)\n{\n array[i] = array[i] + array[a];\n array[a] = array[i] - array[a];\n array[i] = array[i] - array[a--];\n}\n</code></pre>\n" }, { "answer_id": 30936734, "author": "Jason Ausborn", "author_id": 4473175, "author_profile": "https://Stackoverflow.com/users/4473175", "pm_score": 2, "selected": false, "text": "<p>Sorry for posting on this old thread. I am practicing some code for an interview.</p>\n\n<p>This was what I came up with for C#. My first version before refactoring was horrible.</p>\n\n<pre><code>static String Reverse2(string str)\n{\n int strLen = str.Length, elem = strLen - 1;\n char[] charA = new char[strLen];\n\n for (int i = 0; i &lt; strLen; i++)\n {\n charA[elem] = str[i];\n elem--;\n }\n\n return new String(charA);\n}\n</code></pre>\n\n<p>In Contrast to the <code>Array.Reverse</code> method below, it appears faster with 12 characters or less in the string. After 13 characters, the <code>Array.Reverse</code> starts to get faster, and it eventually dominates pretty heavily on speed. I just wanted to point out approximately where the speed starts to change.</p>\n\n<pre><code>static String Reverse(string str)\n{ \n char[] charA = str.ToCharArray();\n\n Array.Reverse(charA);\n\n return new String(charA);\n}\n</code></pre>\n\n<p>At 100 characters in the string, it is faster than my version x 4. However, if I knew that the strings would always be less than 13 characters, I would use the one I made. </p>\n\n<p>Testing was done with <code>Stopwatch</code> and 5000000 iterations. Also, I'm not sure if my version handles Surrogates or combined character situations with <code>Unicode</code> encoding.</p>\n" }, { "answer_id": 33413626, "author": "ddagsan", "author_id": 1580548, "author_profile": "https://Stackoverflow.com/users/1580548", "pm_score": 2, "selected": false, "text": "<pre><code>public static string reverse(string s) \n{\n string r = \"\";\n for (int i = s.Length; i &gt; 0; i--) r += s[i - 1];\n return r;\n}\n</code></pre>\n" }, { "answer_id": 37541215, "author": "Munavvar", "author_id": 3261852, "author_profile": "https://Stackoverflow.com/users/3261852", "pm_score": 1, "selected": false, "text": "<p>There are various ways to reverse the string, I have shown 3 of them below.</p>\n\n<p>-- Using Array.Reverse function.</p>\n\n<pre><code> private static string ReverseString1(string text)\n {\n char[] rtext = text.ToCharArray();\n Array.Reverse(rtext);\n return new string(rtext);\n }\n</code></pre>\n\n<p>-- using string only</p>\n\n<pre><code> private static string ReverseString2(string text)\n {\n String rtext = \"\";\n for (int i = text.Length - 1; i &gt;= 0; i--)\n {\n rtext = rtext + text[i];\n }\n return rtext;\n }\n</code></pre>\n\n<p>-- Using only char array</p>\n\n<pre><code> public static string ReverseString3(string str)\n {\n char[] chars = str.ToCharArray();\n char[] rchars = new char[chars.Length];\n for (int i = 0, j = str.Length - 1; i &lt; chars.Length; i++, j--)\n {\n rchars[j] = chars[i];\n }\n return new string(rchars);\n }\n</code></pre>\n" }, { "answer_id": 39400093, "author": "simon", "author_id": 5225334, "author_profile": "https://Stackoverflow.com/users/5225334", "pm_score": -1, "selected": false, "text": "<p>I was asked a similar question in interview. This was my response, although it is probably not as fast in performance as other answers. My question was phrased as \"Make a class that can have a method to print a string backwards\":</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace BackwardsTest\n{\n class PrintBackwards\n {\n public static void print(string param)\n {\n if (param == null || param.Length == 0)\n {\n Console.WriteLine(\"string is null\");\n return;\n }\n List&lt;char&gt; list = new List&lt;char&gt;();\n string returned = null;\n foreach(char d in param)\n {\n list.Add(d);\n }\n for(int i = list.Count(); i &gt; 0; i--)\n {\n returned = returned + list[list.Count - 1];\n list.RemoveAt(list.Count - 1);\n }\n Console.WriteLine(returned);\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n string test = \"I want to print backwards\";\n PrintBackwards.print(test);\n System.Threading.Thread.Sleep(5000);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 39622549, "author": "Raktim Biswas", "author_id": 6290553, "author_profile": "https://Stackoverflow.com/users/6290553", "pm_score": 1, "selected": false, "text": "<p>As simple as this:</p>\n\n<pre><code>string x = \"your string\"; \nstring x1 = \"\";\nfor(int i = x.Length-1 ; i &gt;= 0; i--)\n x1 += x[i];\nConsole.WriteLine(\"The reverse of the string is:\\n {0}\", x1);\n</code></pre>\n\n<p>See the <a href=\"https://dotnetfiddle.net/6UTpZV\" rel=\"nofollow\">output</a>.</p>\n" }, { "answer_id": 46515622, "author": "Slai", "author_id": 1383168, "author_profile": "https://Stackoverflow.com/users/1383168", "pm_score": 4, "selected": false, "text": "<p>\"Best\" can depend on many things, but here are few more short alternatives ordered from fast to slow:</p>\n\n<pre><code>string s = \"z̽a̎l͘g̈o̓\", pattern = @\"(?s).(?&lt;=(?:.(?=.*$(?&lt;=((\\P{M}\\p{C}?\\p{M}*)\\1?))))*)\";\n\nstring s1 = string.Concat(s.Reverse()); // \"☐☐̓ög͘l̎a̽z\" \n\nstring s2 = Microsoft.VisualBasic.Strings.StrReverse(s); // \"o̓g̈l͘a̎̽z\" \n\nstring s3 = string.Concat(StringInfo.ParseCombiningCharacters(s).Reverse()\n .Select(i =&gt; StringInfo.GetNextTextElement(s, i))); // \"o̓g̈l͘a̎z̽\" \n\nstring s4 = Regex.Replace(s, pattern, \"$2\").Remove(s.Length); // \"o̓g̈l͘a̎z̽\" \n</code></pre>\n" }, { "answer_id": 47080314, "author": "Jim", "author_id": 2040068, "author_profile": "https://Stackoverflow.com/users/2040068", "pm_score": 1, "selected": false, "text": "<p>here is a unicode safe version of the function, written as an extension that will safely handle unicode. It is close to the marked complete answer, but will not throw exceptions for \"Invalid high surrogate character\".</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string Reverse(this string s)\n {\n var info = new StringInfo(s);\n var charArray = new char[s.Length];\n var teIndices = StringInfo.ParseCombiningCharacters(s).Reverse();\n\n int j = 0;\n foreach(var i in teIndices)\n {\n if (char.IsHighSurrogate(s[i]))\n {\n charArray[j] = s[i];\n j++;\n charArray[j] = s[i+1];\n }\n else\n {\n charArray[j] = s[i];\n }\n j++;\n }\n\n return new string(charArray);\n\n }\n}\n</code></pre>\n" }, { "answer_id": 48792874, "author": "joegreentea", "author_id": 2337475, "author_profile": "https://Stackoverflow.com/users/2337475", "pm_score": 1, "selected": false, "text": "<p>How about use Substring</p>\n\n<pre><code>static string ReverseString(string text)\n{\n string sub = \"\";\n int indexCount = text.Length - 1;\n for (int i = indexCount; i &gt; -1; i--)\n {\n sub = sub + text.Substring(i, 1);\n }\n return sub;\n}\n</code></pre>\n" }, { "answer_id": 50337746, "author": "Milad Jafari", "author_id": 4220076, "author_profile": "https://Stackoverflow.com/users/4220076", "pm_score": -1, "selected": false, "text": "<p>This is the code used for reverse string </p>\n\n<pre><code>public Static void main(){\n string text = \"Test Text\";\n Console.Writeline(RevestString(text))\n}\n\npublic Static string RevestString(string text){\n char[] textToChar = text.ToCharArray();\n string result= string.Empty;\n int length = textToChar .Length;\n for (int i = length; i &gt; 0; --i)\n result += textToChar[i - 1];\n return result;\n}\n</code></pre>\n" }, { "answer_id": 50412992, "author": "Pankaj Rawat", "author_id": 4140278, "author_profile": "https://Stackoverflow.com/users/4140278", "pm_score": -1, "selected": false, "text": "<p>It's very simple</p>\n\n<pre><code>static void Reverse()\n {\n string str = \"PankajRawat\";\n var arr = str.ToCharArray();\n for (int i = str.Length-1; i &gt;= 0; i--)\n {\n Console.Write(arr[i]);\n }\n }\n</code></pre>\n" }, { "answer_id": 53648374, "author": "Shadi Serhan", "author_id": 2979382, "author_profile": "https://Stackoverflow.com/users/2979382", "pm_score": 3, "selected": false, "text": "<p>Simplest way:</p>\n\n<pre><code>string reversed = new string(text.Reverse().ToArray());\n</code></pre>\n" }, { "answer_id": 56772632, "author": "Deep", "author_id": 2785027, "author_profile": "https://Stackoverflow.com/users/2785027", "pm_score": 0, "selected": false, "text": "<pre><code>static void Main(string[] args)\n{\n string str = \"\";\n string reverse = \"\";\n Console.WriteLine(\"Enter the value to reverse\");\n str = Console.ReadLine();\n int length = 0;\n length = str.Length - 1;\n while(length &gt;= 0)\n {\n reverse = reverse + str[length];\n length--;\n }\n Console.Write(\"Reverse string is {0}\", reverse);\n Console.ReadKey();\n}\n</code></pre>\n" }, { "answer_id": 56937817, "author": "Flogex", "author_id": 8336143, "author_profile": "https://Stackoverflow.com/users/8336143", "pm_score": 4, "selected": false, "text": "<p>Starting with .NET Core 2.1 there is a new way to reverse a string using the <code>string.Create</code> method.</p>\n<p><em>Note that this solution does not handle Unicode combining characters etc. correctly, as &quot;Les Mise\\u0301rables&quot; would be converted to &quot;selbarésiM seL&quot;. See <a href=\"https://stackoverflow.com/a/15111719/8336143\">the other answers</a> for a better solution.</em></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string Reverse(string input)\n{\n return string.Create&lt;string&gt;(input.Length, input, (chars, state) =&gt;\n {\n state.AsSpan().CopyTo(chars);\n chars.Reverse();\n });\n}\n</code></pre>\n<p>This essentially copies the characters of <code>input</code> to a new string and reverses the new string in-place.</p>\n<h3>Why is <code>string.Create</code> useful?</h3>\n<p>When we create a string from an existing array, a new internal array is allocated and the values are copied. Otherwise, it would be possible to mutate a string after its creation (in a safe environment). That is, in the following snippet we have to allocate an array of length 10 twice, one as the buffer and one as the string's internal array.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var chars = new char[10];\n// set array values\nvar str = new string(chars);\n</code></pre>\n<p><code>string.Create</code> essentially allows us to manipulate the internal array during creation time of the string. This is, we do not need a buffer anymore and can therefore avoid allocating that one char array.</p>\n<p>Steve Gordon has written about it in more detail <a href=\"https://www.stevejgordon.co.uk/creating-strings-with-no-allocation-overhead-using-string-create-csharp\" rel=\"noreferrer\">here</a>. There is also an article on <a href=\"https://msdn.microsoft.com/en-us/magazine/mt814808.aspx#code-snippet-18\" rel=\"noreferrer\">MSDN</a>.</p>\n<h3>How to use <code>string.Create</code>?</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string Create&lt;TState&gt;(int length, TState state, SpanAction&lt;char, TState&gt; action);\n</code></pre>\n<p>The method takes three parameters:</p>\n<ol>\n<li>The length of the string to create,</li>\n<li>the data you want to use to dynamically create the new string,</li>\n<li>and a delegate that creates the final string from the data, where the first parameter points to the internal <code>char</code> array of the new string and the second is the data (state) you passed to <code>string.Create</code>.</li>\n</ol>\n<p>Inside the delegate we can specify how the new string is created from the data. In our case, we just copy the characters of the input string to the <code>Span</code> used by the new string. Then we reverse the <code>Span</code> and hence the whole string is reversed.</p>\n<h3>Benchmarks</h3>\n<p>To compare my proposed way of reversing a string with the accepted answer, I have written two benchmarks using BenchmarkDotNet.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class StringExtensions\n{\n public static string ReverseWithArray(string input)\n {\n var charArray = input.ToCharArray();\n Array.Reverse(charArray);\n return new string(charArray);\n }\n\n public static string ReverseWithStringCreate(string input)\n {\n return string.Create(input.Length, input, (chars, state) =&gt;\n {\n state.AsSpan().CopyTo(chars);\n chars.Reverse();\n });\n }\n}\n\n[MemoryDiagnoser]\npublic class StringReverseBenchmarks\n{\n private string input;\n\n [Params(10, 100, 1000)]\n public int InputLength { get; set; }\n\n\n [GlobalSetup]\n public void SetInput()\n {\n // Creates a random string of the given length\n this.input = RandomStringGenerator.GetString(InputLength);\n }\n\n [Benchmark(Baseline = true)]\n public string WithReverseArray() =&gt; StringExtensions.ReverseWithArray(input);\n\n [Benchmark]\n public string WithStringCreate() =&gt; StringExtensions.ReverseWithStringCreate(input);\n}\n</code></pre>\n<p>Here are the results on my machine:</p>\n<pre><code>| Method | InputLength | Mean | Error | StdDev | Gen 0 | Allocated |\n| ---------------- | ----------- | -----------: | ---------: | --------: | -----: | --------: |\n| WithReverseArray | 10 | 45.464 ns | 0.4836 ns | 0.4524 ns | 0.0610 | 96 B |\n| WithStringCreate | 10 | 39.749 ns | 0.3206 ns | 0.2842 ns | 0.0305 | 48 B |\n| | | | | | | |\n| WithReverseArray | 100 | 175.162 ns | 2.8766 ns | 2.2458 ns | 0.2897 | 456 B |\n| WithStringCreate | 100 | 125.284 ns | 2.4657 ns | 2.0590 ns | 0.1473 | 232 B |\n| | | | | | | |\n| WithReverseArray | 1000 | 1,523.544 ns | 9.8808 ns | 8.7591 ns | 2.5768 | 4056 B |\n| WithStringCreate | 1000 | 1,078.957 ns | 10.2948 ns | 9.6298 ns | 1.2894 | 2032 B |\n</code></pre>\n<p>As you can see, with <code>ReverseWithStringCreate</code> we allocate only half of the memory used by the <code>ReverseWithArray</code> method.</p>\n" }, { "answer_id": 56982067, "author": "Punit Pandya", "author_id": 10747653, "author_profile": "https://Stackoverflow.com/users/10747653", "pm_score": 0, "selected": false, "text": "<pre><code> using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication1\n{\n class Program\n { \n public static string ReverseString(string str)\n {\n int totalLength = str.Length;\n int iCount = 0;\n string strRev = string.Empty;\n iCount = totalLength;\n while (iCount != 0)\n {\n iCount--;\n strRev += str[iCount]; \n }\n return strRev;\n }\n static void Main(string[] args)\n {\n string str = \"Punit Pandya\";\n string strResult = ReverseString(str);\n Console.WriteLine(strResult);\n Console.ReadLine();\n }\n }\n\n }\n</code></pre>\n" }, { "answer_id": 57177035, "author": "Karthik", "author_id": 10726714, "author_profile": "https://Stackoverflow.com/users/10726714", "pm_score": 1, "selected": false, "text": "<p>Using LINQ's Aggregate function</p>\n\n<pre><code>string s = \"Karthik U\";\ns = s.Aggregate(new StringBuilder(), (o, p) =&gt; o.Insert(0, p)).ToString();\n</code></pre>\n" }, { "answer_id": 57577337, "author": "SET", "author_id": 8547919, "author_profile": "https://Stackoverflow.com/users/8547919", "pm_score": 2, "selected": false, "text": "<p>Since I like a couple of the answers - one for using <code>string.Create</code> and therefore high performance and low allocation and another for correctness - using the <code>StringInfo</code> class, I decided a combined approach is needed. This is the ultimate string reversal method :)</p>\n\n<pre><code>private static string ReverseString(string str)\n {\n return string.Create(str.Length, str, (chars, state) =&gt;\n {\n var enumerator = StringInfo.GetTextElementEnumerator(state);\n var position = state.Length;\n while (enumerator.MoveNext())\n {\n var cluster = ((string)enumerator.Current).AsSpan();\n cluster.CopyTo(chars.Slice(position - cluster.Length));\n position -= cluster.Length;\n }\n });\n }\n</code></pre>\n\n<p>There's an even better way using a method of the StringInfo class which skips a lot of string allocations by the Enumerator by returning just the indexes.</p>\n\n<pre><code>private static string ReverseString(string str)\n {\n return string.Create(str.Length, str, (chars, state) =&gt;\n {\n var position = 0;\n var indexes = StringInfo.ParseCombiningCharacters(state); // skips string creation\n var stateSpan = state.AsSpan();\n for (int len = indexes.Length, i = len - 1; i &gt;= 0; i--)\n {\n var index = indexes[i];\n var spanLength = i == len - 1 ? state.Length - index : indexes[i + 1] - index;\n stateSpan.Slice(index, spanLength).CopyTo(chars.Slice(position));\n position += spanLength;\n }\n });\n }\n</code></pre>\n\n<p>Some benchmarks compared to the LINQ solution:</p>\n\n<pre><code>String length 20:\n\nLINQ Mean: 2,355.5 ns Allocated: 1440 B\nstring.Create Mean: 851.0 ns Allocated: 720 B\nstring.Create with indexes Mean: 466.4 ns Allocated: 168 B\n\nString length 450:\n\nLINQ Mean: 34.33 us Allocated: 22.98 KB\nstring.Create Mean: 19.13 us Allocated: 14.98 KB\nstring.Create with indexes Mean: 10.32 us Allocated: 2.69 KB\n</code></pre>\n" }, { "answer_id": 60997534, "author": "Gigabyte", "author_id": 3729730, "author_profile": "https://Stackoverflow.com/users/3729730", "pm_score": 1, "selected": false, "text": "<p>Handles all type of unicode characters </p>\n\n<p>using System.Globalization;</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public static string ReverseString(this string content) {\n\n var textElementEnumerator = StringInfo.GetTextElementEnumerator(content);\n\n var SbBuilder = new StringBuilder(content.Length);\n\n while (textElementEnumerator.MoveNext()) {\n SbBuilder.Insert(0, textElementEnumerator.GetTextElement());\n }\n\n return SbBuilder.ToString();\n }\n</code></pre>\n" }, { "answer_id": 64250151, "author": "Ramakrishna Talla", "author_id": 849030, "author_profile": "https://Stackoverflow.com/users/849030", "pm_score": 2, "selected": false, "text": "<p>If someone asks about string reverse, the intension could be to find out whether you know any bitwise operation like XOR. In C# you have Array.Reverse function, however, you can do using simple XOR operation in few lines of code(minimal)</p>\n<pre><code> public static string MyReverse(string s)\n {\n char[] charArray = s.ToCharArray();\n int bgn = -1;\n int end = s.Length;\n while(++bgn &lt; --end)\n {\n charArray[bgn] ^= charArray[end];\n charArray[end] ^= charArray[bgn];\n charArray[bgn] ^= charArray[end];\n }\n return new string(charArray);\n }\n</code></pre>\n" }, { "answer_id": 71577236, "author": "Perdente", "author_id": 14071426, "author_profile": "https://Stackoverflow.com/users/14071426", "pm_score": 0, "selected": false, "text": "<p>We can use two pointers one pointing to the start of the string and another to the end of the string. Then swap both ith and jth values each time and increment ith pointer +1 and decrement jth pointer -1.</p>\n<pre><code>string s = Console.ReadLine();\nConsole.WriteLine(s + &quot;\\n&quot;);\nchar[] charArray = s.ToCharArray();\nint i = 0, j = s.Length - 1;\nwhile (i &lt; j) {\n char temp = charArray[i];\n charArray[i] = charArray[j];\n charArray[j] = temp;\n i++; j--;\n}\nstring ans = new string(charArray);\nConsole.WriteLine(ans + &quot;\\n&quot;);\n// Input: hello\n// Output: olleh\n</code></pre>\n" }, { "answer_id": 73419041, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 1, "selected": false, "text": "<p>There are a few correct answers where <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.globalization.stringinfo?view=net-6.0\" rel=\"nofollow noreferrer\">StringInfo.GetTextElementEnumerator()</a> is being used. Kudos to you!</p>\n<p>Now, let's find the most efficient way to use this method. First, most answers involve calling <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.reverse?view=net-6.0\" rel=\"nofollow noreferrer\">Reverse()</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.toarray?view=net-6.0\" rel=\"nofollow noreferrer\">ToArray()</a> which is a big no-no on hot paths. For optimal performance, we want to avoid allocating garbage. E.g. temporary strings, allocators, arrays etc.</p>\n<h2>Optimized reversal of string</h2>\n<ul>\n<li>Reduced GC pressure. I.e. no <code>LINQ</code> enumerators, no arrays.</li>\n<li>Using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-6.0\" rel=\"nofollow noreferrer\">Span</a></li>\n<li>Using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.create?view=net-6.0\" rel=\"nofollow noreferrer\">String.Create()</a></li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Globalization;\n\npublic static class StringExtensions\n{\n public static string AsReversed(this string s)\n {\n return string.Create(s.Length, s, (chars, state) =&gt;\n {\n int i = 0;\n var enumerator = StringInfo.GetTextElementEnumerator(s);\n while (enumerator.MoveNext())\n {\n var element = enumerator.GetTextElement();\n i += element.Length;\n element.CopyTo(chars[^i..]);\n }\n });\n }\n}\n\n</code></pre>\n<p>Note that the <code>GetTextElementEnumerator()</code> API contains a <strong>bug</strong> in <code>.NET Core 3.1</code> and earlier. Make sure to run <strong><code>.NET 5</code></strong> or later! Finally, make sure to check out <a href=\"https://github.com/dotnet/runtime/issues/19423\" rel=\"nofollow noreferrer\">issue #19423</a> where API improvements are being discussed.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this: ``` public string Reverse(string text) { char[] cArray = text.ToCharArray(); string reverse = String.Empty; for (int i = cArray.Length - 1; i > -1; i--) { reverse += cArray[i]; } return reverse; } ``` Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
``` public static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } ```
228,089
<p>I have tried what seems like everything - I've done similiar things many times before, but I'm obviously missing something.</p> <p>I have a UserControl (ucA) - on ucA is a LinkButton that loads a different UserControl (ucB) programatically into a panel on ucA. ucB has TextBoxes, etc. </p> <p>Why isn't my control maintaining it's state? ie: The textboxes are loosing thier value on postback - the control tree shows the name of the control and the Form values show the value (in trace.axd)</p> <p>Here is the code for ucA (basically)</p> <pre><code>public int SlideCount { get { return Convert.ToInt32(ViewState["SlideCount"]); } set { ViewState["SlideCount"] = value; } } protected void LinkButton1_Click(object sender, EventArgs e) { SlideCount += 1; LoadSlideControls(); } protected override void OnInit(EventArgs e) { base.OnInit(e); LoadSlideControls(); } private void LoadSlideControls() { this.pnlAnnouncementHolder.Controls.Clear(); for (int i = 0; i &lt; SlideCount; i++) { this.pnlAnnouncementHolder.Controls.Add( LoadControl("AnnouncementSlide.ascx")); } } </code></pre> <p>Heres a full example of what im trying to do: <a href="http://keithsblogs.com/ControlTest2.zip" rel="nofollow noreferrer">http://keithsblogs.com/ControlTest2.zip</a></p> <p>The problem Vyrotek points out is that the control is added a little to late to the lifecycle on the click event - anyone have any ideas?</p>
[ { "answer_id": 228149, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 1, "selected": false, "text": "<p>I am installing express edition as I type. By that time, why should you clear the controls on click of the button? cant you just add/load the uc once control on click of the link?</p>\n\n<p>By doing this, you would not be clearing the old controls and they would retain the value.</p>\n" }, { "answer_id": 228188, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 3, "selected": true, "text": "<p>I just tried to recreate what you have setup and I dont seem to experience the same problem. Would you like me to send you my Solution somehow?</p>\n\n<p>Final Edit, I promised -</p>\n\n<p>Try this solution: <a href=\"http://www.vyrotek.com/code/ControlTest2.zip\" rel=\"nofollow noreferrer\">http://www.vyrotek.com/code/ControlTest2.zip</a></p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26685/" ]
I have tried what seems like everything - I've done similiar things many times before, but I'm obviously missing something. I have a UserControl (ucA) - on ucA is a LinkButton that loads a different UserControl (ucB) programatically into a panel on ucA. ucB has TextBoxes, etc. Why isn't my control maintaining it's state? ie: The textboxes are loosing thier value on postback - the control tree shows the name of the control and the Form values show the value (in trace.axd) Here is the code for ucA (basically) ``` public int SlideCount { get { return Convert.ToInt32(ViewState["SlideCount"]); } set { ViewState["SlideCount"] = value; } } protected void LinkButton1_Click(object sender, EventArgs e) { SlideCount += 1; LoadSlideControls(); } protected override void OnInit(EventArgs e) { base.OnInit(e); LoadSlideControls(); } private void LoadSlideControls() { this.pnlAnnouncementHolder.Controls.Clear(); for (int i = 0; i < SlideCount; i++) { this.pnlAnnouncementHolder.Controls.Add( LoadControl("AnnouncementSlide.ascx")); } } ``` Heres a full example of what im trying to do: <http://keithsblogs.com/ControlTest2.zip> The problem Vyrotek points out is that the control is added a little to late to the lifecycle on the click event - anyone have any ideas?
I just tried to recreate what you have setup and I dont seem to experience the same problem. Would you like me to send you my Solution somehow? Final Edit, I promised - Try this solution: <http://www.vyrotek.com/code/ControlTest2.zip>
228,102
<pre><code>&lt;div&gt; &lt;span&gt;left&lt;/span&gt; &lt;span&gt;right&lt;/span&gt; &lt;!-- new line break, so no more content on that line --&gt; &lt;table&gt; ... &lt;/table&gt; &lt;/div&gt; </code></pre> <p>How can I position those spans (they can be changed to any element) so that depending on how big the table is (not defined anywhere, and shouldn't be) the spans are positioned just on top of the left side of the table and the right side of the table.</p> <p>Example:</p> <pre> a b table0 table1 table2 </pre> <p>(where a is the left span, and b is the right span)</p> <p>P.S. You can change anything bar inner table html.</p>
[ { "answer_id": 228122, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 1, "selected": false, "text": "<p>if you have divs instead of span, try float:left for span a and float:right for span b</p>\n" }, { "answer_id": 228126, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\"&gt;\n #wrapper, #top, #tableArea\n {\n width: 100%;\n padding: 10px;\n margin: 0px auto;\n }\n\n #top\n {\n padding: 0px;\n }\n\n #leftBox, #rightBox\n {\n margin: 0px;\n float: left;\n display: inline;\n clear: none;\n }\n\n #rightBox\n {\n float: right;\n }\n &lt;/style&gt;\n&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"top\"&gt;\n &lt;div id=\"leftBox\"&gt;A&lt;/div&gt;\n &lt;div id=\"rightBox\"&gt;b&lt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"tableArea\"&gt;\n &lt;table&gt; ... &lt;/table&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 228133, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;div&gt;\n&lt;div style=\"float:left\"&gt;a&lt;/div&gt;&lt;div style=\"float:right\"&gt;b&lt;/div&gt;\n&lt;br style=\"clear: both\"&gt;\naaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;br /&gt;\naaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;br /&gt;\naaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;br /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Doesn't place them relatively, nor does Rob Allen's answer, they put them at the far reaches of the browser not, within the table width.</p>\n" }, { "answer_id": 228146, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Doesn't place them relatively, nor\n does Rob Allen's answer, they put them\n at the far reaches of the browser not,\n within the table width.</p>\n</blockquote>\n\n<p>Well they are going to be bound by their container width and Rob's answer makes both the table and container width 100%.</p>\n\n<p>The only solution I can think of off hand is to put in a row in your table with a single column (spanning all columns) and in that row have your floated DIVs.</p>\n" }, { "answer_id": 228151, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@MattMitchell, you might have something there. And then just use fload: left and float right I assume?</p>\n" }, { "answer_id": 228406, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I can't think of anyway, except to set the width of the table to something. In my case I choose 100%, which stretches to the width of the rapper at 50em:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n#wrapper {\n width: 1%;\n min-width:50em;\n padding: 10px;\n}\n#mainTable {\n width:100%;\n}\n\n#leftBox {\n float: left;\n}\n\n#rightBox {\n float: right;\n}\n&lt;/style&gt;\n&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"leftBox\"&gt;A&lt;/div&gt;\n &lt;div id=\"rightBox\"&gt;b&lt;/div&gt;\n &lt;br style=\"clear: both\" /&gt;\n some text some text some text some text some text &lt;br /&gt;\n some text some text some text some text some text &lt;br /&gt;\n some text some text some text some text some text\n &lt;table id=\"mainTable\" border=\"1\"&gt;&lt;tr&gt;&lt;td&gt;test&lt;/td&gt;&lt;td&gt;test 2&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 8680378, "author": "Trix", "author_id": 1123037, "author_profile": "https://Stackoverflow.com/users/1123037", "pm_score": 2, "selected": false, "text": "<p>I ran into similar problem and I have found a solution. It doesn't depend on the width of the table but it is a little trickier. It works in every browser including IE5.5, IE6 and newer.</p>\n\n<pre><code> &lt;style&gt;\n .tablediv {\n float:left; /* this is a must otherwise the div will take a full width of our page and this way it wraps only our content (so only the table) */\n position:relative; /* we are setting this to start the trickie part */ \n padding-top:2.7em; /* we have to set the room for our spans, 2.7em is enough for two rows otherwise try to use something else; for one row e.g. 1.7em */\n }\n .leftspan {\n position:absolute; /* seting this to our spans will start our behaviour */\n top:0; /* we are setting the position where it will be placed inside the .tablediv */\n left:0;\n }\n .rightspan {\n position:absolute; \n top:0; \n right:0; \n }\n &lt;/style&gt;\n&lt;div class=\"tablediv\"&gt;\n &lt;span class=\"leftspan\"&gt;Left text&lt;/span&gt;\n &lt;span class=\"rightspan\"&gt;Right text &lt;br /&gt; with row&lt;/span&gt;\n &lt;table border=\"1\"&gt;\n &lt;tr&gt;&lt;td colspan=\"3\"&gt;Header&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td rowspan=\"2\"&gt;Left content&lt;/td&gt;&lt;td&gt;Content&lt;/td&gt;&lt;td rowspan=\"2\"&gt;Right content&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Bottom content&lt;/td&gt;&lt;/tr&gt;\n &lt;/table&gt;\n&lt;/div&gt;\n &lt;!-- If you don't want to float this on the right side of the table than you must use the clear style --&gt;\n &lt;p style=\"clear:both\"&gt;\n something that continues under our tablediv\n &lt;/p&gt;\n</code></pre>\n\n<p>If you can't use a float for some reason, than you can use an alternative .tablediv style which I found by a mistake. Just replace the <code>float:left; to display:inline-block;</code> This works in all modern browser but not in IE7 and below. </p>\n\n<p>Now you get my point and I'm sure you find any other solutions. Just don't forget that the .tablediv will be as long as the inner content. So placing a paragraph into it will cause to stretch to a bigger size than our table.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` <div> <span>left</span> <span>right</span> <!-- new line break, so no more content on that line --> <table> ... </table> </div> ``` How can I position those spans (they can be changed to any element) so that depending on how big the table is (not defined anywhere, and shouldn't be) the spans are positioned just on top of the left side of the table and the right side of the table. Example: ``` a b table0 table1 table2 ``` (where a is the left span, and b is the right span) P.S. You can change anything bar inner table html.
> > Doesn't place them relatively, nor > does Rob Allen's answer, they put them > at the far reaches of the browser not, > within the table width. > > > Well they are going to be bound by their container width and Rob's answer makes both the table and container width 100%. The only solution I can think of off hand is to put in a row in your table with a single column (spanning all columns) and in that row have your floated DIVs.
228,125
<p>I am after a regular expression that validates a percentage from 0 100 and allows two decimal places. </p> <p>Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?</p> <p>@Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.</p> <p>Thanks to all those who have replied so far. I have found the comments really interesting.</p>
[ { "answer_id": 228152, "author": "Julien Grenier", "author_id": 23051, "author_profile": "https://Stackoverflow.com/users/23051", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><code>(100|[0-9]{1,2})(\\.[0-9]{1,2})?</code></p>\n</blockquote>\n\n<p>That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.</p>\n" }, { "answer_id": 228158, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 1, "selected": false, "text": "<p>Given that your value is in str</p>\n\n<pre><code>str.match(/^(100(\\.0{1,2})?|([0-9]?[0-9](\\.[0-9]{1,2})))$/)\n</code></pre>\n" }, { "answer_id": 228180, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.</p>\n\n<pre><code>var x = parseFloat(str);\nif (isNaN(x) || x &lt; 0 || x &gt; 100) {\n // value is out of range\n}\n</code></pre>\n" }, { "answer_id": 228709, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": false, "text": "<p>I propose this one:</p>\n\n<pre><code>(^100(\\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\\.[0-9]{1,2})?$)\n</code></pre>\n\n<p>It matches 100, 100.0 and 100.00 using this part</p>\n\n<pre><code>^100(\\.0{1,2})?$\n</code></pre>\n\n<p>and numbers like 0, 15, 99, 3.1, 21.67 using </p>\n\n<pre><code>^([1-9]([0-9])?|0)(\\.[0-9]{1,2})?$\n</code></pre>\n\n<p>Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).</p>\n" }, { "answer_id": 228774, "author": "Tom", "author_id": 26155, "author_profile": "https://Stackoverflow.com/users/26155", "pm_score": 1, "selected": false, "text": "<pre><code>^100(\\.(0){0,2})?$|^([1-9]?[0-9])(\\.(\\d{0,2}))?\\%$\n</code></pre>\n\n<p>This would match:<br>\n100.00<br>\noptional \"1-9\" followed by a digit (this makes the int part), optionally followed by a dot and two digits<hr></p>\n\n<p>From what I see, Greg Hewgill's example doesn't really work that well because <i>parseFloat('15x')</i> would simply return 15 which would match the 0&lt;x&lt;100 condition. Using <i><a href=\"http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.w3schools.com%2Fjsref%2Fjsref_parseFloat.asp&amp;ei=WyEASZyqJJW60gW3gPnaDQ&amp;usg=AFQjCNHdASnwFzqSOdqFdPtv6YVEgsOnIQ&amp;sig2=8_OYmkVp4KfsSUCxngbKwA\" rel=\"nofollow noreferrer\">parseFloat</a></i> is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.</p>\n" }, { "answer_id": 228821, "author": "mlarsen", "author_id": 17700, "author_profile": "https://Stackoverflow.com/users/17700", "pm_score": 3, "selected": false, "text": "<p>This reminds me of <a href=\"http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx\" rel=\"nofollow noreferrer\">an old blog Entry</a> By Alex Papadimoulis (of <a href=\"http://thedailywtf.com/\" rel=\"nofollow noreferrer\">The Daily WTF</a> fame) where he tells the following story:</p>\n<blockquote>\n<p>&quot;A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?&quot;</p>\n<p>How would you answer the question?</p>\n<ol>\n<li><p>It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.</p>\n</li>\n<li><p>There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.</p>\n</li>\n</ol>\n</blockquote>\n<p>This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.</p>\n<p>The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.</p>\n<p>The solution given by Greg Hewgill is probably better - even though it would validate &quot;99fxx&quot; as &quot;99&quot;. But given the circumstances that might actually be ok.</p>\n" }, { "answer_id": 228885, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 0, "selected": false, "text": "<p>@mlarsen:\nIs not that a regex here won't do the job better.</p>\n\n<p>Remember that validation msut be done both on client and on server side, so something like:</p>\n\n<pre><code>100|(([1-9][0-9])|[0-9])(\\.(([0-9][1-9])|[1-9]))?\n</code></pre>\n\n<p>would be a cross-language check, just beware of checking the input length with the output match length.</p>\n" }, { "answer_id": 49747017, "author": "L. Schilling", "author_id": 9491307, "author_profile": "https://Stackoverflow.com/users/9491307", "pm_score": 1, "selected": false, "text": "<p>I recomend this, if you are not exclusively developing for english speaking users:</p>\n\n<pre><code>[0-9]{1,2}((,|\\.)[0-9]{1,10})?%?\n</code></pre>\n\n<p>You can simply replace the 10 by a 2 to get two decimal places.</p>\n\n<p>My example will match:</p>\n\n<pre><code>15.5\n5.4366%\n1,43\n50,55%\n34\n45%\n</code></pre>\n\n<p>Of cause the output of this one is harder to cast, but something like this will do (Java Code):</p>\n\n<pre><code>private static Double getMyVal(String myVal) {\n if (myVal.contains(\"%\")) {\n myVal = myVal.replace(\"%\", \"\");\n }\n if (myVal.contains(\",\")) {\n myVal = myVal.replace(',', '.');\n }\n return Double.valueOf(myVal);\n}\n</code></pre>\n" }, { "answer_id": 52160949, "author": "Gangadhara S M", "author_id": 9636426, "author_profile": "https://Stackoverflow.com/users/9636426", "pm_score": 0, "selected": false, "text": "<pre><code>(100(\\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\\.[0-9]{1,2})?)\n</code></pre>\n" }, { "answer_id": 66141634, "author": "Henry Brigham", "author_id": 7133371, "author_profile": "https://Stackoverflow.com/users/7133371", "pm_score": 0, "selected": false, "text": "<p>None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'</p>\n<p>This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.</p>\n<p><code>/(^$)|(^100(\\.0{1,2})?$)|(^([1-9]([0-9])?|0)\\.(\\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\\.[0-9]{1,2})?$)/</code></p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ]
I am after a regular expression that validates a percentage from 0 100 and allows two decimal places. Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript? @Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters. Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job. ``` var x = parseFloat(str); if (isNaN(x) || x < 0 || x > 100) { // value is out of range } ```
228,134
<p>I like Steve Yegge's <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="noreferrer">Prototype Pattern example</a> and decided to whip up a quick proof of concept example.</p> <p>However, I didn't really think things through. While it is great for dynamically specifying the behaviour of objects and is an easy solution to Steve's <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">opinionated elf</a> example, I'm still trying to work out the best way to handle instance variables.</p> <p>For instance, let's say I have an AwesomeDragon object. I then want to make an AwesomeDragonImmuneToFire object so I make a new child of the AwesomeDragon (AwesomeDragonImmuneToFire inherits properties from AwesomeDragon) and 'put' "ImmuneToFire" as a property with a value of 'true'. So far so good. Now let's say I want to send my AwesomeDragon object on a tour of nearby peasant villages. This will involve updating the 'position' property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well.</p> <p>Is the best solution to override instance values upon object creation e.g. immediately 'put' the 'position' value on AwesomeDragonImmuneToFire to the current 'get' value of 'position'?</p>
[ { "answer_id": 228232, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": true, "text": "<p>Doesn't it depend how you actually implement the inheritance in your system?</p>\n\n<p>For example, in a JavaScript version of what you describe, the <code>prototype</code> for <code>AwesomeDragonImmuneToFire</code> would normally be an <em>instance</em> of an <code>AwesomeDragon</code>, and since you'd always be working with instances, it wouldn't matter what you do to any particular <code>AwesomeDragon</code>:</p>\n\n<pre><code>function Dragon()\n{\n this.position = \"starting point\";\n}\n\nfunction AwesomeDragon()\n{\n this.awesome = true;\n}\nAwesomeDragon.prototype = new Dragon();\n\nfunction AwesomeDragonImmuneToFire()\n{\n this.immuneToFire = true;\n}\nAwesomeDragonImmuneToFire.prototype = new AwesomeDragon();\n\n&gt;&gt;&gt; var awesome = new AwesomeDragon();\n&gt;&gt;&gt; var immune = new AwesomeDragonImmuneToFire();\n&gt;&gt;&gt; awesome.position = \"flying above village\";\n&gt;&gt;&gt; immune.position;\n\"starting point\"\n&gt;&gt;&gt; immune.awesome\ntrue\n</code></pre>\n\n<p>In this example, there are no classes and all instances are just instances of <code>Object</code> which happen to know which function was used to construct them. <code>new</code> is just <a href=\"http://javascript.crockford.com/prototypal.html\" rel=\"noreferrer\">a bit of syntactic sugar</a> and using StudlyCaps for constructor functions is just a convention for functions which are intended to be used with <code>new</code>.</p>\n\n<p>The key thing is that each object has a chain of prototype objects, which is examined if you try to access an attribute which the object itself doesn't hold, as per Yegge's description of what the \"Properties Pattern\" is.</p>\n\n<p><a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model\" rel=\"noreferrer\">https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model</a></p>\n" }, { "answer_id": 231482, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>This will involve updating the 'position' property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well.</p>\n</blockquote>\n\n<p>Maybe I misunderstand but I am not sure why you think the AwesomeDragonImmuneToFire will take off as well. If they are two distinct objects and position is a property of the objects then each instance (dragon) will have their own position. Changing the position of one dragon should not affect the position of the other.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I like Steve Yegge's [Prototype Pattern example](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html) and decided to whip up a quick proof of concept example. However, I didn't really think things through. While it is great for dynamically specifying the behaviour of objects and is an easy solution to Steve's [opinionated elf](http://steve.yegge.googlepages.com/when-polymorphism-fails) example, I'm still trying to work out the best way to handle instance variables. For instance, let's say I have an AwesomeDragon object. I then want to make an AwesomeDragonImmuneToFire object so I make a new child of the AwesomeDragon (AwesomeDragonImmuneToFire inherits properties from AwesomeDragon) and 'put' "ImmuneToFire" as a property with a value of 'true'. So far so good. Now let's say I want to send my AwesomeDragon object on a tour of nearby peasant villages. This will involve updating the 'position' property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well. Is the best solution to override instance values upon object creation e.g. immediately 'put' the 'position' value on AwesomeDragonImmuneToFire to the current 'get' value of 'position'?
Doesn't it depend how you actually implement the inheritance in your system? For example, in a JavaScript version of what you describe, the `prototype` for `AwesomeDragonImmuneToFire` would normally be an *instance* of an `AwesomeDragon`, and since you'd always be working with instances, it wouldn't matter what you do to any particular `AwesomeDragon`: ``` function Dragon() { this.position = "starting point"; } function AwesomeDragon() { this.awesome = true; } AwesomeDragon.prototype = new Dragon(); function AwesomeDragonImmuneToFire() { this.immuneToFire = true; } AwesomeDragonImmuneToFire.prototype = new AwesomeDragon(); >>> var awesome = new AwesomeDragon(); >>> var immune = new AwesomeDragonImmuneToFire(); >>> awesome.position = "flying above village"; >>> immune.position; "starting point" >>> immune.awesome true ``` In this example, there are no classes and all instances are just instances of `Object` which happen to know which function was used to construct them. `new` is just [a bit of syntactic sugar](http://javascript.crockford.com/prototypal.html) and using StudlyCaps for constructor functions is just a convention for functions which are intended to be used with `new`. The key thing is that each object has a chain of prototype objects, which is examined if you try to access an attribute which the object itself doesn't hold, as per Yegge's description of what the "Properties Pattern" is. <https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model>
228,145
<p>I am progamatically creating a SharePoint site using </p> <pre><code>SPWeb spWeb = spSite.AllWebs.Add(...); </code></pre> <p>What code do I need run to set the spWeb to turn off the "Show pages in navigation" option?</p> <p><strong>Answer:</strong></p> <pre><code>publishingWeb.IncludePagesInNavigation = false; </code></pre>
[ { "answer_id": 228211, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": true, "text": "<p>Wasn't sure myself but I was able to locate <a href=\"http://msdn.microsoft.com/en-us/magazine/cc507633.aspx\" rel=\"noreferrer\">this</a>:</p>\n\n<blockquote>\n <p>Modifying navigation is another common\n branding task since it affects what\n users can see and how they can proceed\n through a site hierarchy. The\n Microsoft.SharePoint.Publishing\n namespace exposes several classes that\n target the Publishing site\n infrastructure, such as PublishingWeb\n and PublishingPage. Using these\n classes, we can easily modify\n navigation for each site. If you want\n a child Web to display as a root level\n site in global navigation, first turn\n off inheritance from the parent site,\n like so:</p>\n</blockquote>\n\n<pre><code>publishingWeb.InheritGlobalNavigation = false;\n</code></pre>\n\n<blockquote>\n <p>You might also want to hide all site\n pages from global navigation. Setting\n IncludePagesInNavigation to false\n hides all pages in the site,\n regardless of whether the\n PublishingPage.IncludeInGlobalNavigation\n property is set to true</p>\n</blockquote>\n\n<pre><code>// do not show pages in navigation\npublishingWeb.IncludePagesInNavigation = false;\n</code></pre>\n\n<blockquote>\n <p>If you are dealing with default sites\n that don't inherit from PublishingWeb,\n it's still possible to hide these\n sites from the global navigation bar.\n For example, if you create a site\n collection using the collaboration\n portal template and want to exclude\n the News site from global navigation,\n add that site to the\n __GlobalNavigationExcludes property of the site:</p>\n</blockquote>\n\n<pre><code>string globalNavExcludes = String.Empty;\nSPWeb webSite = MSDNSiteCollection.RootWeb;\n// _GlobalNavigationExcludes property contains a delimited string of \n// GUIDs identifying the Id of each site to be excluded from global\n// navigation\n\nif (webSite.AllProperties.ContainsKey(\"__GlobalNavigationExcludes\")) {\n globalNavExcludes = \n webSite.AllProperties[\"__GlobalNavigationExcludes\"].ToString();\n}\n\nSPWeb newsSite = MSDNSiteCollection.AllWebs[\"News\"];\n// string is delimited \"{GUID};{GUID};\",\n// use format code B to convert to string\nglobalNavExcludes += String.Concat(currentWeb.ID.ToString(\"B\"), \";\");\n\nwebSite.AllProperties[\"__GlobalNavigationExcludes\"] = globalNavExcludes;\nwebSite.Update();\n</code></pre>\n\n<blockquote>\n <p>Adding navigation nodes directly to an\n SPNavigationNodeCollection is a good\n way to display only the nodes you want\n as well as to group nodes and links to\n external sites. Figure 10 shows how to\n add an internal link, external link,\n and a heading to the global navigation\n bar. This example addresses some of\n the properties of the SPNavigation\n class that affect whether the link\n opens in a new window and how to\n handle empty URLs.</p>\n</blockquote>\n" }, { "answer_id": 5960885, "author": "Madhuri Dixit", "author_id": 742773, "author_profile": "https://Stackoverflow.com/users/742773", "pm_score": 2, "selected": false, "text": "<p>For SP 2010 use below...</p>\n\n<p>publishingWeb.Navigation.GlobalIncludePages = false;</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13813/" ]
I am progamatically creating a SharePoint site using ``` SPWeb spWeb = spSite.AllWebs.Add(...); ``` What code do I need run to set the spWeb to turn off the "Show pages in navigation" option? **Answer:** ``` publishingWeb.IncludePagesInNavigation = false; ```
Wasn't sure myself but I was able to locate [this](http://msdn.microsoft.com/en-us/magazine/cc507633.aspx): > > Modifying navigation is another common > branding task since it affects what > users can see and how they can proceed > through a site hierarchy. The > Microsoft.SharePoint.Publishing > namespace exposes several classes that > target the Publishing site > infrastructure, such as PublishingWeb > and PublishingPage. Using these > classes, we can easily modify > navigation for each site. If you want > a child Web to display as a root level > site in global navigation, first turn > off inheritance from the parent site, > like so: > > > ``` publishingWeb.InheritGlobalNavigation = false; ``` > > You might also want to hide all site > pages from global navigation. Setting > IncludePagesInNavigation to false > hides all pages in the site, > regardless of whether the > PublishingPage.IncludeInGlobalNavigation > property is set to true > > > ``` // do not show pages in navigation publishingWeb.IncludePagesInNavigation = false; ``` > > If you are dealing with default sites > that don't inherit from PublishingWeb, > it's still possible to hide these > sites from the global navigation bar. > For example, if you create a site > collection using the collaboration > portal template and want to exclude > the News site from global navigation, > add that site to the > \_\_GlobalNavigationExcludes property of the site: > > > ``` string globalNavExcludes = String.Empty; SPWeb webSite = MSDNSiteCollection.RootWeb; // _GlobalNavigationExcludes property contains a delimited string of // GUIDs identifying the Id of each site to be excluded from global // navigation if (webSite.AllProperties.ContainsKey("__GlobalNavigationExcludes")) { globalNavExcludes = webSite.AllProperties["__GlobalNavigationExcludes"].ToString(); } SPWeb newsSite = MSDNSiteCollection.AllWebs["News"]; // string is delimited "{GUID};{GUID};", // use format code B to convert to string globalNavExcludes += String.Concat(currentWeb.ID.ToString("B"), ";"); webSite.AllProperties["__GlobalNavigationExcludes"] = globalNavExcludes; webSite.Update(); ``` > > Adding navigation nodes directly to an > SPNavigationNodeCollection is a good > way to display only the nodes you want > as well as to group nodes and links to > external sites. Figure 10 shows how to > add an internal link, external link, > and a heading to the global navigation > bar. This example addresses some of > the properties of the SPNavigation > class that affect whether the link > opens in a new window and how to > handle empty URLs. > > >
228,165
<p>I stumbled across my rather ancient photo objects disks, and sadly found out the company (hemera) doesn't provide support for it anymore. this has left me with a whole pile of .hpi files. Luckily, I found <a href="http://www.halley.cc/ed/linux/interop/hemera.html" rel="nofollow noreferrer">this information</a> on extracting the jpg and png components of the file.</p> <p>Unfortunately, I haven't been able to get it to work. Can anyone figure out what's wrong with this code? I'd be happy with a PHP or Python solution if Perl isn't your thing. :)</p> <pre><code>open(I, "$name") || die; binmode(I); $_ = &lt;I&gt;; close(I); my ($j, $p) = m|^.{32}(.*)(\211PNG.*)$|s; open(J, "&gt;$name.jpg") &amp;&amp; do { binmode(J); print J $j; close J; }; open(P, "&gt;$name.png") &amp;&amp; do { binmode(P); print P $p; close P; }; </code></pre> <p>The hexdump of the current test file I snagged off a CD is here, if it helps at all:</p> <pre><code>0000000 89 48 50 49 0d 0a 1a 0a 64 00 00 00 20 00 00 00 0000010 45 89 00 00 65 89 00 00 0a 21 00 00 00 d0 d0 00 </code></pre>
[ { "answer_id": 228192, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 3, "selected": true, "text": "<p>It seems the regexp is wrong. That's why I wrote a little C program to do it for me:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX_SIZE 1048576\n\nchar stuff[MAX_SIZE];\n\nint main (int argc, char **argv)\n{\n unsigned int j_off, j_len, p_off, p_len;\n FILE *fp, *jp, *pp;\n fp = fopen (argv[1], \"r\");\n if (!fp) goto error;\n if (fseek (fp, 12, SEEK_SET)) goto error;\n if (!fread (&amp;j_off, 4, 1, fp)) goto error;\n if (!fread (&amp;j_len, 4, 1, fp)) goto error;\n if (!fread (&amp;p_off, 4, 1, fp)) goto error;\n if (!fread (&amp;p_len, 4, 1, fp)) goto error;\n fprintf (stderr, \"INFO %s \\t%d %d %d %d\\n\",\n argv[1], j_off, j_len, p_off, p_len);\n if (j_len &gt; MAX_SIZE || p_len &gt; MAX_SIZE) {\n fprintf (stderr, \"%s: Chunk size too big!\\n\", argv[1]);\n return EXIT_FAILURE;\n }\n\n jp = fopen (argv[2], \"w\");\n if (!jp) goto error;\n if (fseek (fp, j_off, SEEK_SET)) goto error;\n if (!fread (stuff, j_len, 1, fp)) goto error;\n if (!fwrite (stuff, j_len, 1, jp)) goto error;\n fclose (jp);\n\n pp = fopen (argv[3], \"w\");\n if (!pp) goto error;\n if (fseek (fp, p_off, SEEK_SET)) goto error;\n if (!fread (stuff, p_len, 1, fp)) goto error;\n if (!fwrite (stuff, p_len, 1, pp)) goto error;\n fclose (pp);\n fclose (fp);\n return EXIT_SUCCESS;\n\nerror:\n perror (argv[1]);\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>It works with the command line parameters input.hpi output.jpg output.png.\nThe error handling is not 100% correct, but it is good enough to always tell you if something's wrong, and most times what it is. <strong>For large files, you will have to enlarge MAX_SIZE.</strong></p>\n\n<p>Here is a shell script which you can call with *.hpi:</p>\n\n<pre><code>#!/bin/bash\n\ndest=&lt;destination-folder&gt;\n\nfor arg in \"$@\"\ndo\n base=`echo $arg | cut -d'.' -f1`\n &lt;executable&gt; $arg $dest/original/$base.jpg $dest/mask/$base.png 2&gt;&gt;$dest/log\n #composite -compose CopyOpacity $dest/mask/$base.png $dest/original/$base.jpg $dest/rgba/$base.png\ndone\n</code></pre>\n\n<p>The optional composite command (comes with ImageMagick) will create a new PNG image which has the mask applied as alpha channel. Note that this file will be about 5 times larger than the original files.</p>\n\n<p>Note that some HPI files come without mask. In this case, my program will still work, but give an empty PNG file.</p>\n" }, { "answer_id": 228259, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem extracting images from an MS Word document. Here's the program I wrote for that. It only extracts PNGs, though:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\n\nmy $HEADER = \"\\211PNG\";\nmy $FOOTER = \"IEND\\xAEB`\\x82\";\n\nforeach my $file ( @ARGV )\n {\n print \"Extracting $file\\n\";\n (my $image_base = $file) =~ s/(.*)\\..*/$1/;\n\n my $data = do { local $/; open my( $fh ), $file; &lt;$fh&gt; };\n\n my $count = 0;\n\n while( $data =~ m/($HEADER.*?$FOOTER)/sg )\n {\n my $image = $1;\n $count++;\n my $image_name = \"$image_base.$count.png\";\n open my $fh, \"&gt; $image_name\" or warn \"$image_name: $!\", next;\n print \"Writing $image_name: \", length($image), \" bytes\\n\";\n print $fh $image;\n close $fh;\n }\n\n }\n\n\n__END__\n</code></pre>\n" }, { "answer_id": 228302, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>Not a program-your-own solution, but <a href=\"http://www.xnview.com/\" rel=\"nofollow noreferrer\" title=\"xnview\">this</a> application, which is freeware for personal use, states that it can convert hpi files.</p>\n" }, { "answer_id": 4773813, "author": "Aziz K.", "author_id": 586323, "author_profile": "https://Stackoverflow.com/users/586323", "pm_score": 2, "selected": false, "text": "<p>For those arriving by Google here, I've written a Python script that solves this problem for PNG images only:</p>\n\n<pre><code>#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport re, sys\n\ndef main():\n if len(sys.argv) &lt; 2:\n print \"\"\"Usage:\n {0} BINARY_FILE PNG_PATH_TEMPLATE\nExample:\n {0} bin/program 'imgs/image.{{0:03d}}.png'\"\"\".format(__file__)\n return\n binfile, pngpath_tpl = sys.argv[1:3]\n\n rx = re.compile(\"\\x89PNG.+?IEND\\xAEB`\\x82\", re.S)\n bintext = open(binfile, \"rb\").read()\n PNGs = rx.findall(bintext)\n\n for i, PNG in enumerate(PNGs):\n f = open(pngpath_tpl.format(i), \"wb\") # Simple string format.\n f.write(PNG)\n f.close()\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n" }, { "answer_id": 10355166, "author": "sinelaw", "author_id": 562906, "author_profile": "https://Stackoverflow.com/users/562906", "pm_score": 0, "selected": false, "text": "<p>For <code>.jpeg</code> and <code>.mov</code> files there is <a href=\"http://www.rfc1149.net/devel/recoverjpeg.html\" rel=\"nofollow\">recoverjpeg</a>, which I tested on linux (but may be compatible with other platforms). </p>\n\n<p>On some debian systems it's available through <code>apt get install recoverjpeg</code></p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4853/" ]
I stumbled across my rather ancient photo objects disks, and sadly found out the company (hemera) doesn't provide support for it anymore. this has left me with a whole pile of .hpi files. Luckily, I found [this information](http://www.halley.cc/ed/linux/interop/hemera.html) on extracting the jpg and png components of the file. Unfortunately, I haven't been able to get it to work. Can anyone figure out what's wrong with this code? I'd be happy with a PHP or Python solution if Perl isn't your thing. :) ``` open(I, "$name") || die; binmode(I); $_ = <I>; close(I); my ($j, $p) = m|^.{32}(.*)(\211PNG.*)$|s; open(J, ">$name.jpg") && do { binmode(J); print J $j; close J; }; open(P, ">$name.png") && do { binmode(P); print P $p; close P; }; ``` The hexdump of the current test file I snagged off a CD is here, if it helps at all: ``` 0000000 89 48 50 49 0d 0a 1a 0a 64 00 00 00 20 00 00 00 0000010 45 89 00 00 65 89 00 00 0a 21 00 00 00 d0 d0 00 ```
It seems the regexp is wrong. That's why I wrote a little C program to do it for me: ``` #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 1048576 char stuff[MAX_SIZE]; int main (int argc, char **argv) { unsigned int j_off, j_len, p_off, p_len; FILE *fp, *jp, *pp; fp = fopen (argv[1], "r"); if (!fp) goto error; if (fseek (fp, 12, SEEK_SET)) goto error; if (!fread (&j_off, 4, 1, fp)) goto error; if (!fread (&j_len, 4, 1, fp)) goto error; if (!fread (&p_off, 4, 1, fp)) goto error; if (!fread (&p_len, 4, 1, fp)) goto error; fprintf (stderr, "INFO %s \t%d %d %d %d\n", argv[1], j_off, j_len, p_off, p_len); if (j_len > MAX_SIZE || p_len > MAX_SIZE) { fprintf (stderr, "%s: Chunk size too big!\n", argv[1]); return EXIT_FAILURE; } jp = fopen (argv[2], "w"); if (!jp) goto error; if (fseek (fp, j_off, SEEK_SET)) goto error; if (!fread (stuff, j_len, 1, fp)) goto error; if (!fwrite (stuff, j_len, 1, jp)) goto error; fclose (jp); pp = fopen (argv[3], "w"); if (!pp) goto error; if (fseek (fp, p_off, SEEK_SET)) goto error; if (!fread (stuff, p_len, 1, fp)) goto error; if (!fwrite (stuff, p_len, 1, pp)) goto error; fclose (pp); fclose (fp); return EXIT_SUCCESS; error: perror (argv[1]); return EXIT_FAILURE; } ``` It works with the command line parameters input.hpi output.jpg output.png. The error handling is not 100% correct, but it is good enough to always tell you if something's wrong, and most times what it is. **For large files, you will have to enlarge MAX\_SIZE.** Here is a shell script which you can call with \*.hpi: ``` #!/bin/bash dest=<destination-folder> for arg in "$@" do base=`echo $arg | cut -d'.' -f1` <executable> $arg $dest/original/$base.jpg $dest/mask/$base.png 2>>$dest/log #composite -compose CopyOpacity $dest/mask/$base.png $dest/original/$base.jpg $dest/rgba/$base.png done ``` The optional composite command (comes with ImageMagick) will create a new PNG image which has the mask applied as alpha channel. Note that this file will be about 5 times larger than the original files. Note that some HPI files come without mask. In this case, my program will still work, but give an empty PNG file.
228,175
<p>When using SubSonic, do you return the data as a dataset or do you put that in a strongly typed custom collection or a generic object?</p> <p>I ran through the subsonic project and for the four stored procs I have in my DB, it gave me a Sps.cs with 4 methods which return a StoredProcedure object.</p> <p>If you used a MVC, do you usually use the StoredProcedure object or wrap that around your business logic and return a dataset, list, collection or something else?</p> <p>Are datasets still the norm or is that replaced by something else?</p>
[ { "answer_id": 228190, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>If the results of the stored procedure has the same schema as one of your tables, you can build a collection using this code (SubSonic 2.1):</p>\n\n<pre><code>ProductCollection coll = new ProductCollection();\ncoll.LoadAndCloseReader(SPs.GetProducts(1).GetReader());\n</code></pre>\n" }, { "answer_id": 228198, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 2, "selected": false, "text": "<p>If my stored procedure returns all the fields from one of the tables for which I have a SubSonic object then I do a LoadAndCloseReader on the result of the stored procedure. If my stored procedure returns data that does not match a SubSonic object then I just work with it as a dataset.</p>\n" }, { "answer_id": 351551, "author": "Steven Quick", "author_id": 37493, "author_profile": "https://Stackoverflow.com/users/37493", "pm_score": 1, "selected": false, "text": "<p>Perhaps return a datareader and then iterate it to populate some custom objects. Alternatively the quick and dirty way (since you're not using domain driven design) create a view in the DB with the same structure as the stored proc, then load the result into your ViewObjectCollection similar to John's code.</p>\n" }, { "answer_id": 716884, "author": "Rick Rat", "author_id": 43754, "author_profile": "https://Stackoverflow.com/users/43754", "pm_score": 0, "selected": false, "text": "<p>You can do data readers, but that's so 1999. Returning objects is a breeze with SubSonic, and easier to use than a data reader. You can retrieve objects like so:</p>\n\n<pre><code>Dim Charts As Generic.List(Of MusicDB.Billboard) = _\n New SubSonic.Select(MusicDB.DB.Repository.Provider, New String() _\n {\"Prefix\", \"Artist\", \"Track\", \"ArtistNarrowToken\", \"TrackNarrowToken\", \"ArtistId\", \"TrackId\", \"TrackYear\"}). _\n From(MetadataTagger.MusicDB.Tables.Billboard). _\n Where(MusicDB.Billboard.Columns.ArtistNarrowToken).IsLessThan(10). _\n Or(MusicDB.Billboard.Columns.TrackId).IsNull(). _\n OrderAsc(New String() {\"TrackYear\"}).ExecuteTypedList(Of MetadataTagger.MusicDB.Billboard)()\n</code></pre>\n" }, { "answer_id": 717601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><code>ExecuteTypedList&lt;&gt;</code> is your best friend in this case:</p>\n\n<pre><code>IList&lt;Product&gt; list=SPs.GetProducts().ExecuteTypedList&lt;Product&gt;();\n</code></pre>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using SubSonic, do you return the data as a dataset or do you put that in a strongly typed custom collection or a generic object? I ran through the subsonic project and for the four stored procs I have in my DB, it gave me a Sps.cs with 4 methods which return a StoredProcedure object. If you used a MVC, do you usually use the StoredProcedure object or wrap that around your business logic and return a dataset, list, collection or something else? Are datasets still the norm or is that replaced by something else?
If the results of the stored procedure has the same schema as one of your tables, you can build a collection using this code (SubSonic 2.1): ``` ProductCollection coll = new ProductCollection(); coll.LoadAndCloseReader(SPs.GetProducts(1).GetReader()); ```
228,200
<p><code>%AX = (%AH + %AL)</code></p> <p>So why not <code>%EAX = (%SOME_REGISTER + %AX)</code> for some register <code>%SOME_REGISTER</code>? </p>
[ { "answer_id": 228231, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>In the old 8-bit days, there was the A register.</p>\n\n<p>In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.</p>\n\n<p>In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.</p>\n" }, { "answer_id": 228367, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 8, "selected": true, "text": "<p>Just for some clarification. In the early microprocessor days of the 1970's, CPUs had only a small number of registers and a very limited instruction set. Typically, the arithmetic unit could only operate on a single CPU register, often referred to as the \"accumulator\". The accumulator on the 8 bit 8080 &amp; Z80 processors was called \"A\". There were 6 other general purpose 8 bit registers: B, C, D, E, H &amp; L. These six registers could be paired up to form 3 16 bit registers: BC, DE &amp; HL. Internally, the accumulator was combined with the Flags register to form the AF 16 bit register.</p>\n\n<p>When Intel developed the 16 bit 8086 family they wanted to be able to port 8080 code, so they kept the same basic register structure:</p>\n\n<pre><code>8080/Z80 8086\nA AX\nBC BX\nDE CX\nHL DX\nIX SI \nIY DI\n</code></pre>\n\n<p>Because of the need to port 8 bit code they needed to be able to refer to the individual 8 bit parts of AX, BX, CX &amp; DX. These are called AL, AH for the low &amp; high bytes of AX and so on for BL/BH, CL/CH &amp; DL/DH. IX &amp; IY on the Z80 were only ever used as 16 bit pointer registers so there was no need to access the two halves of SI &amp; DI.</p>\n\n<p>When the 80386 was released in the mid 1980s they created \"extended\" versions of all the registers. So, AX became EAX, BX became EBX etc. There was no need to access to top 16 bits of these new extended registers, so they didn't create an EAXH pseudo register.</p>\n\n<p>AMD applied the same trick when they produced the first 64 bit processors. The 64 bit version of the AX register is called RAX. So, now you have something that looks like this:</p>\n\n<pre><code>|63..32|31..16|15-8|7-0|\n |AH.|AL.|\n |AX.....|\n |EAX............|\n|RAX...................|\n</code></pre>\n" }, { "answer_id": 32472219, "author": "Sean Werkema", "author_id": 412416, "author_profile": "https://Stackoverflow.com/users/412416", "pm_score": 5, "selected": false, "text": "<p>There are a lot of answers posted here, but none really answer the given question: Why isn't there a register that directly encodes the high 16 bits of EAX, or the high 32 bits of RAX? The answer boils down to the limitations of the x86 instruction encoding itself.</p>\n\n<p><strong>16-Bit History Lesson</strong></p>\n\n<p>When Intel designed the 8086, they used a variable-length encoding scheme for many of the instructions. This meant that certain extremely-common instructions, like <code>POP AX</code>, could be represented as a single byte (58), while rare (but still potentially useful) instructions like <code>MOV CX, [BX+SI+1023]</code> could still be represented, even if it took several bytes to store them (in this example, 8B 88 FF 03).</p>\n\n<p>This may seem like a reasonable solution, but when they designed it, <em>they filled out most of the available space</em>. So, for example, there were eight <code>POP</code> instructions for the eight individual registers (AX, CX, DX, BX, SP, BP, SI, DI), and they filled out opcodes 58 through 5F, and opcode 60 was something else entirely (<code>PUSHA</code>), as was opcode 57 (<code>PUSH DI</code>). There's no room left over for anything after or before those. Even pushing and popping the segment registers — which is conceptually nearly identical to pushing and popping the general-purpose registers — had to be encoded in a different location (down around 06/0E/16/1E) just because there wasn't room beside the rest of the push/pop instructions.</p>\n\n<p>Likewise, the \"mod r/m\" byte used for a complex instruction like <code>MOV CX, [BX+SI+1023]</code> only has three bits for encoding the register, which means it can only represent eight registers total. That's fine if you only have eight registers, but presents a real problem if you want to have more.</p>\n\n<p>(There's an excellent map of all these byte allocations in the x86 architecture here: <a href=\"https://i.imgur.com/xfeWv.png\" rel=\"nofollow noreferrer\">http://i.imgur.com/xfeWv.png</a> . Notice how there's no space left in the primary map, with some instructions overlapping bytes, and even how much of the secondary \"0F\" map is used now thanks to the MMX and SSE instructions.)</p>\n\n<p><strong>Toward 32 and 64 Bits</strong></p>\n\n<p>So to even allow the CPU design to be extended from 16 bits to 32 bits, they already had a design problem, and they solved that with <em>prefix bytes</em>: By adding a special \"66\" byte in front of all of the standard 16-bit instructions, the CPU knows you want the same instruction but the 32-bit version (EAX) instead of the 16-bit version (AX). The rest of the design stayed the same: There were still only eight total general-purpose registers in the overall CPU architecture.</p>\n\n<p>Similar hackery had to be done to extend the architecture to 64-bits (RAX and friends); there, the problem was solved by adding yet another set of prefix codes (<code>REX</code>, 40-4F) that meant \"64-bit\" (and effectively added another two bits to the \"mod r/m\" field), and also discarding weird old instructions nobody ever used and reusing their byte codes for newer stuff.</p>\n\n<p><strong>An Aside on 8-Bit Registers</strong></p>\n\n<p>One of the bigger questions to ask, then, is how the heck things like AH and AL ever worked in the first place if there's only really room in the design for eight registers. The first part of the answer is that there's no such thing as \"<code>PUSH AL</code>\" — some instructions simply can't operate on the byte-sized registers at all! The only ones that can are a few special oddities (like <code>AAD</code> and <code>XLAT</code>) and special versions of the \"mod r/m\" instructions: By having a very specific bit flipped in the \"mod r/m\" byte, those \"extended instructions\" could be flipped to operate on the 8-bit registers instead of the 16-bit ones. It just so happens that there are exactly eight 8-bit registers, too: AL, CL, DL, BL, AH, CH, DH, and BH (in that order), and that lines up very nicely with the eight register slots available in the \"mod r/m\" byte.</p>\n\n<p>Intel noted at the time that the 8086 design was supposed to be \"source compatible\" with the 8080/8085: There was an equivalent instruction in the 8086 for each of the 8080/8085 instructions, but it didn't use the same byte codes (they aren't even close), and you'd have to recompile (reassemble) your program to get it to use the new byte codes. But \"source compatible\" was a way forward for old software, and it allowed the 8085's individual A, B, C, etc. and combo \"BC\" and \"DE\" registers to still work on the new processor, even if they were now called \"AL\" and \"BL\" and \"BX\" and \"DX\" (or whatever the mapping was).</p>\n\n<p>So that's really the real answer: It's not that Intel or AMD intentionally \"left out\" a high 16-bit register for EAX, or a high 32-bit register for RAX: It's that the high 8-bit registers are a weird leftover historical anomaly, and replicating their design at higher bit sizes would be really difficult given the requirement that the architecture be backward-compatible.</p>\n\n<p><strong>A Performance Consideration</strong></p>\n\n<p>There is one other consideration as to why those \"high registers\" haven't been added since, as well: Inside modern processor architectures, for performance reasons, the variably-sized registers don't actually overlap for real: AH and AL aren't part of AX, and AX isn't a part of EAX, and EAX isn't a part of RAX: They're all separate registers under the hood, and the processor sets an invalidation flag on the others when you manipulate one of them so that it knows it will need to copy the data when you read from the others.</p>\n\n<p>(For example: If you set AL = 5, the processor doesn't update AX. But if you then read from AX, the processor quickly copies that 5 from AL into AX's bottom bits.)</p>\n\n<p>By keeping the registers separate, the CPU can do all sorts of clever things like invisible register renaming to make your code run faster, but that means that your code runs <em>slower</em> if you do use the old pattern of treating the small registers as pieces of larger registers, because the processor will have to stall and update them. To keep all of this internal bookkeeping from getting out of hand, the CPU designers wisely chose to add separate registers on the newer processors rather than to add more overlapping registers.</p>\n\n<p>(And yes, that means that it really is faster on modern processors to explicitly \"<code>MOVZX EAX, value</code>\" than to do it the old, sloppier way of \"<code>MOV AX, value / use EAX</code>\".)</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>With all that said, could Intel and AMD add more \"overlapping\" registers if they really really wanted to? Sure. There are ways to worm them in if there was enough demand. But given the significant historical baggage, the current architectural limitations, the notable performance limitations, and the fact that most code these days is generated by compilers optimized for non-overlapping registers, it's highly unlikely they'll add such things any time soon.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10432/" ]
`%AX = (%AH + %AL)` So why not `%EAX = (%SOME_REGISTER + %AX)` for some register `%SOME_REGISTER`?
Just for some clarification. In the early microprocessor days of the 1970's, CPUs had only a small number of registers and a very limited instruction set. Typically, the arithmetic unit could only operate on a single CPU register, often referred to as the "accumulator". The accumulator on the 8 bit 8080 & Z80 processors was called "A". There were 6 other general purpose 8 bit registers: B, C, D, E, H & L. These six registers could be paired up to form 3 16 bit registers: BC, DE & HL. Internally, the accumulator was combined with the Flags register to form the AF 16 bit register. When Intel developed the 16 bit 8086 family they wanted to be able to port 8080 code, so they kept the same basic register structure: ``` 8080/Z80 8086 A AX BC BX DE CX HL DX IX SI IY DI ``` Because of the need to port 8 bit code they needed to be able to refer to the individual 8 bit parts of AX, BX, CX & DX. These are called AL, AH for the low & high bytes of AX and so on for BL/BH, CL/CH & DL/DH. IX & IY on the Z80 were only ever used as 16 bit pointer registers so there was no need to access the two halves of SI & DI. When the 80386 was released in the mid 1980s they created "extended" versions of all the registers. So, AX became EAX, BX became EBX etc. There was no need to access to top 16 bits of these new extended registers, so they didn't create an EAXH pseudo register. AMD applied the same trick when they produced the first 64 bit processors. The 64 bit version of the AX register is called RAX. So, now you have something that looks like this: ``` |63..32|31..16|15-8|7-0| |AH.|AL.| |AX.....| |EAX............| |RAX...................| ```
228,205
<p>How do you handle update refresh rate from your worker function to your UI ?</p> <p>Sending everything to the UI or maybe using a timer (from which side ? worker or UI ?)</p>
[ { "answer_id": 228231, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>In the old 8-bit days, there was the A register.</p>\n\n<p>In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.</p>\n\n<p>In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.</p>\n" }, { "answer_id": 228367, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 8, "selected": true, "text": "<p>Just for some clarification. In the early microprocessor days of the 1970's, CPUs had only a small number of registers and a very limited instruction set. Typically, the arithmetic unit could only operate on a single CPU register, often referred to as the \"accumulator\". The accumulator on the 8 bit 8080 &amp; Z80 processors was called \"A\". There were 6 other general purpose 8 bit registers: B, C, D, E, H &amp; L. These six registers could be paired up to form 3 16 bit registers: BC, DE &amp; HL. Internally, the accumulator was combined with the Flags register to form the AF 16 bit register.</p>\n\n<p>When Intel developed the 16 bit 8086 family they wanted to be able to port 8080 code, so they kept the same basic register structure:</p>\n\n<pre><code>8080/Z80 8086\nA AX\nBC BX\nDE CX\nHL DX\nIX SI \nIY DI\n</code></pre>\n\n<p>Because of the need to port 8 bit code they needed to be able to refer to the individual 8 bit parts of AX, BX, CX &amp; DX. These are called AL, AH for the low &amp; high bytes of AX and so on for BL/BH, CL/CH &amp; DL/DH. IX &amp; IY on the Z80 were only ever used as 16 bit pointer registers so there was no need to access the two halves of SI &amp; DI.</p>\n\n<p>When the 80386 was released in the mid 1980s they created \"extended\" versions of all the registers. So, AX became EAX, BX became EBX etc. There was no need to access to top 16 bits of these new extended registers, so they didn't create an EAXH pseudo register.</p>\n\n<p>AMD applied the same trick when they produced the first 64 bit processors. The 64 bit version of the AX register is called RAX. So, now you have something that looks like this:</p>\n\n<pre><code>|63..32|31..16|15-8|7-0|\n |AH.|AL.|\n |AX.....|\n |EAX............|\n|RAX...................|\n</code></pre>\n" }, { "answer_id": 32472219, "author": "Sean Werkema", "author_id": 412416, "author_profile": "https://Stackoverflow.com/users/412416", "pm_score": 5, "selected": false, "text": "<p>There are a lot of answers posted here, but none really answer the given question: Why isn't there a register that directly encodes the high 16 bits of EAX, or the high 32 bits of RAX? The answer boils down to the limitations of the x86 instruction encoding itself.</p>\n\n<p><strong>16-Bit History Lesson</strong></p>\n\n<p>When Intel designed the 8086, they used a variable-length encoding scheme for many of the instructions. This meant that certain extremely-common instructions, like <code>POP AX</code>, could be represented as a single byte (58), while rare (but still potentially useful) instructions like <code>MOV CX, [BX+SI+1023]</code> could still be represented, even if it took several bytes to store them (in this example, 8B 88 FF 03).</p>\n\n<p>This may seem like a reasonable solution, but when they designed it, <em>they filled out most of the available space</em>. So, for example, there were eight <code>POP</code> instructions for the eight individual registers (AX, CX, DX, BX, SP, BP, SI, DI), and they filled out opcodes 58 through 5F, and opcode 60 was something else entirely (<code>PUSHA</code>), as was opcode 57 (<code>PUSH DI</code>). There's no room left over for anything after or before those. Even pushing and popping the segment registers — which is conceptually nearly identical to pushing and popping the general-purpose registers — had to be encoded in a different location (down around 06/0E/16/1E) just because there wasn't room beside the rest of the push/pop instructions.</p>\n\n<p>Likewise, the \"mod r/m\" byte used for a complex instruction like <code>MOV CX, [BX+SI+1023]</code> only has three bits for encoding the register, which means it can only represent eight registers total. That's fine if you only have eight registers, but presents a real problem if you want to have more.</p>\n\n<p>(There's an excellent map of all these byte allocations in the x86 architecture here: <a href=\"https://i.imgur.com/xfeWv.png\" rel=\"nofollow noreferrer\">http://i.imgur.com/xfeWv.png</a> . Notice how there's no space left in the primary map, with some instructions overlapping bytes, and even how much of the secondary \"0F\" map is used now thanks to the MMX and SSE instructions.)</p>\n\n<p><strong>Toward 32 and 64 Bits</strong></p>\n\n<p>So to even allow the CPU design to be extended from 16 bits to 32 bits, they already had a design problem, and they solved that with <em>prefix bytes</em>: By adding a special \"66\" byte in front of all of the standard 16-bit instructions, the CPU knows you want the same instruction but the 32-bit version (EAX) instead of the 16-bit version (AX). The rest of the design stayed the same: There were still only eight total general-purpose registers in the overall CPU architecture.</p>\n\n<p>Similar hackery had to be done to extend the architecture to 64-bits (RAX and friends); there, the problem was solved by adding yet another set of prefix codes (<code>REX</code>, 40-4F) that meant \"64-bit\" (and effectively added another two bits to the \"mod r/m\" field), and also discarding weird old instructions nobody ever used and reusing their byte codes for newer stuff.</p>\n\n<p><strong>An Aside on 8-Bit Registers</strong></p>\n\n<p>One of the bigger questions to ask, then, is how the heck things like AH and AL ever worked in the first place if there's only really room in the design for eight registers. The first part of the answer is that there's no such thing as \"<code>PUSH AL</code>\" — some instructions simply can't operate on the byte-sized registers at all! The only ones that can are a few special oddities (like <code>AAD</code> and <code>XLAT</code>) and special versions of the \"mod r/m\" instructions: By having a very specific bit flipped in the \"mod r/m\" byte, those \"extended instructions\" could be flipped to operate on the 8-bit registers instead of the 16-bit ones. It just so happens that there are exactly eight 8-bit registers, too: AL, CL, DL, BL, AH, CH, DH, and BH (in that order), and that lines up very nicely with the eight register slots available in the \"mod r/m\" byte.</p>\n\n<p>Intel noted at the time that the 8086 design was supposed to be \"source compatible\" with the 8080/8085: There was an equivalent instruction in the 8086 for each of the 8080/8085 instructions, but it didn't use the same byte codes (they aren't even close), and you'd have to recompile (reassemble) your program to get it to use the new byte codes. But \"source compatible\" was a way forward for old software, and it allowed the 8085's individual A, B, C, etc. and combo \"BC\" and \"DE\" registers to still work on the new processor, even if they were now called \"AL\" and \"BL\" and \"BX\" and \"DX\" (or whatever the mapping was).</p>\n\n<p>So that's really the real answer: It's not that Intel or AMD intentionally \"left out\" a high 16-bit register for EAX, or a high 32-bit register for RAX: It's that the high 8-bit registers are a weird leftover historical anomaly, and replicating their design at higher bit sizes would be really difficult given the requirement that the architecture be backward-compatible.</p>\n\n<p><strong>A Performance Consideration</strong></p>\n\n<p>There is one other consideration as to why those \"high registers\" haven't been added since, as well: Inside modern processor architectures, for performance reasons, the variably-sized registers don't actually overlap for real: AH and AL aren't part of AX, and AX isn't a part of EAX, and EAX isn't a part of RAX: They're all separate registers under the hood, and the processor sets an invalidation flag on the others when you manipulate one of them so that it knows it will need to copy the data when you read from the others.</p>\n\n<p>(For example: If you set AL = 5, the processor doesn't update AX. But if you then read from AX, the processor quickly copies that 5 from AL into AX's bottom bits.)</p>\n\n<p>By keeping the registers separate, the CPU can do all sorts of clever things like invisible register renaming to make your code run faster, but that means that your code runs <em>slower</em> if you do use the old pattern of treating the small registers as pieces of larger registers, because the processor will have to stall and update them. To keep all of this internal bookkeeping from getting out of hand, the CPU designers wisely chose to add separate registers on the newer processors rather than to add more overlapping registers.</p>\n\n<p>(And yes, that means that it really is faster on modern processors to explicitly \"<code>MOVZX EAX, value</code>\" than to do it the old, sloppier way of \"<code>MOV AX, value / use EAX</code>\".)</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>With all that said, could Intel and AMD add more \"overlapping\" registers if they really really wanted to? Sure. There are ways to worm them in if there was enough demand. But given the significant historical baggage, the current architectural limitations, the notable performance limitations, and the fact that most code these days is generated by compilers optimized for non-overlapping registers, it's highly unlikely they'll add such things any time soon.</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ]
How do you handle update refresh rate from your worker function to your UI ? Sending everything to the UI or maybe using a timer (from which side ? worker or UI ?)
Just for some clarification. In the early microprocessor days of the 1970's, CPUs had only a small number of registers and a very limited instruction set. Typically, the arithmetic unit could only operate on a single CPU register, often referred to as the "accumulator". The accumulator on the 8 bit 8080 & Z80 processors was called "A". There were 6 other general purpose 8 bit registers: B, C, D, E, H & L. These six registers could be paired up to form 3 16 bit registers: BC, DE & HL. Internally, the accumulator was combined with the Flags register to form the AF 16 bit register. When Intel developed the 16 bit 8086 family they wanted to be able to port 8080 code, so they kept the same basic register structure: ``` 8080/Z80 8086 A AX BC BX DE CX HL DX IX SI IY DI ``` Because of the need to port 8 bit code they needed to be able to refer to the individual 8 bit parts of AX, BX, CX & DX. These are called AL, AH for the low & high bytes of AX and so on for BL/BH, CL/CH & DL/DH. IX & IY on the Z80 were only ever used as 16 bit pointer registers so there was no need to access the two halves of SI & DI. When the 80386 was released in the mid 1980s they created "extended" versions of all the registers. So, AX became EAX, BX became EBX etc. There was no need to access to top 16 bits of these new extended registers, so they didn't create an EAXH pseudo register. AMD applied the same trick when they produced the first 64 bit processors. The 64 bit version of the AX register is called RAX. So, now you have something that looks like this: ``` |63..32|31..16|15-8|7-0| |AH.|AL.| |AX.....| |EAX............| |RAX...................| ```
228,218
<p>I am very new to Java. My assignment is to create my own method and then create a class to test it in. My question, do I create the method separate of the class, or within the class? If it is separate of the class, how do I get the class to access my method?</p> <p>(Are they saved as two separate files?)</p> <p>This is what I have so far, but I am getting an error that I have to initialize KILOWATT in class DWindmill. I thought I did already in the method??? Any suggestions?</p> <pre><code>//This is the method Windmill import java.util.*; import static java.lang.Math.*; class DWindmill { public static void Windmill(){ //create the method for the Windmill class int miles = 50; //int miles = 200; //int miles = 250; int KILOWATT = (miles / 50);} static Scanner console = new Scanner(System.in); { System.out.println("Enter miles per hour:"); miles = console.nextInt(); Windmill(); System.out.println(+ KILOWATT + "kilowatts"); } } </code></pre>
[ { "answer_id": 228226, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "<p>In Java, ALL methods exist within classes. So in order to create a class, you write something like:</p>\n\n<pre><code>public class MyClass {\n\n public static void Hello() {\n //This is your method!\n }\n\n public static void main (String[] args) {\n Hello(); //This is how you call your method.\n }\n}\n</code></pre>\n" }, { "answer_id": 228228, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": false, "text": "<p>For a simple assignment such as this, you can probably create your method in the same class as your class. Create a class with a static main method, which will be your programs starting point, and then create your method which will be called.</p>\n\n<p>Seems like you are quite new to programming I would take advantage of any tutorials that are offered in your program. They are usually taught by junior, senior, or grad level students, and are meant to give you a good introduction to the material, as well as give you time outside class to ask questions. Make sure you go to class, and try to read the textbook you were supposed to buy for the course. The information can often be found there.</p>\n" }, { "answer_id": 228236, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 1, "selected": false, "text": "<p>OR you can create like follows</p>\n\n<pre><code>public class MyClass {\n public int myMethod() {\n ,,,,,\n }\n}\n\npublic class myTest {\n public void testMyMethod() {\n MyClass testClass = new MyClass();\n int output = testClass.myMethod();\n . \n. \n }\n}\n</code></pre>\n\n<p>In Java, all methods need to be inside a class. You can have a separate test class or test it in the same class.</p>\n\n<p>Things can get more complicated if you use something like jUnit(www.junit.org) for unit testing your methods.</p>\n" }, { "answer_id": 228429, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p><strong>please</strong> go to class or read a textbook or something because your code illustrates\na fundamental misunderstanding of what a class is, what a method is, and\nhow to use braces for code blocks. Here is a corrected (but untested) version of\nyour code -</p>\n\n<pre><code>class Windmill\n{\n public static void main(String args[])\n {\n Scanner console = new Scanner(System.in);\n System.out.println(\"Enter miles per hour:\");\n int miles = console.nextInt();\n int KILOWATT = (miles / 50);\n System.out.println(KILOWATT + \" kilowatts\");\n }\n}\n</code></pre>\n\n<p>seriously, <a href=\"http://java.sun.com/docs/books/tutorial/getStarted/application/index.html\" rel=\"nofollow noreferrer\">anything</a> should be helpful at this point</p>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30606/" ]
I am very new to Java. My assignment is to create my own method and then create a class to test it in. My question, do I create the method separate of the class, or within the class? If it is separate of the class, how do I get the class to access my method? (Are they saved as two separate files?) This is what I have so far, but I am getting an error that I have to initialize KILOWATT in class DWindmill. I thought I did already in the method??? Any suggestions? ``` //This is the method Windmill import java.util.*; import static java.lang.Math.*; class DWindmill { public static void Windmill(){ //create the method for the Windmill class int miles = 50; //int miles = 200; //int miles = 250; int KILOWATT = (miles / 50);} static Scanner console = new Scanner(System.in); { System.out.println("Enter miles per hour:"); miles = console.nextInt(); Windmill(); System.out.println(+ KILOWATT + "kilowatts"); } } ```
For a simple assignment such as this, you can probably create your method in the same class as your class. Create a class with a static main method, which will be your programs starting point, and then create your method which will be called. Seems like you are quite new to programming I would take advantage of any tutorials that are offered in your program. They are usually taught by junior, senior, or grad level students, and are meant to give you a good introduction to the material, as well as give you time outside class to ask questions. Make sure you go to class, and try to read the textbook you were supposed to buy for the course. The information can often be found there.
228,221
<p>I know that I can insert multiple rows using a single statement, if I use the syntax in <a href="https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602">this answer</a>. </p> <p>However, one of the values I am inserting is taken from a sequence, i.e. </p> <pre><code>insert into TABLE_NAME (COL1,COL2) select MY_SEQ.nextval,'some value' from dual union all select MY_SEQ.nextval,'another value' from dual ; </code></pre> <p>If I try to run it, I get an ORA-02287 error. Is there any way around this, or should I just use a lot of INSERT statements?</p> <p>EDIT:<br> If I have to specify column names for all other columns other than the sequence, I lose the original brevity, so it's just not worth it. In that case I'll just use multiple INSERT statements.</p>
[ { "answer_id": 228264, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<p>A possibility is to create a trigger on insert to add in the correct sequence number.</p>\n" }, { "answer_id": 228266, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://www.orafaq.com/wiki/ORA-02287\" rel=\"nofollow noreferrer\">Oracle Wiki</a>, error 02287 is </p>\n\n<blockquote>\n <p>An ORA-02287 occurs when you use a sequence where it is not allowed.</p>\n</blockquote>\n\n<p>Of the places where sequences <strong>can't</strong> be used, you seem to be trying:</p>\n\n<blockquote>\n <p>In a sub-query</p>\n</blockquote>\n\n<p>So it seems you can't do multiples in the same statement.</p>\n\n<p>The solution they offer is:</p>\n\n<blockquote>\n <p>If you want the sequence value to be inserted into the column \n for every row created, then create a before insert trigger and \n fetch the sequence value in the trigger and assign it to the column </p>\n</blockquote>\n" }, { "answer_id": 228294, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 6, "selected": true, "text": "<p>This works:</p>\n\n<pre><code>insert into TABLE_NAME (COL1,COL2)\nselect my_seq.nextval, a\nfrom\n(SELECT 'SOME VALUE' as a FROM DUAL\n UNION ALL\n SELECT 'ANOTHER VALUE' FROM DUAL)\n</code></pre>\n" }, { "answer_id": 228310, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "<pre><code>insert into TABLE_NAME\n(COL1,COL2)\nWITH\ndata AS\n(\n select 'some value' x from dual\n union all\n select 'another value' x from dual\n)\nSELECT my_seq.NEXTVAL, x \nFROM data\n;\n</code></pre>\n\n<p>I think that is what you want, but i don't have access to oracle to test it right now.</p>\n" }, { "answer_id": 237634, "author": "Dilshod Tadjibaev", "author_id": 29122, "author_profile": "https://Stackoverflow.com/users/29122", "pm_score": 5, "selected": false, "text": "<p>It does not work because sequence does not work in following scenarios:</p>\n\n<ul>\n<li>In a WHERE clause</li>\n<li>In a GROUP BY or ORDER BY clause</li>\n<li>In a DISTINCT clause</li>\n<li>Along with a UNION or INTERSECT or MINUS</li>\n<li>In a sub-query </li>\n</ul>\n\n<p>Source: <a href=\"http://www.orafaq.com/wiki/ORA-02287\" rel=\"noreferrer\">http://www.orafaq.com/wiki/ORA-02287</a></p>\n\n<p>However this does work:</p>\n\n<pre><code>insert into table_name\n (col1, col2)\n select my_seq.nextval, inner_view.*\n from (select 'some value' someval\n from dual\n union all\n select 'another value' someval\n from dual) inner_view;\n</code></pre>\n\n<hr>\n\n<p>Try it out:</p>\n\n<pre><code>create table table_name(col1 varchar2(100), col2 varchar2(100));\n\ncreate sequence vcert.my_seq\nstart with 1\nincrement by 1\nminvalue 0;\n\nselect * from table_name;\n</code></pre>\n" }, { "answer_id": 11580817, "author": "Mordred", "author_id": 1540960, "author_profile": "https://Stackoverflow.com/users/1540960", "pm_score": 0, "selected": false, "text": "<p>this works and there is no need to use union all.</p>\n\n<pre><code>Insert into BARCODECHANGEHISTORY (IDENTIFIER,MESSAGETYPE,FORMERBARCODE,NEWBARCODE,REPLACEMENTDATETIME,OPERATORID,REASON)\nselect SEQ_BARCODECHANGEHISTORY.nextval, MESSAGETYPE, FORMERBARCODE, NEWBARCODE, REPLACEMENTDATETIME, OPERATORID, REASON\nfrom (\n SELECT\n 'BAR' MESSAGETYPE,\n '1234567890' FORMERBARCODE,\n '1234567899' NEWBARCODE,\n to_timestamp('20/07/12','DD/MM/RR HH24:MI:SSXFF') REPLACEMENTDATETIME,\n 'PIMATD' OPERATORID,\n 'CORRECTION' REASON\n FROM dual\n);\n</code></pre>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/228221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
I know that I can insert multiple rows using a single statement, if I use the syntax in [this answer](https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602). However, one of the values I am inserting is taken from a sequence, i.e. ``` insert into TABLE_NAME (COL1,COL2) select MY_SEQ.nextval,'some value' from dual union all select MY_SEQ.nextval,'another value' from dual ; ``` If I try to run it, I get an ORA-02287 error. Is there any way around this, or should I just use a lot of INSERT statements? EDIT: If I have to specify column names for all other columns other than the sequence, I lose the original brevity, so it's just not worth it. In that case I'll just use multiple INSERT statements.
This works: ``` insert into TABLE_NAME (COL1,COL2) select my_seq.nextval, a from (SELECT 'SOME VALUE' as a FROM DUAL UNION ALL SELECT 'ANOTHER VALUE' FROM DUAL) ```