qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
72,381 | <p>I'm trying to use the following code but it's returning the wrong day of month.</p>
<pre><code>Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
</code></pre>
| [{'answer_id': 72411, 'author': 'Stephen Wrighton', 'author_id': 7516, 'author_profile': 'https://Stackoverflow.com/users/7516', 'pm_score': 2, 'selected': False, 'text': '<p>I would create a date object for the first day of the NEXT month, and then just subtract a single day from the date object.</p>\n'}, {'answer_id': 72438, 'author': 'Argelbargel', 'author_id': 2992, 'author_profile': 'https://Stackoverflow.com/users/2992', 'pm_score': 5, 'selected': True, 'text': '<p>Get the number of days for this month:</p>\n\n<p><pre><code>\nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\nint noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);\n</pre></code></p>\n\n<p>Set the Calendar to the last day of this month:</p>\n\n<p><pre><code>\nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n</pre></code></p>\n'}, {'answer_id': 72460, 'author': 'Peter Hilton', 'author_id': 2670, 'author_profile': 'https://Stackoverflow.com/users/2670', 'pm_score': 2, 'selected': False, 'text': '<p>It looks like you set the calendar to the first day of the next month, so you need one more line to subtract one day, to get the last day of the month that <em>sampleDay</em> is in:</p>\n\n<pre><code>Calendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.roll(Calendar.MONTH, true);\ncal.set(Calendar.DAY_OF_MONTH, 0);\ncal.add(Calendar.DAY_OF_MONTH, -1);\n</code></pre>\n\n<p>In general, it\'s much easier to do this kind of thing using <a href="http://joda-time.sourceforge.net/" rel="nofollow noreferrer">Joda Time</a>, eg:</p>\n\n<pre><code>DateTime date = new DateTime(sampleDay.getTime());\nreturn date.plusMonths(1).withDayOfMonth(0).minusDays(1).getMillis();\n</code></pre>\n'}, {'answer_id': 72526, 'author': 'paul', 'author_id': 11249, 'author_profile': 'https://Stackoverflow.com/users/11249', 'pm_score': 2, 'selected': False, 'text': '<p>Use calObject.getActualMaximum(calobject.DAY_OF_MONTH)</p>\n\n<p>See <a href="http://www.rgagnon.com/javadetails/java-0098.html" rel="nofollow noreferrer">Real\'s Java How-to</a> for more info on this.</p>\n'}, {'answer_id': 4981993, 'author': 'John', 'author_id': 157080, 'author_profile': 'https://Stackoverflow.com/users/157080', 'pm_score': 1, 'selected': False, 'text': '<p>If you use the <a href="http://www.date4j.net" rel="nofollow">date4j</a> library:</p>\n\n<pre><code>DateTime monthEnd = dt.getEndOfMonth();\n</code></pre>\n'}, {'answer_id': 13409132, 'author': 'Nick', 'author_id': 1828375, 'author_profile': 'https://Stackoverflow.com/users/1828375', 'pm_score': -1, 'selected': False, 'text': "<p>I think this should work nicely:</p>\n\n<pre><code>Dim MyDate As Date = #11/14/2012# 'This is just an example date\n\nMyDate = MyDate.AddDays(DateTime.DaysInMonth(MyDate.Year, MyDate.Month) - MyDate.Day)\n</code></pre>\n"}, {'answer_id': 38032903, 'author': 'Basil Bourque', 'author_id': 642706, 'author_profile': 'https://Stackoverflow.com/users/642706', 'pm_score': 2, 'selected': False, 'text': '<h1>tl;dr</h1>\n\n<pre><code>YearMonth.from(\n LocalDate.now( ZoneId.of( "America/Montreal" ) )\n).atEndOfMonth()\n</code></pre>\n\n<h1>java.time</h1>\n\n<p>The Question and other Answers use old outmoded classes. They have been supplanted by the <a href="http://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. See <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="nofollow noreferrer">Oracle Tutorial</a>. Much of the functionality has been back-ported to Java 6 & 7 in <a href="http://www.threeten.org/threetenbp/" rel="nofollow noreferrer">ThreeTen-Backport</a> and further adapted to Android in <a href="https://github.com/JakeWharton/ThreeTenABP" rel="nofollow noreferrer">ThreeTenABP</a>.</p>\n\n<h2><code>LocalDate</code></h2>\n\n<p>The <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="nofollow noreferrer"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone. While these objects store no time zone, note that time zone is crucial in determining the current date. For any given moment the date varies around the globe by time zone.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of( "America/Montreal" );\nLocalDate today = LocalDate.now( zoneId ); // 2016-06-25\n</code></pre>\n\n<h2><code>YearMonth</code></h2>\n\n<p>Combine with the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html" rel="nofollow noreferrer"><code>YearMonth</code></a> class to determine last day of any month.</p>\n\n<pre><code>YearMonth currentYearMonth = YearMonth.from( today ); // 2016-06\nLocalDate lastDayOfCurrentYearMonth = currentYearMonth.atEndOfMonth(); // 2016-06-30\n</code></pre>\n\n<p>By the way, both <code>LocalDate</code> and <code>YearMonth</code> use month numbers as you would expect (1-12) rather than the screwball 0-11 seen in the old date-time classes. One of many poor design decisions that make those old date-time classes so troublesome and confusing.</p>\n\n<h1><code>TemporalAdjuster</code></h1>\n\n<p>Another valid approach is using a <a href="https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjuster.html" rel="nofollow noreferrer"><code>TemporalAdjuster</code></a>.\n See <a href="https://stackoverflow.com/a/46914556/642706">the correct Answer by Pierre Henry</a>.</p>\n'}, {'answer_id': 46914556, 'author': 'Pierre Henry', 'author_id': 315677, 'author_profile': 'https://Stackoverflow.com/users/315677', 'pm_score': 2, 'selected': False, 'text': '<h1><code>TemporalAdjuster</code></h1>\n\n<p>Using the (relatively) <strong>new Java date API</strong>, it is actually very easy :</p>\n\n<p>Let <code>date</code> be an instance of <code>LocalDate</code>, for example :</p>\n\n<pre><code>LocalDate date = LocalDate.of(2018, 1, 22);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>LocalDate date = LocalDate.now();\n</code></pre>\n\n<p>or, of course, you could get it as a user input, from a database, etc.</p>\n\n<p>Then apply an implementation of the <a href="https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjuster.html" rel="nofollow noreferrer"><code>TemporalAdjuster</code></a> interface found in the <a href="https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjusters.html" rel="nofollow noreferrer"><code>TemporalAdjusters</code></a> class:</p>\n\n<pre><code>LocalDate first = date.with(TemporalAdjusters.firstDayOfMonth());\nLocalDate last = date.with(TemporalAdjusters.lastDayOfMonth());\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2443/'] |
72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:</p>
<pre><code>result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`
</code></pre>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| [{'answer_id': 72449, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Are you using the <code>re.match()</code> or <code>re.search()</code> method? My understanding is that <code>re.match()</code> assumes a "<code>^</code>" at the beginning of your expression and will only search at the beginning of the text, while <code>re.search()</code> acts more like the Perl regular expressions and will only match the beginning of the text if you include a "<code>^</code>" at the beginning of your expression. Hope that helps.</p>\n'}, {'answer_id': 72470, 'author': 'zweiterlinde', 'author_id': 6592, 'author_profile': 'https://Stackoverflow.com/users/6592', 'pm_score': 5, 'selected': True, 'text': '<p>In Python, there\'s a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.</p>\n\n<p><a href="http://docs.python.org/lib/module-re.html" rel="noreferrer">Python regex docs</a><br>\n<a href="http://docs.python.org/lib/matching-searching.html" rel="noreferrer">Matching vs searching</a></p>\n'}, {'answer_id': 72501, 'author': 'Aaron Maenpaa', 'author_id': 2603, 'author_profile': 'https://Stackoverflow.com/users/2603', 'pm_score': 2, 'selected': False, 'text': '<pre><code>>>> import re\n>>> pattern = re.compile("url")\n>>> string = " url"\n>>> pattern.match(string)\n>>> pattern.search(string)\n<_sre.SRE_Match object at 0xb7f7a6e8>\n</code></pre>\n'}, {'answer_id': 78072, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 2, 'selected': False, 'text': "<pre><code>from BeautifulSoup import BeautifulSoup \n\nsoup = BeautifulSoup(your_html)\nfor a in soup.findAll('a', href=True):\n # do something with `a` w/ href attribute\n print a['href']\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/'] |
72,410 | <p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p>
<p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p>
<p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p>
<p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p>
<hr>
<p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p>
<p>Google will help me with translating the text, but not storing/presenting it.</p>
<p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p>
<hr>
<p>Any thoughts on serving up content in the following ways, and which is best?</p>
<ul>
<li><a href="http://www.website.com/text/view.asp?id=12345&lang=fr" rel="nofollow noreferrer">http://www.website.com/text/view.asp?id=12345&lang=fr</a></li>
<li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow noreferrer">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li>
<li><a href="http://fr.website.com/text/12345" rel="nofollow noreferrer">http://fr.website.com/text/12345</a></li>
</ul>
<p>(these are not real URLs, i was just showing examples)</p>
| [{'answer_id': 72451, 'author': 'SaaS Developer', 'author_id': 7215, 'author_profile': 'https://Stackoverflow.com/users/7215', 'pm_score': 1, 'selected': False, 'text': '<p>If you are using .Net, I would recommend going with one or more resource files (.resx). There is plenty of documentation on this on MSDN.</p>\n'}, {'answer_id': 72473, 'author': 'Michael Pliskin', 'author_id': 9777, 'author_profile': 'https://Stackoverflow.com/users/9777', 'pm_score': 2, 'selected': False, 'text': '<p>You might want to check <a href="http://www.gnu.org/software/gettext/" rel="nofollow noreferrer">GNU Gettext</a> project out - at least something to start with.</p>\n\n<p><em>Edited to add info about projects:</em></p>\n\n<p>I\'ve worked on several multilingual projects using Gettext technology in different technologies, including C++/MFC and J2EE/JSP, and it worked all fine. However, you need to write/find your own code to display the localized data of course.</p>\n'}, {'answer_id': 72524, 'author': 'Dr. Bob', 'author_id': 12182, 'author_profile': 'https://Stackoverflow.com/users/12182', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re just worried about the article content being translated, and do not need a fully integrated option, I have used <a href="http://www.google.com/language_tools" rel="nofollow noreferrer">google translation</a> in the past and it works great on a smaller scale.</p>\n'}, {'answer_id': 73406, 'author': 'Rich McCollister', 'author_id': 9306, 'author_profile': 'https://Stackoverflow.com/users/9306', 'pm_score': 1, 'selected': False, 'text': "<p>As with most general programming questions, it depends on your needs. </p>\n\n<p>For static text, I would use RESX files. For me, as .Net programmer, they are easy to use and the .Net Framework has good support for them. </p>\n\n<p>For any dynamic text, I tend to store such information in the database, especially if the site maintainer is going to be a non-developer. In the past I've used two approaches, adding a language column and creating different entries for the different languages or creating a separate table to store the language specific text. </p>\n\n<p>The table for the first approach might look something like this:</p>\n\n<p>Article Id | Language Id | Language Specific Article Text | Created By | Created Date</p>\n\n<p>This works for situations where you can create different entries for a given article and you don't need to keep any data associated with these different entries in sync (such as an Updated timestamp). </p>\n\n<p>The other approach is to have two separate tables, one for non-language specific text (id, created date, created user, updated date, etc) and another table containing the language specific text. So the tables might look something like this:</p>\n\n<p>First Table: Article Id | Created By | Created Date | Updated By | Updated Date</p>\n\n<p>Second Table: Article Id | Language Id | Language Specific Article Text</p>\n\n<p>For me, the question comes down to updating the non-language dependent data. If you are updating that data then I would lean towards the second approach, otherwise I would go with the first approach as I view that as simpler (can't forget the KISS principle).</p>\n"}, {'answer_id': 120364, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': True, 'text': '<p>Firstly put all code for all languages under one domain - it will help your google-rank.</p>\n\n<p>We have a fully multi-lingual system, with localisations stored in a database but cached with the web application.</p>\n\n<p>Wherever we want a localisation to appear we use:</p>\n\n<pre><code><%$ Resources: LanguageProvider, Path/To/Localisation %>\n</code></pre>\n\n<p>Then in our web.config:</p>\n\n<pre><code><globalization resourceProviderFactoryType="FactoryClassName, AssemblyName"/>\n</code></pre>\n\n<p><code>FactoryClassName</code> then implements <code>ResourceProviderFactory</code> to provide the actual dynamic functionality. Localisations are stored in the DB with a string key "Path/To/Localisation"</p>\n\n<p>It is important to cache the localised values - you don\'t want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues.</p>\n\n<p>Use the user\'s current browser localisation to choose what language to serve up.</p>\n'}, {'answer_id': 933114, 'author': 'ilya n.', 'author_id': 115200, 'author_profile': 'https://Stackoverflow.com/users/115200', 'pm_score': 0, 'selected': False, 'text': "<p>Wonderful question. </p>\n\n<p>I solved this problem for the website I made (link in my profile) with a homemade Python 3 script that translates the general template on the fly and inserts a specific content page from a language requested (or guessed by Apache from Accept-Language).</p>\n\n<p>It was fun since I got to learn Python and write my own mini-library for creating content pages. One downside was that our hosting didn't have Python 3, but I made my script generate static HTML (the original one was examining User-agent) and then upload it to server. That works so far and making a new language version of the site is now a breeze :)</p>\n\n<p>The biggest downside of this method is that it is time-consuming to write things from scratch. So if you want, drop me line and I'll help you use my script :)</p>\n"}, {'answer_id': 933135, 'author': 'ilya n.', 'author_id': 115200, 'author_profile': 'https://Stackoverflow.com/users/115200', 'pm_score': 0, 'selected': False, 'text': '<p>As for the URL format, I use <code>site.com/content/example.fr</code> since this allows Apache to perform language negotiation in case somebody asks for <code>/content/example</code> and has a browser tell that it likes French language. When you do this Apache also adds <code>.html</code> or whatever as a bonus.</p>\n\n<p>So when a request is for <code>example</code> and I have files </p>\n\n<pre><code>example.fr\nexample.en\nexample.vi\n</code></pre>\n\n<p>Apache will automatically proceed with <code>example.vi</code> for a person with Vietnamese-configured browser or <code>example.en</code> for a person with German-configured browser. Pretty useful. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11461/'] |
72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| [{'answer_id': 72498, 'author': 'mmaibaum', 'author_id': 12213, 'author_profile': 'https://Stackoverflow.com/users/12213', 'pm_score': 0, 'selected': False, 'text': '<p>If I recall correctly in that test framework the setUp method is run before each test</p>\n'}, {'answer_id': 72504, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 4, 'selected': False, 'text': '<p>From <a href="http://docs.python.org/lib/minimal-example.html" rel="noreferrer">http://docs.python.org/lib/minimal-example.html</a> :</p>\n\n<blockquote>\n <p>When a setUp() method is defined, the\n test runner will run that method prior\n to each test.</p>\n</blockquote>\n\n<p>So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.</p>\n'}, {'answer_id': 72702, 'author': 'Jon Homan', 'author_id': 7589, 'author_profile': 'https://Stackoverflow.com/users/7589', 'pm_score': -1, 'selected': False, 'text': '<p>The setUp method, as everyone else has said, runs before every test method you write. So, when testB runs, the value of i is 1, not 3.</p>\n\n<p>You can also use a tearDown method which runs after every test method. However if one of your tests crashes, your tearDown method will never run.</p>\n'}, {'answer_id': 73791, 'author': 'Sebastian Rittau', 'author_id': 7779, 'author_profile': 'https://Stackoverflow.com/users/7779', 'pm_score': 4, 'selected': True, 'text': '<p>Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.</p>\n\n<p>Additionally, as others have pointed out, setUp is called before each test.</p>\n'}, {'answer_id': 215576, 'author': 'Roman Plášil', 'author_id': 16590, 'author_profile': 'https://Stackoverflow.com/users/16590', 'pm_score': 0, 'selected': False, 'text': '<p>From a methodological point of view, individual tests should be independent, otherwise it can produce more hard-to-find bugs. Imagine for instance that testA and testB would be called in a different order.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9510/'] |
72,442 | <p>I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?</p>
<p>Currently I use this solution, but I think there might be a better way.</p>
<pre><code> Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return (New Nullable(Of Integer)).Value
End If
End Get
End Property
</code></pre>
| [{'answer_id': 72465, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 4, 'selected': True, 'text': '<p>Are you looking for the keyword "Nothing"?</p>\n'}, {'answer_id': 72542, 'author': 'Luca Molteni', 'author_id': 4206, 'author_profile': 'https://Stackoverflow.com/users/4206', 'pm_score': 2, 'selected': False, 'text': '<p>Yes, it\'s Nothing in VB.NET, or null in C#.</p>\n\n<p>The Nullable generic datatype give the compiler the possibility to assign a "Nothing" (or null" value to a value type. Without explicitally writing it, you can\'t do it.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx" rel="nofollow noreferrer">Nullable Types in C#</a></p>\n'}, {'answer_id': 78272, 'author': 'gregmac', 'author_id': 7913, 'author_profile': 'https://Stackoverflow.com/users/7913', 'pm_score': 1, 'selected': False, 'text': '<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString("rid") <> "" Then\n Return CInt(Current.Request.QueryString("rid"))\n Else\n Return Nothing\n End If\n End Get\nEnd Property\n</code></pre>\n'}, {'answer_id': 439923, 'author': 'Barbaros Alp', 'author_id': 51734, 'author_profile': 'https://Stackoverflow.com/users/51734', 'pm_score': 0, 'selected': False, 'text': '<p>Or this is the way i use, to be honest ReSharper has taught me :)</p>\n\n<pre><code>finder.Advisor = ucEstateFinder.Advisor == "-1" ? (long?)null : long.Parse(ucEstateFinder.Advisor);\n</code></pre>\n\n<p>On the assigning above if i directly assign null to finder.Advisor*(long?)* there would be no problem. But if i try to use if clause i need to cast it like that <code>(long?)null</code>.</p>\n'}, {'answer_id': 21494597, 'author': 'Mark Hurd', 'author_id': 256431, 'author_profile': 'https://Stackoverflow.com/users/256431', 'pm_score': 0, 'selected': False, 'text': '<p>Although <code>Nothing</code> can be used, your "existing" code is almost correct; just don\'t attempt to get the <code>.Value</code>:</p>\n\n<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString("rid") <> "" Then\n Return CInt(Current.Request.QueryString("rid"))\n Else\n Return New Nullable(Of Integer)\n End If\n End Get\nEnd Property\n</code></pre>\n\n<p>This then becomes the simplest solution if you happen to want to reduce it to a <code>If</code> expression:</p>\n\n<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n Return If(Current.Request.QueryString("rid") <> "", _\n CInt(Current.Request.QueryString("rid")), _\n New Nullable(Of Integer))\n End Get\nEnd Property\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6776/'] |
72,456 | <p>Sorry for the Windows developers out there, this solution is for Macs only.</p>
<p>This set of applications accounts for: Usability Testing, Screen Capture (Video and Still), Version Control, Task Lists, Bug Tracking, a Developer IDE, a Web Server, A Blog, Shared Doc Editing on the Web, Team and individual Chat, Email, Databases and Continuous Integration. This does assume your team members provide their own machines, and one person has a spare old computer to be the Source Repository and Web Server. All for under $200 bucks.</p>
<p><strong>Usability</strong></p>
<p><a href="http://silverbackapp.com/" rel="nofollow noreferrer">Silverback</a> </p>
<p>Licenses = 3 x $49.95</p>
<p>"Spontaneous, unobtrusive usability testing software for designers and developers."</p>
<p><strong>Source Control Server and Clients (multiple options)</strong></p>
<p><a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a> = Free</p>
<p>Subversion is an open source version control system.</p>
<p><a href="http://versionsapp.com/" rel="nofollow noreferrer">Versions</a> (Currently in Beta) = Free</p>
<p>Versions provides a pleasant work with Subversion on your Mac.</p>
<p><a href="http://lucidmac.com/products/diffly" rel="nofollow noreferrer">Diffly</a> = Free</p>
<p>"Diffly is a tool for exploring Subversion working copies. It shows all files with changes and, clicking on a file, shows a highlighted view of the changes for that file. When you are ready to commit Diffly makes it easy to select the files you want to check-in and assemble a useful commit message."</p>
<p><strong>Bug/Feature/Defect Tracking (multiple options)</strong></p>
<p><a href="http://www.bugzilla.org/" rel="nofollow noreferrer">Bugzilla</a> = Free</p>
<p>Bugzilla is a "Defect Tracking System" or "Bug-Tracking System". Defect Tracking Systems allow individual or groups of developers to keep track of outstanding bugs in their product effectively. Most commercial defect-tracking software vendors charge enormous licensing fees.</p>
<p><a href="http://trac.edgewall.org/" rel="nofollow noreferrer">Trac</a> = Free</p>
<p>Trac is an enhanced wiki and issue tracking system for software development projects.</p>
<p><strong>Database Server & Clients</strong></p>
<p><a href="http://dev.mysql.com/downloads/mysql/?rz=gdl#downloads" rel="nofollow noreferrer">MySQL</a> = Free</p>
<p><a href="http://cocoamysql.sourceforge.net/" rel="nofollow noreferrer">CocoaMySQL</a> = Free</p>
<p><strong>Web Server</strong></p>
<p><a href="http://apache.org/" rel="nofollow noreferrer">Apache</a> = Free</p>
<p><strong>Development and Build Tools</strong></p>
<p><a href="http://www.apple.com/macosx/features/300.html#xcode3" rel="nofollow noreferrer">XCode</a> = Free</p>
<p><a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a> = Free</p>
<p>CruiseControl is a framework for a continuous build process. It includes, but is not limited to, plugins for email notification, Ant, and various source control tools. A web interface is provided to view the details of the current and previous builds.</p>
<p><strong>Collaboration Tools</strong></p>
<p><a href="http://www.writeboard.com/" rel="nofollow noreferrer">Writeboard</a> = Free</p>
<p><a href="http://www.tadalist.com/" rel="nofollow noreferrer">Ta-da List</a> = Free</p>
<p><a href="https://signup.37signals.com/campfire/free/signup/new" rel="nofollow noreferrer">Campfire Chat</a> for 4 users = Free</p>
<p><a href="http://wordpress.org/download/" rel="nofollow noreferrer">WordPress</a> = Free</p>
<p>"WordPress is a state-of-the-art publishing platform with a focus on aesthetics, web standards, and usability. WordPress is both free and priceless at the same time."</p>
<p><a href="http://www.gmail.com/" rel="nofollow noreferrer">Gmail</a> = Free</p>
<p>"Gmail is a new kind of webmail, built on the idea that email can be more intuitive, efficient, and useful."</p>
<p><strong>Screen Capture (Video / Still)</strong></p>
<p><a href="http://www.jingproject.com/" rel="nofollow noreferrer">Jing</a> = Free</p>
<p>"The concept of Jing is the always-ready program that instantly captures and shares images and video…from your computer to anywhere."</p>
<hr>
<p><strong>Lots of great responses:</strong></p>
<p>TeamCity [Yo|||]</p>
<p>Skype [Eric DeLabar]</p>
<p>FogBugz [chakrit]</p>
<p>IChatAV and Screen Sharing (built-in to OS) [amrox]</p>
<p>Google Docs [amrox]</p>
<hr>
| [{'answer_id': 72543, 'author': 'Steve McLeod', 'author_id': 2959, 'author_profile': 'https://Stackoverflow.com/users/2959', 'pm_score': 0, 'selected': False, 'text': "<p>Change CruiseControl for JetBrains' TeamCity. It's free for up to 20 users, and is more powerful and usable than CruiseControl.</p>\n\n<p>It's easy to set up, and has some amazing features. Such as automatically sending off a build to be performed on any spare computer you may have sitting around in the office.</p>\n"}, {'answer_id': 72548, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 0, 'selected': False, 'text': '<p>How do you do time tracking/scheduling/release planning?</p>\n\n<p>Those that help you ship on time? ala FogBugz</p>\n'}, {'answer_id': 72581, 'author': 'Eric DeLabar', 'author_id': 7556, 'author_profile': 'https://Stackoverflow.com/users/7556', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Collaboration Tools</strong></p>\n\n<p><a href="http://www.skype.com/" rel="nofollow noreferrer">Skype</a> = Free - If you can\'t work face-to-face a tool like Skype can get you pretty close for no cost assuming everybody already has broadband. The mac client works great and since most modern macs have a camera already you should be mostly set.</p>\n'}, {'answer_id': 74265, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Trac and Subversion have a pretty nice integration that lets you link Trac tickets to SVN change sets and vice-versa (SVN change sets can actually move a Trac ticket to a new state).</p>\n'}, {'answer_id': 74346, 'author': 'amrox', 'author_id': 4468, 'author_profile': 'https://Stackoverflow.com/users/4468', 'pm_score': 0, 'selected': False, 'text': '<p>Some built-in Leopard tools that I find useful are iChat AV and Screen Sharing.</p>\n\n<p>Also, Google Docs, especially spreadsheets and forms are nice (and free).</p>\n'}, {'answer_id': 78068, 'author': 'ran6110', 'author_id': 14248, 'author_profile': 'https://Stackoverflow.com/users/14248', 'pm_score': 4, 'selected': True, 'text': "<p>You've got most of it covered.</p>\n\n<p>I always add space, time and money for 2 more things you might consider strange.</p>\n\n<ol>\n<li><p>A machine set up just like the average user. No development or debugging tools installed. Make it look like someone just bought it from the Apple store. I do image switching but I've know people who swear by switching to an external boot drive.</p></li>\n<li><p>Also include a 'free' lunch for a virgin. This is someone to come in and test your program that is NOT a developer and doesn't know squat about your software. You might have to do this more than once but don't ever use the same person again.</p></li>\n</ol>\n\n<p>As an added note, make very sure the 'free' applications and web sites you use are truly free, not just free for personal use!</p>\n\n<p>Good luck on your project!</p>\n"}, {'answer_id': 101445, 'author': 'Paul A. Hoadley', 'author_id': 18493, 'author_profile': 'https://Stackoverflow.com/users/18493', 'pm_score': 0, 'selected': False, 'text': '<ul>\n<li><strong>Version control</strong>: <a href="http://www.apple.com/downloads/macosx/development_tools/svnx.html" rel="nofollow noreferrer">svnX</a> is a <em>free</em> GUI-based Subversion client.</li>\n<li><strong>RDBMS</strong>: <a href="http://postgresql.org/" rel="nofollow noreferrer">PostgreSQL</a> is a <em>free</em> relational database with a track record stretching back a couple of <em>decades</em>. It\'s <a href="http://developer.apple.com/internet/opensource/postgres.html" rel="nofollow noreferrer">easily installed on OS X</a>.</li>\n<li><strong>IDE</strong>: If (and possibly only if) you\'re coding Java, <a href="http://www.eclipse.org/" rel="nofollow noreferrer">Eclipse</a> is an unbeatable (and <em>free</em>) IDE for Java (and other platforms, though I\'m not vouching for anything other than it\'s Java ability).</li>\n<li><strong>Screencasting</strong>: <a href="http://www.flip4mac.com/screenflow.htm" rel="nofollow noreferrer">ScreenFlow</a> is outstanding at $US 99.</li>\n</ul>\n'}, {'answer_id': 2796608, 'author': 'Tim', 'author_id': 10755, 'author_profile': 'https://Stackoverflow.com/users/10755', 'pm_score': 1, 'selected': False, 'text': '<p>Consider hudson as a CI server</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6943/'] |
72,458 | <p><strong>Problem</strong></p>
<p>I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions.</p>
<p>I would like the URL to which certain requests are redirected to include the HTTP_HOST such that I don't have to create a custom .htaccess file for each host.</p>
<p><strong>Host-specific Example (snipped from .htaccess file)</strong></p>
<pre><code>Redirect /terms http://support.dev01.example.com/articles/terms/
</code></pre>
<p>This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place.</p>
<p><strong>Ideal rule (not sure of the correct syntax)</strong></p>
<pre><code>Redirect /terms http://support.{HTTP_HOST}/articles/terms/
</code></pre>
<p>This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result.</p>
<p><strong>Answers?</strong></p>
<ul>
<li>Can this be done with mod_alias or does it require the more complex mod_rewrite?</li>
<li>How can this be achieved using mod_alias or mod_rewrite? I'd prefer a mod_alias solution if possible.</li>
</ul>
<p><strong>Clarifications</strong></p>
<p>I'm not staying on the same server. I'd like:</p>
<ul>
<li>http://<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li>http://<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
</ul>
<p>I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP_HOST as a variable rather than specifying it literally in the URL to which requests are redirected.</p>
<p>I'll investigate the HTTP_HOST parameter as suggested but was hoping for a working example.</p>
| [{'answer_id': 72530, 'author': 'Nicholas', 'author_id': 8054, 'author_profile': 'https://Stackoverflow.com/users/8054', 'pm_score': -1, 'selected': False, 'text': '<p>According to this cheatsheet ( <a href="http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/" rel="nofollow noreferrer">http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/</a> ) this should work</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\.domain\\.com$ [NC]\nRewriteRule ^(.*)$ http://www.domain2.com/$1\n</code></pre>\n\n<p>Note that i don\'t have a way to test this so this should be taken as a pointer in the right direction as opposed to an explicit answer.</p>\n'}, {'answer_id': 72597, 'author': 'Colonel Sponsz', 'author_id': 11651, 'author_profile': 'https://Stackoverflow.com/users/11651', 'pm_score': -1, 'selected': False, 'text': "<p>If you are staying on the same server then putting this in your .htaccess will work regardless of the server:</p>\n\n<pre><code>RedirectMatch 301 ^/terms$ /articles/terms/\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>http://example.com/terms -> http://example.com/articles/terms\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>http://test.example.com/terms -> http://test.example.com/articles/terms\n</code></pre>\n\n<p>Obviously you'll need to adjust the REGEX matching and the like to make sure it copes with what you are going to throw at it. Same goes for the 301, you might want a 302 if you don't want browsers to cache the redirect.</p>\n\n<p>If you want:</p>\n\n<pre><code>http://example.com/terms -> http://server02.example.com/articles/terms\n</code></pre>\n\n<p>Then you'll need to use the HTTP_HOST parameter.</p>\n"}, {'answer_id': 72652, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': -1, 'selected': False, 'text': '<p>You don\'t need to include this information. Just provide a URI relative to the root.</p>\n\n<pre><code>Redirect temp /terms /articles/terms/\n</code></pre>\n\n<p>This is explained in <a href="http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect" rel="nofollow noreferrer">the mod_alias documentation</a>:</p>\n\n<blockquote>\n <p>The new URL should be an absolute URL beginning with a scheme and hostname, but a URL-path beginning with a slash may also be used, in which case the scheme and hostname of the current server will be added.</p>\n</blockquote>\n'}, {'answer_id': 72707, 'author': 'Jaykul', 'author_id': 8718, 'author_profile': 'https://Stackoverflow.com/users/8718', 'pm_score': -1, 'selected': False, 'text': '<p>It sounds like what you really need is just an alias?</p>\n\n<pre><code>Alias /terms /www/public/articles/terms/\n</code></pre>\n'}, {'answer_id': 72828, 'author': 'Sean Carpenter', 'author_id': 729, 'author_profile': 'https://Stackoverflow.com/users/729', 'pm_score': 0, 'selected': False, 'text': "<p>I think you'll want to capture the HTTP_HOST value and then use that in the rewrite rule: </p>\n\n<pre><code>RewriteCond %{HTTP_HOST} (.*)\nRewriteRule ^/terms http://support.%1/article/terms [NC,R=302]\n</code></pre>\n"}, {'answer_id': 10010128, 'author': 'jornare', 'author_id': 1249477, 'author_profile': 'https://Stackoverflow.com/users/1249477', 'pm_score': 0, 'selected': False, 'text': '<p>If I understand your question right, you want a 301 redirect (tell browser to go to other URL).\nIf my solution is not the correct one for you, try this tool: <a href="http://www.htaccessredirect.net/index.php" rel="nofollow">http://www.htaccessredirect.net/index.php</a> and figure out what works for you.</p>\n\n<pre><code>//301 Redirect Entire Directory\nRedirectMatch 301 /terms(.*) /articles/terms/$1\n\n//Change default directory page\nDirectoryIndex \n</code></pre>\n'}, {'answer_id': 10024434, 'author': 'Olivier Pons', 'author_id': 106140, 'author_profile': 'https://Stackoverflow.com/users/106140', 'pm_score': 3, 'selected': True, 'text': '<p>It\'s strange that nobody has done the actual <strong>working</strong> answer (lol):</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} support\\.(([^\\.]+))\\.example\\.com\nRewriteRule ^/terms http://support.%1/article/terms [NC,QSA,R]\n</code></pre>\n\n<hr>\n\n<p>To help you doing the job faster, my favorite tool to check for regexp:</p>\n\n<p><a href="http://www.quanetic.com/Regex" rel="nofollow">http://www.quanetic.com/Regex</a> (don\'t forget to choose ereg(POSIX) instead of preg(PCRE)!)</p>\n\n<p>You use this tool when you want to check the URL and see if they\'re valid or not.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5343/'] |
72,462 | <p>What tools, preferably open source, are recommended for driving an automated test suite on a FLEX based web application? The same tool also having built in capabilities to drive Web Services would be nice.</p>
| [{'answer_id': 72648, 'author': 'Brian G', 'author_id': 3208, 'author_profile': 'https://Stackoverflow.com/users/3208', 'pm_score': 2, 'selected': False, 'text': '<p>I heard of people using selenium as a free/open source testing tool. A quick google revealed a FLEX API for it. Not sure if it works or is still in development, but it may be worth a look.</p>\n\n<p><a href="http://sourceforge.net/projects/seleniumflexapi/" rel="nofollow noreferrer">http://sourceforge.net/projects/seleniumflexapi/</a></p>\n'}, {'answer_id': 76456, 'author': 'ianmjones', 'author_id': 3023, 'author_profile': 'https://Stackoverflow.com/users/3023', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s an automated test tool called <a href="http://www.riatest.com/" rel="nofollow noreferrer">RIATest</a> that might fit the bill for you.</p>\n\n<p>Unfortunately only for Windows, and not open source, but if it does the job it might be well worth the price ($399 at time of writing).</p>\n'}, {'answer_id': 76752, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 3, 'selected': False, 'text': '<p>Adobe distributes a test framework themselves: <a href="http://opensource.adobe.com/wiki/display/flexunit/FlexUnit" rel="noreferrer">FlexUnit</a>.</p>\n'}, {'answer_id': 94234, 'author': 'Mike Deck', 'author_id': 1247, 'author_profile': 'https://Stackoverflow.com/users/1247', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://funfx.rubyforge.org/" rel="nofollow noreferrer">FunFX</a> is an option for automating UI testing. I haven\'t used it extensively, but I\'ve heard of some having success with it. <a href="http://blog.objectmentor.com/articles/2008/06/22/observations-on-test-driving-user-interfaces" rel="nofollow noreferrer">Here</a> is the article where I first learned about it.</p>\n'}, {'answer_id': 110276, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Are you looking to script code-level unit tests? If so, dpuint is the bomb: <a href="http://code.google.com/p/dpuint/" rel="nofollow noreferrer">http://code.google.com/p/dpuint/</a> . This library makes it really easy to do automated testing on all sorts of asynchronous events, on either non-visual ActionScript objects or visual components. They also have a nice multi-page tutorial on the Google Code project page.</p>\n\n<p>If you are looking for functional testing tools along the lines of automated record-and-playback simulating an end user using a Flex app, HP\'s QuickTest Pro is the Adobe-endorsed solution. It works great, but costs about $4,000 - $6,000 per seat.</p>\n'}, {'answer_id': 117838, 'author': 'Derek B.', 'author_id': 20756, 'author_profile': 'https://Stackoverflow.com/users/20756', 'pm_score': 0, 'selected': False, 'text': '<p>My preferred tool is Selenium Remote Control. There is a plug-in I discovered a few months ago:</p>\n\n<p><a href="http://code.google.com/p/flash-selenium/" rel="nofollow noreferrer">http://code.google.com/p/flash-selenium/</a></p>\n\n<p>This required \'hooks\' to be written on the server side (ActionScript/Flex). Once they were added, I was able to do some browser testing using Selenium RC.</p>\n'}, {'answer_id': 673928, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>FunFX is great. We've used it extensively and have been very happy with it. The community is also active and very responsive, so that is a big plus for me.</p>\n"}, {'answer_id': 674343, 'author': 'James Ward', 'author_id': 77409, 'author_profile': 'https://Stackoverflow.com/users/77409', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://code.google.com/p/flexmonkey/" rel="nofollow noreferrer">FlexMonkey</a>. It does automated testing via FlexUnit tests.</p>\n'}, {'answer_id': 846426, 'author': 'Fergal', 'author_id': 102641, 'author_profile': 'https://Stackoverflow.com/users/102641', 'pm_score': 0, 'selected': False, 'text': '<p>The new version of the <a href="https://sourceforge.net/projects/seleniumflexapi/" rel="nofollow noreferrer">Selenium-Flex API (0.2.5)</a> works great.</p>\n'}, {'answer_id': 1836855, 'author': 'James Bobowski', 'author_id': 108881, 'author_profile': 'https://Stackoverflow.com/users/108881', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve been extensively using <a href="http://github.com/peternic/funfx" rel="nofollow noreferrer">FunFX</a> for several months now on a Flex 3 + Rails project. Not only is it open source, it\'s also written in Ruby, so integration with web services should be fairly easy. There are a few <a href="http://onrails.org/articles/2009/07/08/screencast-testing-flex-apps-with-cucumber" rel="nofollow noreferrer">screen</a><a href="http://onrails.org/articles/2009/07/13/screencast-testing-flex-apps-with-cucumber-take-2" rel="nofollow noreferrer">casts</a> out there covering the basics.</p>\n'}, {'answer_id': 3944371, 'author': 'Ben Johnson', 'author_id': 97394, 'author_profile': 'https://Stackoverflow.com/users/97394', 'pm_score': 2, 'selected': False, 'text': '<p>Try looking at Melomel. It has Cucumber support baked right in and comes packaged with steps for most Halo and Spark components.</p>\n\n<p><a href="http://melomel.info" rel="nofollow">http://melomel.info</a></p>\n'}, {'answer_id': 5249157, 'author': 'Samson', 'author_id': 651976, 'author_profile': 'https://Stackoverflow.com/users/651976', 'pm_score': 1, 'selected': False, 'text': '<p>The Flex code that your Flex app needs is contained in the SeleniumFlexAPI distribution .swc file, SeleniumFlexAPI.swc. Just include this file as a library when you compile your Flex app.</p>\n'}, {'answer_id': 20117529, 'author': 'Chinmay Shepal', 'author_id': 1700212, 'author_profile': 'https://Stackoverflow.com/users/1700212', 'pm_score': 1, 'selected': False, 'text': '<p>Sikuli is good tool which can be used to test flex/flash based web applications.\n-It can automate anything on graphical user interface.\n-It works on Windows, MAC OSX and Linux as well as iPhone and Android.\n-Here is the <a href="http://www.sikuli.org/" rel="nofollow">Sikuli link</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12251/'] |
72,479 | <p>Can anyone tell me what exactly does this Java code do?</p>
<pre><code>SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
</code></pre>
<hr>
<p>Step by step explanation will be useful so that I can recreate this code in VB. Thanks</p>
| [{'answer_id': 72520, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and populates it with random data.</p>\n\n<p>This is then encoded using BASE64 and returned.</p>\n\n<p>So, in a nutshell,</p>\n\n<ol>\n<li>Generate 20 random bytes</li>\n<li>Encode using Base 64</li>\n</ol>\n'}, {'answer_id': 72531, 'author': 'Aidos', 'author_id': 12040, 'author_profile': 'https://Stackoverflow.com/users/12040', 'pm_score': 1, 'selected': False, 'text': "<p>It creates a SHA1 based random number generator (RNG), then Base64 encodes the next 20 bytes returned by the RNG.</p>\n\n<p>I can't tell you why it does this however without some more context :-).</p>\n"}, {'answer_id': 72588, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 1, 'selected': False, 'text': '<p>This code gets a cryptographically strong random number that is 20 bytes in length, then Base64 encodes it. There\'s a lot of Java library code here, so your guess is as good as mine as to how to do it in VB.</p>\n\n<pre><code>SecureRandom random = SecureRandom.getInstance("SHA1PRNG");\nbyte[] bytes = new byte[20];\nsynchronized (random) { random.nextBytes(bytes); }\nreturn Base64.encode(bytes);\n</code></pre>\n\n<p>The first line creates an instance of the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html" rel="nofollow noreferrer">SecureRandom</a> class. This class provides a cryptographically strong pseudo-random number generator.</p>\n\n<p>The second line declares a byte array of length 20.</p>\n\n<p>The third line reads the next 20 random bytes into the array created in line 2. It synchronizes on the SecureRandom object so that there are no conflicts from other threads that may be using the object. It\'s not apparent from this code why you need to do this.</p>\n\n<p>The fourth line Base64 encodes the resulting byte array. This is probably for transmission, storage, or display in a known format.</p>\n'}, {'answer_id': 72590, 'author': 'Eduardo Campañó', 'author_id': 12091, 'author_profile': 'https://Stackoverflow.com/users/12091', 'pm_score': 4, 'selected': True, 'text': '<p>Using code snippets you can get to something like this</p>\n\n<pre>\nDim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()\nDim randomBytes(20) As Byte\nrandomNumGen.GetBytes(randomBytes)\nreturn Convert.ToBase64String(randomBytes)\n</pre>\n'}, {'answer_id': 72646, 'author': 'Erlend', 'author_id': 5746, 'author_profile': 'https://Stackoverflow.com/users/5746', 'pm_score': 0, 'selected': False, 'text': '<p>Basically the code above:</p>\n\n<ol>\n<li>Creates a secure random number generator (for VB see link below)</li>\n<li>Fills a bytearray of length 20 with random bytes</li>\n<li>Base64 encodes the result (you can probably use Convert.ToBase64String(...))</li>\n</ol>\n\n<p>You should find some help here:\n<a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12178/'] |
72,482 | <p>Is it possible in a large GWT project, load some portion of JavaScript lazy, on the fly?
Like overlays. </p>
<p>PS: Iframes is not a solution.</p>
| [{'answer_id': 76295, 'author': 'Grant Wagner', 'author_id': 9254, 'author_profile': 'https://Stackoverflow.com/users/9254', 'pm_score': 0, 'selected': False, 'text': '<p>I think this is what you are looking for.</p>\n\n<pre><code><body onload="onloadHandler();">\n<script type="text/javascript">\nfunction onloadHandler() {\n if (document.createElement && document.getElementsByTagName) {\n var script = document.createElement(\'script\');\n script.type = \'text/javascript\';\n script.src = \'./test.js\';\n var heads = document.getElementsByTagName(\'head\');\n if (heads && heads[0]) {\n heads[0].appendChild(script);\n }\n }\n}\nfunction iAmReady(theName) {\n if (\'undefined\' != typeof window[theName]) {\n window[theName]();\n }\n}\nfunction test() {\n // stuff to do when test.js loads\n} \n</script>\n</code></pre>\n\n<p>-- test.js</p>\n\n<pre><code>iAmReady(\'test\');\n</code></pre>\n\n<p>Tested and working in Firefox 2, Safari 3.1.2 for Windows, IE 6 and Opera 9.52. I assume up-level versions of those should work as well.</p>\n\n<p>Note that the loading is asynchronous. If you attempt to use a function or variable in the loaded file immediately after calling <code>appendChild()</code> it will most likely fail, that is why I have included a call-back in the loaded script file that forces an initialization function to run when the script is done loading.</p>\n\n<p>You could also just call an internal function at the bottom of the loaded script to do something once it has loaded.</p>\n'}, {'answer_id': 81957, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>GWT doesn't readily support this since all Java code that is (or rather may be) required for the module that you load is compiled into a single JavaScript file. This single JavaScript file can be large but for non-trivial modules it is smaller than the equivalent hand written JavaScript.</p>\n\n<p>Do you have a scenario where the single generated JavaScript file is too large? </p>\n"}, {'answer_id': 82584, 'author': 'Simon Collins', 'author_id': 12412, 'author_profile': 'https://Stackoverflow.com/users/12412', 'pm_score': 0, 'selected': False, 'text': '<p>You could conceivably split your application up into multiple GWT modules but you need to remember that this will limit your ability to share code between modules. So if one module has classes that reference the same class that another module references, the code for the common class will get included twice.</p>\n\n<p>Effectively the modules create their own namespace, similar what you get in Java if you load the same class via two separate class loaders. In fact because the GWT compiler only compiles in the methods that are referenced in your code (i.e it does dead code elimination), it is conceivable that one module will include a different subset of methods from the common class to the other module.</p>\n\n<p>So you have to weigh up whether loading it all as one monolithic module and taking an upfront hit the first time round is better than having multiple modules whose cumulative code size might well be significantly greater than the single module approach.</p>\n\n<p>Given that GWT is designed so that the user should only ever load the same version of a module once (it is cached thereafter), in most cases the one off upfront hit is preferable.</p>\n'}, {'answer_id': 202580, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Try to load a big GWT application with the "one upfront" approach using a iPhone or an iPod touch...it will never load.</p>\n\n<p>The module approach is a but more complexe to manage but better for smaller client devices.</p>\n\n<p>Now, how do I load a module from my Java code without using an iFrame?</p>\n\n<ul>\n<li>Erick</li>\n</ul>\n'}, {'answer_id': 967116, 'author': 'Eric Walker', 'author_id': 61048, 'author_profile': 'https://Stackoverflow.com/users/61048', 'pm_score': 3, 'selected': False, 'text': '<p>Check out <code>GWT.runAsync</code> as well as the Google I/O talk below, which goes into lazy loading of <code>JavaScript</code> in <code>GWT</code> projects.</p>\n\n<ul>\n<li><a href="http://code.google.com/p/google-web-toolkit/wiki/CodeSplitting" rel="nofollow noreferrer">http://code.google.com/p/google-web-toolkit/wiki/CodeSplitting</a></li>\n<li><a href="http://code.google.com/events/io/sessions/GoogleWavePoweredByGWT.html" rel="nofollow noreferrer">http://code.google.com/events/io/sessions/GoogleWavePoweredByGWT.html</a> (around time 25:30)</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12259/'] |
72,515 | <p>I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?</p>
<p>I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class?</p>
| [{'answer_id': 72538, 'author': 'GEOCHET', 'author_id': 5640, 'author_profile': 'https://Stackoverflow.com/users/5640', 'pm_score': 0, 'selected': False, 'text': '<p>I think what you are looking for is Custom Type Descriptors.\nYou could read up a bit and get started here: <a href="http://www.codeproject.com/KB/miscctrl/bending_property.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/bending_property.aspx</a></p>\n\n<p>I am not sure you can do any control you want, but that article got me started on propertygrids.</p>\n'}, {'answer_id': 72607, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 1, 'selected': False, 'text': "<p>You can control whether the PropertyGrid displays a simple edit box, a drop-down arrow, or an ellipsis control.</p>\n\n<p>Look up EditorAttribute, and follow it on from there. I did have a sample somewhere; I'll try to dig it out.</p>\n"}, {'answer_id': 72651, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 3, 'selected': True, 'text': '<p>To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.</p>\n\n<p>What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...</p>\n\n<pre><code>[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\npublic override string Text\n{\n get { return _string; }\n set { _string = value; }\n}\n</code></pre>\n\n<p>Another nice one they provide for you is the ability to edit an array of strings...</p>\n\n<pre><code>[Editor("System.Windows.Forms.Design.StringArrayEditor, \n System.Design, Version=2.0.0.0, \n Culture=neutral, \n PublicKeyToken=b03f5f7f11d50a3a", \n typeof(UITypeEditor))]\npublic string[] Lines\n{\n get { return _lines; }\n set { _lines = value; }\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533/'] |
72,528 | <p>How would you create a database in Microsoft Access that is searchable only by certain fields and controlled by only a few (necessary) text boxes and check boxes on a form so it is easy to use - no difficult queries?</p>
<p>Example:
You have several text boxes and several corresponding check boxes on a form, and when the check box next to the text box is checked, the text box is enabled and you can then search by what is entered into said text box</p>
<p>(Actually I already know this, just playing stackoverflow jeopardy, where I ask a question I know the answer just to increase the world's coding knowledge! answer coming in about 5 mins)</p>
| [{'answer_id': 72643, 'author': 'BIBD', 'author_id': 685, 'author_profile': 'https://Stackoverflow.com/users/685', 'pm_score': 0, 'selected': False, 'text': '<p>For a question that vague, all that I can answer is open MS Access, and click the mouse a few times.</p>\n\n<p>On second thought:<br>\nUse the "WhereCondition" argument of the "OpenForm" method</p>\n'}, {'answer_id': 72660, 'author': 'ProfK', 'author_id': 8741, 'author_profile': 'https://Stackoverflow.com/users/8741', 'pm_score': 0, 'selected': False, 'text': '<p>At start-up, you need to show a form and disable other menus etc. That way your user only ever sees your limited functionality and cannot directly open the tables etc.</p>\n\n<p>This book excerpt, <a href="http://msdn.microsoft.com/en-us/library/aa200349.aspx" rel="nofollow noreferrer">Real World Microsoft Access Database Protection and Security</a>, should be enlightening. </p>\n'}, {'answer_id': 72798, 'author': 'Philippe Grondier', 'author_id': 11436, 'author_profile': 'https://Stackoverflow.com/users/11436', 'pm_score': 1, 'selected': False, 'text': '<p>My own solution is to add a "filter" control in the header part of the form for each of the columns I want to be able to filter on (usually all ...). Each time such a "filter" control is updated, a procedure will run to update the active filter of the form, using the "BuildCriteria" function available in Access VBA.</p>\n\n<p>Thus, When I type "<code>*cable*</code>" in the "filter" at the top of the Purchase Order Description column, the "WHERE PODescription IS LIKE "<code>*cable*</code>" is automatically added to the MyForm.filter property ....</p>\n\n<p>Some would object that filtering record source made of multiple underlying tables can become very tricky. That\'s right. So the best solution is according to me to always (I mean it!) use a flat table or a view ("SELECT" query in Access) as a record source for a form. This will make your life a lot easier!</p>\n\n<p>Once you\'re convinced of this, you can even think of a small module that will automate the addition of "filter" controls and related procedures to your forms. You\'ll be on the right way for a real user-friendly client interface. </p>\n'}, {'answer_id': 74713, 'author': 'David-W-Fenton', 'author_id': 9787, 'author_profile': 'https://Stackoverflow.com/users/9787', 'pm_score': 1, 'selected': True, 'text': '<p>This is actually a pretty large topic, and fraught with all kinds of potential problems. Most intermediate to advanced books on Access will have some kind of section discussing "Query by Form," where you have an unbound form that allows the user to choose certain criteria, and that when executed, writes on-the-fly SQL to return the matching data.</p>\n\n<p>In anything but a flat, single-table data structure, this is not a trivial task because the FROM clause of the SQL is dependent on the tables queried in the WHERE clause.</p>\n\n<p>A few examples of some QBF forms from apps I\'ve created for clients:</p>\n\n<ol>\n<li><a href="http://dfenton.com/DFA/examples/Search.gif" rel="nofollow noreferrer">Querying 4 underlying tables</a></li>\n<li><a href="http://dfenton.com/DFA/examples/SearchSimple.gif" rel="nofollow noreferrer">Querying a flat single table</a></li>\n<li><a href="http://dfenton.com/DFA/examples/QBF/CFM.gif" rel="nofollow noreferrer">Querying 3 underlying tables</a></li>\n<li><a href="http://dfenton.com/DFA/examples/QBF/SA.gif" rel="nofollow noreferrer">Querying 6 underlying tables</a></li>\n<li><a href="http://dfenton.com/DFA/examples/QBF/WTS.gif" rel="nofollow noreferrer">Querying 2 underlying tables</a></li>\n</ol>\n\n<p>The first one is driven by a class module that has properties that reflect the criteria selected in this form, and that has methods that write the FROM and WHERE clauses. This makes it extremely easy to add other fields (as long as those fields don\'t come from tables other than the ones already included).</p>\n\n<p>The most complex part of the process is writing the FROM clause, as you have to have appropriate join types and include only the tables that are either in the SELECT clause or the WHERE clause. If you include anything else, you\'ll slow down your query a lot (especially if you have any outer joins).</p>\n\n<p>But this is a big subject, and there is no magic bullet solution -- instead, something like this has to be created for each particular application. It\'s also important that you test it thoroughly with users, since what is completely clear and understandable to you, the developer, is often pretty darned mystifying to end users.</p>\n\n<p>But that\'s a principle that doesn\'t just apply to QBF!</p>\n'}, {'answer_id': 156735, 'author': 'onedaywhen', 'author_id': 15354, 'author_profile': 'https://Stackoverflow.com/users/15354', 'pm_score': 0, 'selected': False, 'text': "<p>If the functionality is very limited and/or specialised then a SQL database is probably going to be overkill anyhow e.g. cache all combinations of the data locally, in memory even, and show one according to the checkboxes on the form. Previously you could have revoked permissions from the table and granted them only on VIEWs/PROCs that queried the data in the prescribed way, however security has been removed from MS Access 2007 so you can you now really stop users bypassing your simple app using, say, Excel and querying the data any way they like ...but then isn't that the point of an enterprise database? ;-)</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,537 | <p>In a SharePoint list I want an auto number column that as I add to the list gets incremented. How best can I go about this?</p>
| [{'answer_id': 72569, 'author': 'kemiller2002', 'author_id': 1942, 'author_profile': 'https://Stackoverflow.com/users/1942', 'pm_score': 1, 'selected': False, 'text': "<p>it's in there by default. It's the id field.</p>\n"}, {'answer_id': 72583, 'author': 'MrHinsh - Martin Hinshelwood', 'author_id': 11799, 'author_profile': 'https://Stackoverflow.com/users/11799', 'pm_score': 3, 'selected': False, 'text': '<p>You can\'t add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.</p>\n\n<p>There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can\'t edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.</p>\n\n<p>Check out: <a href="https://web.archive.org/web/20130413013118/http://blog.hinshelwood.com/unique-id-in-sharepoint-list/" rel="nofollow noreferrer">Unique ID in SharePoint list</a></p>\n'}, {'answer_id': 72641, 'author': 'BrewinBombers', 'author_id': 5989, 'author_profile': 'https://Stackoverflow.com/users/5989', 'pm_score': 7, 'selected': True, 'text': '<p>Sharepoint Lists automatically have an column with "ID" which auto increments. You simply need to select this column from the "modify view" screen to view it.</p>\n'}, {'answer_id': 73422, 'author': 'dariom', 'author_id': 12389, 'author_profile': 'https://Stackoverflow.com/users/12389', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to control the formatting of the unique identifier you can <a href="http://msdn.microsoft.com/en-us/library/ms415141.aspx" rel="nofollow noreferrer">create your own <code><FieldType></code> in SharePoint</a>. MSDN also has a <a href="http://msdn.microsoft.com/en-us/library/bb684919.aspx" rel="nofollow noreferrer">visual How-To</a>. This basically means that you\'re creating a custom column.</p>\n\n<p>WSS defines the Counter field type (which is what the ID column above is using). I\'ve never had the need to re-use this or extend it, but it should be possible.</p>\n\n<p>A solution might exist without creating a custom <code><FieldType></code>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (<code>="CUST" & [ID]</code>). I haven\'t tried this, but this <em>should</em> work :)</p>\n'}, {'answer_id': 79813, 'author': 'Sam Yates', 'author_id': 14911, 'author_profile': 'https://Stackoverflow.com/users/14911', 'pm_score': 1, 'selected': False, 'text': '<p>If you want something beyond the ID column that\'s there in all lists, you\'re probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don\'t have complete control over the servers.</p>\n\n<p>If you don\'t need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).</p>\n\n<p>Unfortunately, calculated columns, which seem like an obvious solution, won\'t work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.</p>\n'}, {'answer_id': 83293, 'author': 'user15916', 'author_id': 15916, 'author_profile': 'https://Stackoverflow.com/users/15916', 'pm_score': 1, 'selected': False, 'text': '<p>As stated, all objects in sharepoint contain some sort of unique identifier (often an integer based counter for list items, and GUIDs for lists).</p>\n\n<p>That said, there is also a feature available at <a href="http://www.codeplex.com/features" rel="nofollow noreferrer">http://www.codeplex.com/features</a> called "Unique Column Policy", designed to add an other column with a unique value. A complete writeup is available at <a href="http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!293.entry" rel="nofollow noreferrer">http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!293.entry</a></p>\n'}, {'answer_id': 105826, 'author': 'spdevsolutions', 'author_id': 19086, 'author_profile': 'https://Stackoverflow.com/users/19086', 'pm_score': 1, 'selected': False, 'text': '<p>So I am not sure I can really think of <em>why</em> you would actually need a "site collection unique" id, so maybe you can comment and let us know what is actually trying to be accomplished here...</p>\n\n<p>Either way, all items have a UniqueID property that is a GUID if you <strong>really</strong> need it: <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.uniqueid.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.uniqueid.aspx</a></p>\n'}, {'answer_id': 786529, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Peetha has the best idea, I\'ve done the same with a custom list in our SP site. Using a workflow to auto increment is the best way, and it is not that difficult. Check this website out: <a href="http://splittingshares.wordpress.com/2008/04/11/auto-increment-a-number-in-a-new-list-item/" rel="nofollow noreferrer">http://splittingshares.wordpress.com/2008/04/11/auto-increment-a-number-in-a-new-list-item/</a></p>\n\n<p>I give much appreciation to the person who posted that solution, it is very cool!!</p>\n'}, {'answer_id': 16094572, 'author': 'David Clarke', 'author_id': 132599, 'author_profile': 'https://Stackoverflow.com/users/132599', 'pm_score': 2, 'selected': False, 'text': '<p>I had this issue with a custom list and while it\'s not possible to use the auto-generated <em>ID</em> column to create a calculated column, it is possible to use a workflow to do the heavy lifting.</p>\n\n<p>I created a new workflow variable of type <em>Number</em> and set it to be the value of the <em>ID</em> column in the current item. Then it\'s simply a matter of calculating the custom column value and setting it - in my case I just needed the numbering to begin at 100,000.</p>\n\n<p><img src="https://i.stack.imgur.com/1S1ek.png" alt="enter image description here"></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12318/'] |
72,540 | <p>We are changing our remote log-in security process at my workplace, and we are concerned that the new system does not use <a href="http://en.wikipedia.org/wiki/Two-factor_authentication" rel="nofollow noreferrer">multi-factor authentication</a> as the old one did. (We had been using RSA key-fobs, but they are being replaced due to cost.) The new system is an anti-phishing image system which has been misunderstood to be a two-factor authentication system. We are now exploring ways to continue providing multi-factor security without issuing hardware devices to the users.</p>
<p>Is it possible to write a software-based token system to be installed on the user's PCs that would constitute a true second factor in a multi-factor authentication system? Would this be considered "something the user has", or would it simply be another form of "something the user knows"?</p>
<p>Edit: <em>phreakre</em> makes a good point about cookies. For the sake of this question, assume that cookies have been ruled out as they are not secure enough.</p>
| [{'answer_id': 72642, 'author': 'phreakre', 'author_id': 12051, 'author_profile': 'https://Stackoverflow.com/users/12051', 'pm_score': 1, 'selected': False, 'text': '<p>While I am not sure it is a "valid" second factor, many websites have been using this type of process for a while: cookies. Hardly secure, but it is the type of item you are describing. </p>\n\n<p>Insofar as regarding "something the user has" vs "something the user knows", if it is something resident on the user PC [like a background app providing information when asked but not requiring the user to do anything], I would file it under "things the user has". If they are typing a password into some field and then typing another password to unlock the information you are storing on their PC, then it is "something the user knows".</p>\n\n<p>With regards to commercial solutions out there already in existence: We use a product for windows called BigFix. While it is primarily a remote configuration and compliance product, we have a module for it that works as part of our multi-factor system for remote/VPN situations.</p>\n'}, {'answer_id': 73138, 'author': 'Chris Upchurch', 'author_id': 2600, 'author_profile': 'https://Stackoverflow.com/users/2600', 'pm_score': 1, 'selected': False, 'text': "<p>A software token is a second factor, but it probably isn't as good choice a choice as a RSA fob. If the user's computer is compromised the attacker could silently copy the software token without leaving any trace it's been stolen (unlike a RSA fob where they'd have to take the fob itself, so the user has a chance to notice it's missing). </p>\n"}, {'answer_id': 74145, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 3, 'selected': True, 'text': '<p>I would say "no". I don\'t think you can really get the "something you have" part of multi-factor authentication without issuing something the end user can carry with them. If you "have" something, it implies it can be lost - not many users lose their entire desktop machines. The security of "something you have", after all, comes from the following:</p>\n\n<ul>\n<li>you would notice when you don\'t have it - a clear indication security has been compromised</li>\n<li>only 1 person can have it. So if you do, someone else doesn\'t</li>\n</ul>\n\n<p>Software tokens do not offer the same guarantees, and I would not in good conscience class it as something the user "has". </p>\n'}, {'answer_id': 74369, 'author': 'markus', 'author_id': 3498, 'author_profile': 'https://Stackoverflow.com/users/3498', 'pm_score': 0, 'selected': False, 'text': '<p>I agree with @freespace that the the image is not part of the multi-factor authentication for the user. As you state the image is part of the anti-phishing scheme. I think that the image is actually a weak authentication of the system to the user. The image provides authentication to the user that the website is valid and not a fake phishing site.</p>\n\n<blockquote>\n <p>Is it possible to write a software-based token system to be installed on the user\'s PCs that would constitute a true second factor in a multi-factor authentication system? </p>\n</blockquote>\n\n<p>The software based token system sounds like you may want to investigate the Kerberos protocol, <a href="http://en.wikipedia.org/wiki/Kerberos_(protocol)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Kerberos_(protocol)</a>. I am not sure if this would count as a multi-factor authentication, though.</p>\n'}, {'answer_id': 74793, 'author': 'AviD', 'author_id': 10080, 'author_profile': 'https://Stackoverflow.com/users/10080', 'pm_score': 0, 'selected': False, 'text': "<p>What you're describing is something the <em>computer</em> has, not the user. \nSo you can supposedly (depending on implementation) be assured that it is the computer, but no assurance regarding the user...</p>\n\n<p>Now, since we're talking about remote login, perhaps the situation is personal laptops? In which case, <em>the laptop</em> is the something you have, and of course the password to it as something you know... Then all that remains is secure implementation, and that can work fine.</p>\n"}, {'answer_id': 87583, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Security is always about trade-offs. Hardware tokens may be harder to steal, but they offer no protection against network-based MITM attacks. If this is a web-based solution (I assume it is, since you\'re using one of the image-based systems), you should consider something that offer mutual https authentication. Then you get protection from the numerous DNS attacks and wi-fi based attacks. </p>\n\n<p>You can find out more here:\n<a href="http://www.wikidsystems.com/learn-more/technology/mutual_authentication" rel="nofollow noreferrer">http://www.wikidsystems.com/learn-more/technology/mutual_authentication</a>\nand\n<a href="http://en.wikipedia.org/wiki/Mutual_authentication" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Mutual_authentication</a>\nand here is a tutorial on setting up mutual authentication to prevent phishing:\n<a href="http://www.howtoforge.net/prevent_phishing_with_mutual_authentication" rel="nofollow noreferrer">http://www.howtoforge.net/prevent_phishing_with_mutual_authentication</a>.</p>\n\n<p>The image-based system is pitched as mutual authentication, which I guess it is, but since it\'s not based on cryptographic principals, it\'s pretty weak. What\'s to stop a MITM from presenting the image too? It\'s less than user-friendly IMO too.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8223/'] |
72,541 | <p>I have an ASP.NET web page that displays a variety of fields that need to be updated best on certain conditions, button clicks and so on. We've implemented AJAX, using the ASP.NET Update Panel to avoid visible postbacks.</p>
<p>Originally there was only <em>one</em> area that needed this ability ... that soon expanded to other fields. Now my web page has multiple UpdatePanels. </p>
<p>I am wondering if it would be best to just wrap the entire form in a single UpdatePanel, or keep the individual UpdatePanels.</p>
<p>What are the best practices for using the ASP.NET UpdatePanel?</p>
| [{'answer_id': 72575, 'author': 'Raithlin', 'author_id': 6528, 'author_profile': 'https://Stackoverflow.com/users/6528', 'pm_score': 1, 'selected': False, 'text': '<p>Not sure about the best practices, but in my experience multiple panels work well, and reduce the amount of data being sent at one time - resulting in an increase in response time overall. Multiple panels also reduce the complexity of each server call.</p>\n'}, {'answer_id': 72697, 'author': 'Wayne', 'author_id': 8236, 'author_profile': 'https://Stackoverflow.com/users/8236', 'pm_score': 7, 'selected': True, 'text': "<p>Multiple panels are much better. One of the main reasons for using UpdatePanels at all is to reduce the traffic and to only send the pieces that you need back and forth across the wire. By only using one update panel, you're pretty much doing a full post back every time, you're just using a little Javascript to update the page without a flicker.</p>\n\n<p>If there are pieces of the page that need to be updated together, there are ways to trigger other panels to update when one does.. but you should definitely be using multiple update panels.</p>\n"}, {'answer_id': 72725, 'author': 'craigmoliver', 'author_id': 12252, 'author_profile': 'https://Stackoverflow.com/users/12252', 'pm_score': 3, 'selected': False, 'text': '<p>I believe it is best to use multiple UpdatePanel if you can because of the size the POST that the UpdatePanel generates. It\'s even better if you can use manual AJAX approaches for small things like updating a field. The WPF provides some javascript functions and methods to accomplish this. Here\'s some link that may be helpful:</p>\n\n<ul>\n<li><a href="http://msdn.microsoft.com/en-us/library/bb514961.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb514961.aspx</a></li>\n<li><a href="http://msdn.microsoft.com/en-us/library/bb515101.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb515101.aspx</a></li>\n</ul>\n'}, {'answer_id': 73080, 'author': 'Jon', 'author_id': 4764, 'author_profile': 'https://Stackoverflow.com/users/4764', 'pm_score': 5, 'selected': False, 'text': '<p>I\'d caution that with multiple update panels you\'ll want to be careful. Make sure you set the UpdateMode to Conditional. Otherwise, when one update panel is "posted back" to the server, all of them are posted back. </p>\n\n<p>I\'d highly suggest using these tools</p>\n\n<p><a href="http://projects.nikhilk.net/WebDevHelper/Default.aspx" rel="noreferrer">Web Development Helper</a> (here\'s a brief tutorial <a href="http://www.nikhilk.net/WebDevHelperHTTPTracingUpdates.aspx" rel="noreferrer">Web Development Helper and ASP.NET Ajax</a>)</p>\n\n<p><a href="http://www.fiddlertool.com/fiddler/" rel="noreferrer">Fiddler</a></p>\n'}, {'answer_id': 374486, 'author': 'sangam', 'author_id': 47043, 'author_profile': 'https://Stackoverflow.com/users/47043', 'pm_score': 2, 'selected': False, 'text': '<p>I recommend multiple updatepanels. Using multiple updatepanels will keep alive the true meaning of using updatepanel in asp.net web applications. And since we can even trigger one updatepanel from another updatepanel this makes it easier to code page-wide controls and behaviour.</p>\n'}, {'answer_id': 5077186, 'author': 'Chintan', 'author_id': 628169, 'author_profile': 'https://Stackoverflow.com/users/628169', 'pm_score': 2, 'selected': False, 'text': '<p>I completely agree to use Multiple Update Panel rather than to use single update panel,When you want only a certain part to be postbacked \nif you want entire page to be postback then it is better to use single update panel.</p>\n\n<p>Make sure that you make the updatemode="conditional" for all the updatepanel otherwise all the updatepanel will get refreshed.</p>\n\n<p>Also Check out the below Post for complete usage for update panel</p>\n\n<p><a href="http://www.codeproject.com/KB/aspnet/Select_List_Box.aspx" rel="nofollow">http://www.codeproject.com/KB/aspnet/Select_List_Box.aspx</a></p>\n'}, {'answer_id': 5331810, 'author': 'BigbangO', 'author_id': 396927, 'author_profile': 'https://Stackoverflow.com/users/396927', 'pm_score': 3, 'selected': False, 'text': '<p>Any of these answers don\'t mentioned maintainabiliy comparison between the choices. Third options is that you don\'t use any update panel and leave your self to the reverse ajax. Check out the interesting projects: <a href="http://pokein.codeplex.com" rel="noreferrer">PokeIn</a> and <a href="http://visualjs.net" rel="noreferrer">VisualJS.NET</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768/'] |
72,552 | <p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p>
<p>In my case, I have never knowingly needed it.</p>
| [{'answer_id': 72576, 'author': 'ChrisN', 'author_id': 3853, 'author_profile': 'https://Stackoverflow.com/users/3853', 'pm_score': 7, 'selected': False, 'text': "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the <code>volatile</code> keyword to ensure that such accesses aren't optimised away by the compiler.</p>\n"}, {'answer_id': 72617, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 9, 'selected': True, 'text': "<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>\n\n<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>\n\n<pre><code>void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n</code></pre>\n\n<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>\n"}, {'answer_id': 72629, 'author': 'Mladen Janković', 'author_id': 6300, 'author_profile': 'https://Stackoverflow.com/users/6300', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>you must use it to implement spinlocks as well as some (all?) lock-free data structures</li>\n<li>use it with atomic operations/instructions</li>\n<li>helped me once to overcome compiler's bug (wrongly generated code during optimization)</li>\n</ol>\n"}, {'answer_id': 72666, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Developing for an embedded, I have a loop that checks on a variable that can be changed in an interrupt handler. Without "volatile", the loop becomes a noop - as far as the compiler can tell, the variable never changes, so it optimizes the check away.</p>\n\n<p>Same thing would apply to a variable that may be changed in a different thread in a more traditional environment, but there we often do synchronization calls, so compiler is not so free with optimization.</p>\n'}, {'answer_id': 72962, 'author': 'MikeZ', 'author_id': 12402, 'author_profile': 'https://Stackoverflow.com/users/12402', 'pm_score': 6, 'selected': False, 'text': '<p>From a <em>"Volatile as a promise"</em> article by Dan Saks:</p>\n\n<blockquote>\n <p>(...) a volatile object is one whose value might change spontaneously. That is, when you declare an object to be volatile, you\'re telling the compiler that the object might change state even though no statements in the program appear to change it."</p>\n</blockquote>\n\n<p>Here are links to three of his articles regarding the <code>volatile</code> keyword:</p>\n\n<ul>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025583/Use-volatile-judiciously" rel="noreferrer">Use volatile judiciously</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025609/Place-volatile-accurately" rel="noreferrer">Place volatile accurately</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025624/Volatile-as-a-promise" rel="noreferrer">Volatile as a promise</a></li>\n</ul>\n'}, {'answer_id': 73520, 'author': 'tfinniga', 'author_id': 9042, 'author_profile': 'https://Stackoverflow.com/users/9042', 'pm_score': 6, 'selected': False, 'text': "<p>Some processors have floating point registers that have more than 64 bits of precision (eg. 32-bit x86 without SSE, see Peter's comment). That way, if you run several operations on double-precision numbers, you actually get a higher-precision answer than if you were to truncate each intermediate result to 64 bits.</p>\n\n<p>This is usually great, but it means that depending on how the compiler assigned registers and did optimizations you'll have different results for the exact same operations on the exact same inputs. If you need consistency then you can force each operation to go back to memory by using the volatile keyword.</p>\n\n<p>It's also useful for some algorithms that make no algebraic sense but reduce floating point error, such as Kahan summation. Algebraicly it's a nop, so it will often get incorrectly optimized out unless some intermediate variables are volatile.</p>\n"}, {'answer_id': 77042, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 2, 'selected': False, 'text': "<p>Beside the fact that the volatile keyword is used for telling the compiler not to optimize the access to some variable (that can be modified by a thread or an interrupt routine), it can be also <strong>used to remove some compiler bugs</strong> -- <em>YES it can be</em> ---.</p>\n\n<p>For example I worked on an embedded platform were the compiler was making some wrong assuptions regarding a value of a variable. If the code wasn't optimized the program would run ok. With optimizations (which were really needed because it was a critical routine) the code wouldn't work correctly. The only solution (though not very correct) was to declare the 'faulty' variable as volatile.</p>\n"}, {'answer_id': 77057, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>A large application that I used to work on in the early 1990s contained C-based exception handling using setjmp and longjmp. The volatile keyword was necessary on variables whose values needed to be preserved in the block of code that served as the "catch" clause, lest those vars be stored in registers and wiped out by the longjmp.</p>\n'}, {'answer_id': 77141, 'author': 'indentation', 'author_id': 7706, 'author_profile': 'https://Stackoverflow.com/users/7706', 'pm_score': 3, 'selected': False, 'text': "<p>I've used it in debug builds when the compiler insists on optimizing away a variable that I want to be able to see as I step through code.</p>\n"}, {'answer_id': 81460, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 3, 'selected': False, 'text': "<p>Besides using it as intended, volatile is used in (template) metaprogramming. It can be used to prevent accidental overloading, as the volatile attribute (like const) takes part in overload resolution.</p>\n\n<pre><code>template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n</code></pre>\n\n<p>This is legal; both overloads are potentially callable and do almost the same. The cast in the <code>volatile</code> overload is legal as we know bar won't pass a non-volatile <code>T</code> anyway. The <code>volatile</code> version is strictly worse, though, so never chosen in overload resolution if the non-volatile <code>f</code> is available.</p>\n\n<p>Note that the code never actually depends on <code>volatile</code> memory access.</p>\n"}, {'answer_id': 82306, 'author': 'Frederik Slijkerman', 'author_id': 12416, 'author_profile': 'https://Stackoverflow.com/users/12416', 'pm_score': 5, 'selected': False, 'text': '<p>You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.</p>\n\n<p>To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.</p>\n\n<p>For example, this is how InterlockedIncrement is declared in the Win32 API:</p>\n\n<pre><code>LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n</code></pre>\n'}, {'answer_id': 17900959, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 3, 'selected': False, 'text': '<p>In Standard C, one of the places to use <code>volatile</code> is with a signal handler. In fact, in Standard C, all you can safely do in a signal handler is modify a <code>volatile sig_atomic_t</code> variable, or exit quickly. Indeed, AFAIK, it is the only place in Standard C that the use of <code>volatile</code> is required to avoid undefined behaviour.</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:2011 §7.14.1.1 The <code>signal</code> function</h3>\n \n <p>¶5 If the signal occurs other than as the result of calling the <code>abort</code> or <code>raise</code> function, the\n behavior is undefined if the signal handler refers to any object with static or thread\n storage duration that is not a lock-free atomic object other than by assigning a value to an\n object declared as <code>volatile sig_atomic_t</code>, or the signal handler calls any function\n in the standard library other than the <code>abort</code> function, the <code>_Exit</code> function, the\n <code>quick_exit</code> function, or the <code>signal</code> function with the first argument equal to the\n signal number corresponding to the signal that caused the invocation of the handler.\n Furthermore, if such a call to the <code>signal</code> function results in a SIG_ERR return, the\n value of <code>errno</code> is indeterminate.<sup>252)</sup></p>\n \n <p><sup>252)</sup> If any signal is generated by an asynchronous signal handler, the behavior is undefined.</p>\n</blockquote>\n\n<p>That means that in Standard C, you can write:</p>\n\n<pre><code>static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n</code></pre>\n\n<p>and not much else.</p>\n\n<p>POSIX is a lot more lenient about what you can do in a signal handler, but there are still limitations (and one of the limitations is that the Standard I/O library — <code>printf()</code> et al — cannot be used safely).</p>\n'}, {'answer_id': 39875143, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>volatile</code> keyword is intended to prevent the compiler from applying any optimisations on objects that can change in ways that cannot be determined by the compiler.</p>\n\n<p>Objects declared as <code>volatile</code> are omitted from optimisation because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a <code>volatile</code> object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.</p>\n\n<p><strong>Consider the following cases</strong></p>\n\n<p>1) Global variables modified by an interrupt service routine outside the scope.</p>\n\n<p>2) Global variables within a multi-threaded application.</p>\n\n<p><strong>If we do not use volatile qualifier, the following problems may arise</strong></p>\n\n<p>1) Code may not work as expected when optimisation is turned on.</p>\n\n<p>2) Code may not work as expected when interrupts are enabled and used.</p>\n\n<p><a href="http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766" rel="nofollow">Volatile: A programmer’s best friend</a></p>\n\n<p><a href="https://en.wikipedia.org/wiki/Volatile_(computer_programming)" rel="nofollow">https://en.wikipedia.org/wiki/Volatile_(computer_programming)</a></p>\n'}, {'answer_id': 43802700, 'author': 'bugs king', 'author_id': 1211764, 'author_profile': 'https://Stackoverflow.com/users/1211764', 'pm_score': 1, 'selected': False, 'text': "<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>\n"}, {'answer_id': 46888720, 'author': 'Joachim', 'author_id': 1961484, 'author_profile': 'https://Stackoverflow.com/users/1961484', 'pm_score': 2, 'selected': False, 'text': "<p>Your program seems to work even without <code>volatile</code> keyword? Perhaps this is the reason:</p>\n\n<p>As mentioned previously the <code>volatile</code> keyword helps for cases like</p>\n\n<pre><code>volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n</code></pre>\n\n<p>But there seems to be almost no effect once an external or non-inline function is being called. E.g.:</p>\n\n<pre><code>while( *p!=0 ) { g(); }\n</code></pre>\n\n<p>Then with or without <code>volatile</code> almost the same result is generated.</p>\n\n<p>As long as g() can be completely inlined, the compiler can see everything that's going on and can therefore optimize. But when the program makes a call to a place where the compiler can't see what's going on, it isn't safe for the compiler to make any assumptions any more. Hence the compiler will generate code that always reads from memory directly.</p>\n\n<p>But beware of the day, when your function g() becomes inline (either due to explicit changes or due to compiler/linker cleverness) then your code might break if you forgot the <code>volatile</code> keyword!</p>\n\n<p>Therefore I recommend to add the <code>volatile</code> keyword even if your program seems to work without. It makes the intention clearer and more robust in respect to future changes.</p>\n"}, {'answer_id': 51598967, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 2, 'selected': False, 'text': '<p>In the early days of C, compilers would interpret all actions that read and write lvalues as memory operations, to be performed in the same sequence as the reads and writes appeared in the code. Efficiency could be greatly improved in many cases if compilers were given a certain amount of freedom to re-order and consolidate operations, but there was a problem with this. Even though operations were often specified in a certain order merely because it was necessary to specify them in <em>some</em> order, and thus the programmer picked one of many equally-good alternatives, that wasn\'t always the case. Sometimes it would be important that certain operations occur in a particular sequence.</p>\n<p>Exactly which details of sequencing are important will vary depending upon the target platform and application field. Rather than provide particularly detailed control, the Standard opted for a simple model: if a sequence of accesses are done with lvalues that are not qualified <code>volatile</code>, a compiler may reorder and consolidate them as it sees fit. If an action is done with a <code>volatile</code>-qualified lvalue, a quality implementation should offer whatever additional ordering guarantees might be required by code targeting its intended platform and application field, without requiring that programmers use non-standard syntax.</p>\n<p>Unfortunately, rather than identify what guarantees programmers would need, many compilers have opted instead to offer the bare minimum guarantees mandated by the Standard. This makes <code>volatile</code> much less useful than it should be. On gcc or clang, for example, a programmer needing to implement a basic "hand-off mutex" [one where a task that has acquired and released a mutex won\'t do so again until the other task has done so] must do one of four things:</p>\n<ol>\n<li><p>Put the acquisition and release of the mutex in a function that the compiler cannot inline, and to which it cannot apply Whole Program Optimization.</p>\n</li>\n<li><p>Qualify all the objects guarded by the mutex as <code>volatile</code>--something which shouldn\'t be necessary if all accesses occur after acquiring the mutex and before releasing it.</p>\n</li>\n<li><p>Use optimization level 0 to force the compiler to generate code as though all objects that aren\'t qualified <code>register</code> are <code>volatile</code>.</p>\n</li>\n<li><p>Use gcc-specific directives.</p>\n</li>\n</ol>\n<p>By contrast, when using a higher-quality compiler which is more suitable for systems programming, such as icc, one would have another option:</p>\n<ol start="5">\n<li>Make sure that a <code>volatile</code>-qualified write gets performed everyplace an acquire or release is needed.</li>\n</ol>\n<p>Acquiring a basic "hand-off mutex" requires a <code>volatile</code> read (to see if it\'s ready), and shouldn\'t require a <code>volatile</code> write as well (the other side won\'t try to re-acquire it until it\'s handed back) but having to perform a meaningless <code>volatile</code> write is still better than any of the options available under gcc or clang.</p>\n'}, {'answer_id': 59002919, 'author': 'curiousguy', 'author_id': 963864, 'author_profile': 'https://Stackoverflow.com/users/963864', 'pm_score': 2, 'selected': False, 'text': '<p>Other answers already mention avoiding some optimization in order to:</p>\n\n<ul>\n<li>use memory mapped registers (or "MMIO")</li>\n<li>write device drivers</li>\n<li>allow easier debugging of programs</li>\n<li>make floating point computations more deterministic </li>\n</ul>\n\n<p>Volatile is essential whenever you need a value to appear to come from the outside and be unpredictable and avoid compiler optimizations based on a value being known, and when a result isn\'t actually used but you need it to be computed, or it\'s used but you want to compute it several times for a benchmark, and you need the computations to start and end at precise points.</p>\n\n<p>A volatile read is like an input operation (like <code>scanf</code> or a use of <code>cin</code>): <em>the value seems to come from the outside of the program, so any computation that has a dependency on the value needs to start after it</em>. </p>\n\n<p>A volatile write is like an output operation (like <code>printf</code> or a use of <code>cout</code>): <em>the value seems to be communicated outside of the program, so if the value depends on a computation, it needs to be finished before</em>.</p>\n\n<p>So <strong>a pair of volatile read/write can be used to tame benchmarks and make time measurement meaningful</strong>.</p>\n\n<p>Without volatile, your computation could be started by the compiler before, <strong>as nothing would prevent reordering of computations with functions such as time measurement</strong>.</p>\n'}, {'answer_id': 61495883, 'author': 'Rohit', 'author_id': 3049983, 'author_profile': 'https://Stackoverflow.com/users/3049983', 'pm_score': 2, 'selected': False, 'text': '<p>All answers are excellent. But on the top of that, I would like to share an example.</p>\n\n<p>Below is a little cpp program:</p>\n\n<pre><code>#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf("x is 8\\n");\n else\n sprintf(buf, "x is not 8\\n");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n</code></pre>\n\n<p>Now, lets generate the assembly of the above code (and I will paste only that portions of the assembly which relevant here):</p>\n\n<p>The command to generate assembly:</p>\n\n<pre><code>g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n</code></pre>\n\n<p>And the assembly:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf("x is 8\\n");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf("x is 8\\n");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>You can see in the assembly that the assembly code was not generated for <code>sprintf</code> because the compiler assumed that <code>x</code> will not change outside of the program. And same is the case with the <code>while</code> loop. <code>while</code> loop was altogether removed due to the optimization because compiler saw it as a useless code and thus directly assigned <code>5</code> to <code>x</code> (see <code>movl $5, x(%rip)</code>).</p>\n\n<p>The problem occurs when what if an external process/ hardware would change the value of <code>x</code> somewhere between <code>x = 8;</code> and <code>if(x == 8)</code>. We would expect <code>else</code> block to work but unfortunately the compiler has trimmed out that part. </p>\n\n<p>Now, in order to solve this, in the <code>assembly.cpp</code>, let us change <code>int x;</code> to <code>volatile int x;</code> and quickly see the assembly code generated:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, "x is not 8\\n");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf("x is 8\\n");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>Here you can see that the assembly codes for <code>sprintf</code>, <code>printf</code> and <code>while</code> loop were generated. The advantage is that if the <code>x</code> variable is changed by some external program or hardware, <code>sprintf</code> part of the code will be executed. And similarly <code>while</code> loop can be used for busy waiting now.</p>\n'}, {'answer_id': 65641563, 'author': 'alex_noname', 'author_id': 13782669, 'author_profile': 'https://Stackoverflow.com/users/13782669', 'pm_score': 1, 'selected': False, 'text': '<p>I would like to quote Herb Sutter\'s words from his <a href="https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/" rel="nofollow noreferrer">GotW #95</a>, which can help to understand the meaning of the <code>volatile</code> variables:</p>\n<blockquote>\n<p><code>C++</code> <code>volatile</code> variables (which have no analog in languages like <code>C#</code> and <code>Java</code>) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because <code>C++</code> <code>volatile</code> variables aren’t about threads or communication at all and don’t interact with those things. Rather, a <code>C++</code> <code>volatile</code> variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise “strange” and beyond the language. So <code>C++</code> <code>volatile</code> variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler (because the compiler isn’t allowed to know their semantics; a <code>volatile int vi;</code> may not behave anything like a normal <code>int</code>, and you can’t even assume that code like <code>vi = 5; int read_back = vi;</code> is guaranteed to result in <code>read_back == 5</code>, or that code like <code>int i = vi; int j = vi;</code> that reads vi twice will result in <code>i == j</code> which will not be true if <code>vi</code> is a hardware counter for example).</p>\n</blockquote>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2167252/'] |
72,556 | <p>I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.</p>
<p>Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.</p>
| [{'answer_id': 72576, 'author': 'ChrisN', 'author_id': 3853, 'author_profile': 'https://Stackoverflow.com/users/3853', 'pm_score': 7, 'selected': False, 'text': "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the <code>volatile</code> keyword to ensure that such accesses aren't optimised away by the compiler.</p>\n"}, {'answer_id': 72617, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 9, 'selected': True, 'text': "<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>\n\n<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>\n\n<pre><code>void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n</code></pre>\n\n<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>\n"}, {'answer_id': 72629, 'author': 'Mladen Janković', 'author_id': 6300, 'author_profile': 'https://Stackoverflow.com/users/6300', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>you must use it to implement spinlocks as well as some (all?) lock-free data structures</li>\n<li>use it with atomic operations/instructions</li>\n<li>helped me once to overcome compiler's bug (wrongly generated code during optimization)</li>\n</ol>\n"}, {'answer_id': 72666, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Developing for an embedded, I have a loop that checks on a variable that can be changed in an interrupt handler. Without "volatile", the loop becomes a noop - as far as the compiler can tell, the variable never changes, so it optimizes the check away.</p>\n\n<p>Same thing would apply to a variable that may be changed in a different thread in a more traditional environment, but there we often do synchronization calls, so compiler is not so free with optimization.</p>\n'}, {'answer_id': 72962, 'author': 'MikeZ', 'author_id': 12402, 'author_profile': 'https://Stackoverflow.com/users/12402', 'pm_score': 6, 'selected': False, 'text': '<p>From a <em>"Volatile as a promise"</em> article by Dan Saks:</p>\n\n<blockquote>\n <p>(...) a volatile object is one whose value might change spontaneously. That is, when you declare an object to be volatile, you\'re telling the compiler that the object might change state even though no statements in the program appear to change it."</p>\n</blockquote>\n\n<p>Here are links to three of his articles regarding the <code>volatile</code> keyword:</p>\n\n<ul>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025583/Use-volatile-judiciously" rel="noreferrer">Use volatile judiciously</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025609/Place-volatile-accurately" rel="noreferrer">Place volatile accurately</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025624/Volatile-as-a-promise" rel="noreferrer">Volatile as a promise</a></li>\n</ul>\n'}, {'answer_id': 73520, 'author': 'tfinniga', 'author_id': 9042, 'author_profile': 'https://Stackoverflow.com/users/9042', 'pm_score': 6, 'selected': False, 'text': "<p>Some processors have floating point registers that have more than 64 bits of precision (eg. 32-bit x86 without SSE, see Peter's comment). That way, if you run several operations on double-precision numbers, you actually get a higher-precision answer than if you were to truncate each intermediate result to 64 bits.</p>\n\n<p>This is usually great, but it means that depending on how the compiler assigned registers and did optimizations you'll have different results for the exact same operations on the exact same inputs. If you need consistency then you can force each operation to go back to memory by using the volatile keyword.</p>\n\n<p>It's also useful for some algorithms that make no algebraic sense but reduce floating point error, such as Kahan summation. Algebraicly it's a nop, so it will often get incorrectly optimized out unless some intermediate variables are volatile.</p>\n"}, {'answer_id': 77042, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 2, 'selected': False, 'text': "<p>Beside the fact that the volatile keyword is used for telling the compiler not to optimize the access to some variable (that can be modified by a thread or an interrupt routine), it can be also <strong>used to remove some compiler bugs</strong> -- <em>YES it can be</em> ---.</p>\n\n<p>For example I worked on an embedded platform were the compiler was making some wrong assuptions regarding a value of a variable. If the code wasn't optimized the program would run ok. With optimizations (which were really needed because it was a critical routine) the code wouldn't work correctly. The only solution (though not very correct) was to declare the 'faulty' variable as volatile.</p>\n"}, {'answer_id': 77057, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>A large application that I used to work on in the early 1990s contained C-based exception handling using setjmp and longjmp. The volatile keyword was necessary on variables whose values needed to be preserved in the block of code that served as the "catch" clause, lest those vars be stored in registers and wiped out by the longjmp.</p>\n'}, {'answer_id': 77141, 'author': 'indentation', 'author_id': 7706, 'author_profile': 'https://Stackoverflow.com/users/7706', 'pm_score': 3, 'selected': False, 'text': "<p>I've used it in debug builds when the compiler insists on optimizing away a variable that I want to be able to see as I step through code.</p>\n"}, {'answer_id': 81460, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 3, 'selected': False, 'text': "<p>Besides using it as intended, volatile is used in (template) metaprogramming. It can be used to prevent accidental overloading, as the volatile attribute (like const) takes part in overload resolution.</p>\n\n<pre><code>template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n</code></pre>\n\n<p>This is legal; both overloads are potentially callable and do almost the same. The cast in the <code>volatile</code> overload is legal as we know bar won't pass a non-volatile <code>T</code> anyway. The <code>volatile</code> version is strictly worse, though, so never chosen in overload resolution if the non-volatile <code>f</code> is available.</p>\n\n<p>Note that the code never actually depends on <code>volatile</code> memory access.</p>\n"}, {'answer_id': 82306, 'author': 'Frederik Slijkerman', 'author_id': 12416, 'author_profile': 'https://Stackoverflow.com/users/12416', 'pm_score': 5, 'selected': False, 'text': '<p>You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.</p>\n\n<p>To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.</p>\n\n<p>For example, this is how InterlockedIncrement is declared in the Win32 API:</p>\n\n<pre><code>LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n</code></pre>\n'}, {'answer_id': 17900959, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 3, 'selected': False, 'text': '<p>In Standard C, one of the places to use <code>volatile</code> is with a signal handler. In fact, in Standard C, all you can safely do in a signal handler is modify a <code>volatile sig_atomic_t</code> variable, or exit quickly. Indeed, AFAIK, it is the only place in Standard C that the use of <code>volatile</code> is required to avoid undefined behaviour.</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:2011 §7.14.1.1 The <code>signal</code> function</h3>\n \n <p>¶5 If the signal occurs other than as the result of calling the <code>abort</code> or <code>raise</code> function, the\n behavior is undefined if the signal handler refers to any object with static or thread\n storage duration that is not a lock-free atomic object other than by assigning a value to an\n object declared as <code>volatile sig_atomic_t</code>, or the signal handler calls any function\n in the standard library other than the <code>abort</code> function, the <code>_Exit</code> function, the\n <code>quick_exit</code> function, or the <code>signal</code> function with the first argument equal to the\n signal number corresponding to the signal that caused the invocation of the handler.\n Furthermore, if such a call to the <code>signal</code> function results in a SIG_ERR return, the\n value of <code>errno</code> is indeterminate.<sup>252)</sup></p>\n \n <p><sup>252)</sup> If any signal is generated by an asynchronous signal handler, the behavior is undefined.</p>\n</blockquote>\n\n<p>That means that in Standard C, you can write:</p>\n\n<pre><code>static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n</code></pre>\n\n<p>and not much else.</p>\n\n<p>POSIX is a lot more lenient about what you can do in a signal handler, but there are still limitations (and one of the limitations is that the Standard I/O library — <code>printf()</code> et al — cannot be used safely).</p>\n'}, {'answer_id': 39875143, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>volatile</code> keyword is intended to prevent the compiler from applying any optimisations on objects that can change in ways that cannot be determined by the compiler.</p>\n\n<p>Objects declared as <code>volatile</code> are omitted from optimisation because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a <code>volatile</code> object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.</p>\n\n<p><strong>Consider the following cases</strong></p>\n\n<p>1) Global variables modified by an interrupt service routine outside the scope.</p>\n\n<p>2) Global variables within a multi-threaded application.</p>\n\n<p><strong>If we do not use volatile qualifier, the following problems may arise</strong></p>\n\n<p>1) Code may not work as expected when optimisation is turned on.</p>\n\n<p>2) Code may not work as expected when interrupts are enabled and used.</p>\n\n<p><a href="http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766" rel="nofollow">Volatile: A programmer’s best friend</a></p>\n\n<p><a href="https://en.wikipedia.org/wiki/Volatile_(computer_programming)" rel="nofollow">https://en.wikipedia.org/wiki/Volatile_(computer_programming)</a></p>\n'}, {'answer_id': 43802700, 'author': 'bugs king', 'author_id': 1211764, 'author_profile': 'https://Stackoverflow.com/users/1211764', 'pm_score': 1, 'selected': False, 'text': "<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>\n"}, {'answer_id': 46888720, 'author': 'Joachim', 'author_id': 1961484, 'author_profile': 'https://Stackoverflow.com/users/1961484', 'pm_score': 2, 'selected': False, 'text': "<p>Your program seems to work even without <code>volatile</code> keyword? Perhaps this is the reason:</p>\n\n<p>As mentioned previously the <code>volatile</code> keyword helps for cases like</p>\n\n<pre><code>volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n</code></pre>\n\n<p>But there seems to be almost no effect once an external or non-inline function is being called. E.g.:</p>\n\n<pre><code>while( *p!=0 ) { g(); }\n</code></pre>\n\n<p>Then with or without <code>volatile</code> almost the same result is generated.</p>\n\n<p>As long as g() can be completely inlined, the compiler can see everything that's going on and can therefore optimize. But when the program makes a call to a place where the compiler can't see what's going on, it isn't safe for the compiler to make any assumptions any more. Hence the compiler will generate code that always reads from memory directly.</p>\n\n<p>But beware of the day, when your function g() becomes inline (either due to explicit changes or due to compiler/linker cleverness) then your code might break if you forgot the <code>volatile</code> keyword!</p>\n\n<p>Therefore I recommend to add the <code>volatile</code> keyword even if your program seems to work without. It makes the intention clearer and more robust in respect to future changes.</p>\n"}, {'answer_id': 51598967, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 2, 'selected': False, 'text': '<p>In the early days of C, compilers would interpret all actions that read and write lvalues as memory operations, to be performed in the same sequence as the reads and writes appeared in the code. Efficiency could be greatly improved in many cases if compilers were given a certain amount of freedom to re-order and consolidate operations, but there was a problem with this. Even though operations were often specified in a certain order merely because it was necessary to specify them in <em>some</em> order, and thus the programmer picked one of many equally-good alternatives, that wasn\'t always the case. Sometimes it would be important that certain operations occur in a particular sequence.</p>\n<p>Exactly which details of sequencing are important will vary depending upon the target platform and application field. Rather than provide particularly detailed control, the Standard opted for a simple model: if a sequence of accesses are done with lvalues that are not qualified <code>volatile</code>, a compiler may reorder and consolidate them as it sees fit. If an action is done with a <code>volatile</code>-qualified lvalue, a quality implementation should offer whatever additional ordering guarantees might be required by code targeting its intended platform and application field, without requiring that programmers use non-standard syntax.</p>\n<p>Unfortunately, rather than identify what guarantees programmers would need, many compilers have opted instead to offer the bare minimum guarantees mandated by the Standard. This makes <code>volatile</code> much less useful than it should be. On gcc or clang, for example, a programmer needing to implement a basic "hand-off mutex" [one where a task that has acquired and released a mutex won\'t do so again until the other task has done so] must do one of four things:</p>\n<ol>\n<li><p>Put the acquisition and release of the mutex in a function that the compiler cannot inline, and to which it cannot apply Whole Program Optimization.</p>\n</li>\n<li><p>Qualify all the objects guarded by the mutex as <code>volatile</code>--something which shouldn\'t be necessary if all accesses occur after acquiring the mutex and before releasing it.</p>\n</li>\n<li><p>Use optimization level 0 to force the compiler to generate code as though all objects that aren\'t qualified <code>register</code> are <code>volatile</code>.</p>\n</li>\n<li><p>Use gcc-specific directives.</p>\n</li>\n</ol>\n<p>By contrast, when using a higher-quality compiler which is more suitable for systems programming, such as icc, one would have another option:</p>\n<ol start="5">\n<li>Make sure that a <code>volatile</code>-qualified write gets performed everyplace an acquire or release is needed.</li>\n</ol>\n<p>Acquiring a basic "hand-off mutex" requires a <code>volatile</code> read (to see if it\'s ready), and shouldn\'t require a <code>volatile</code> write as well (the other side won\'t try to re-acquire it until it\'s handed back) but having to perform a meaningless <code>volatile</code> write is still better than any of the options available under gcc or clang.</p>\n'}, {'answer_id': 59002919, 'author': 'curiousguy', 'author_id': 963864, 'author_profile': 'https://Stackoverflow.com/users/963864', 'pm_score': 2, 'selected': False, 'text': '<p>Other answers already mention avoiding some optimization in order to:</p>\n\n<ul>\n<li>use memory mapped registers (or "MMIO")</li>\n<li>write device drivers</li>\n<li>allow easier debugging of programs</li>\n<li>make floating point computations more deterministic </li>\n</ul>\n\n<p>Volatile is essential whenever you need a value to appear to come from the outside and be unpredictable and avoid compiler optimizations based on a value being known, and when a result isn\'t actually used but you need it to be computed, or it\'s used but you want to compute it several times for a benchmark, and you need the computations to start and end at precise points.</p>\n\n<p>A volatile read is like an input operation (like <code>scanf</code> or a use of <code>cin</code>): <em>the value seems to come from the outside of the program, so any computation that has a dependency on the value needs to start after it</em>. </p>\n\n<p>A volatile write is like an output operation (like <code>printf</code> or a use of <code>cout</code>): <em>the value seems to be communicated outside of the program, so if the value depends on a computation, it needs to be finished before</em>.</p>\n\n<p>So <strong>a pair of volatile read/write can be used to tame benchmarks and make time measurement meaningful</strong>.</p>\n\n<p>Without volatile, your computation could be started by the compiler before, <strong>as nothing would prevent reordering of computations with functions such as time measurement</strong>.</p>\n'}, {'answer_id': 61495883, 'author': 'Rohit', 'author_id': 3049983, 'author_profile': 'https://Stackoverflow.com/users/3049983', 'pm_score': 2, 'selected': False, 'text': '<p>All answers are excellent. But on the top of that, I would like to share an example.</p>\n\n<p>Below is a little cpp program:</p>\n\n<pre><code>#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf("x is 8\\n");\n else\n sprintf(buf, "x is not 8\\n");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n</code></pre>\n\n<p>Now, lets generate the assembly of the above code (and I will paste only that portions of the assembly which relevant here):</p>\n\n<p>The command to generate assembly:</p>\n\n<pre><code>g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n</code></pre>\n\n<p>And the assembly:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf("x is 8\\n");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf("x is 8\\n");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>You can see in the assembly that the assembly code was not generated for <code>sprintf</code> because the compiler assumed that <code>x</code> will not change outside of the program. And same is the case with the <code>while</code> loop. <code>while</code> loop was altogether removed due to the optimization because compiler saw it as a useless code and thus directly assigned <code>5</code> to <code>x</code> (see <code>movl $5, x(%rip)</code>).</p>\n\n<p>The problem occurs when what if an external process/ hardware would change the value of <code>x</code> somewhere between <code>x = 8;</code> and <code>if(x == 8)</code>. We would expect <code>else</code> block to work but unfortunately the compiler has trimmed out that part. </p>\n\n<p>Now, in order to solve this, in the <code>assembly.cpp</code>, let us change <code>int x;</code> to <code>volatile int x;</code> and quickly see the assembly code generated:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, "x is not 8\\n");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf("x is 8\\n");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>Here you can see that the assembly codes for <code>sprintf</code>, <code>printf</code> and <code>while</code> loop were generated. The advantage is that if the <code>x</code> variable is changed by some external program or hardware, <code>sprintf</code> part of the code will be executed. And similarly <code>while</code> loop can be used for busy waiting now.</p>\n'}, {'answer_id': 65641563, 'author': 'alex_noname', 'author_id': 13782669, 'author_profile': 'https://Stackoverflow.com/users/13782669', 'pm_score': 1, 'selected': False, 'text': '<p>I would like to quote Herb Sutter\'s words from his <a href="https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/" rel="nofollow noreferrer">GotW #95</a>, which can help to understand the meaning of the <code>volatile</code> variables:</p>\n<blockquote>\n<p><code>C++</code> <code>volatile</code> variables (which have no analog in languages like <code>C#</code> and <code>Java</code>) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because <code>C++</code> <code>volatile</code> variables aren’t about threads or communication at all and don’t interact with those things. Rather, a <code>C++</code> <code>volatile</code> variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise “strange” and beyond the language. So <code>C++</code> <code>volatile</code> variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler (because the compiler isn’t allowed to know their semantics; a <code>volatile int vi;</code> may not behave anything like a normal <code>int</code>, and you can’t even assume that code like <code>vi = 5; int read_back = vi;</code> is guaranteed to result in <code>read_back == 5</code>, or that code like <code>int i = vi; int j = vi;</code> that reads vi twice will result in <code>i == j</code> which will not be true if <code>vi</code> is a hardware counter for example).</p>\n</blockquote>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12333/'] |
72,562 | <p>Is there a good way to find out which exceptions a procedure/function can raise in Delphi (including it's called procedures/functions)? </p>
<p>In Java you always have to declare which exceptions that can be thrown, but this is not the case in Delphi, which could lead to unhandled exceptions. </p>
<p>Are there any code analysis tools that detects unhandled exceptions?</p>
| [{'answer_id': 72612, 'author': 'Pierre-Jean Coudert', 'author_id': 8450, 'author_profile': 'https://Stackoverflow.com/users/8450', 'pm_score': 2, 'selected': False, 'text': '<p>Take a look at <a href="http://www.madshi.net/madExceptDescription.htm" rel="nofollow noreferrer">http://www.madshi.net/madExceptDescription.htm</a></p>\n'}, {'answer_id': 72658, 'author': 'PatrickvL', 'author_id': 12170, 'author_profile': 'https://Stackoverflow.com/users/12170', 'pm_score': 3, 'selected': False, 'text': '<p>Except for a scan on the "raise" keyword, there\'s no language construct in Delphi that tells the casual reader which exceptions can be expected from a method.</p>\n\n<p>At runtime, one could add a catch-all exception handler in every method, but that\'s not advisable, as it will slow down the speed of execution. (And it\'s cumbersome to do too).</p>\n\n<p>Adding an exception-handling block to a method will add a few assembly instructions to it (even when the exception isn\'t triggered), which forms measureable slow-down when the method is called very often.</p>\n\n<p>There do exist a few libraries that can help you in analyzing runtime exceptions, like <a href="http://madshi.de/madExceptDescription.htm" rel="nofollow noreferrer">madExcept</a>, <a href="http://jcl.svn.sourceforge.net/viewvc/jcl/trunk/jcl/source/windows/JclDebug.pas?view=markup" rel="nofollow noreferrer">JclDebug</a>, and <a href="http://www.eurekalog.com/" rel="nofollow noreferrer">EurekaLog</a>. These tools can log all kinds of details about the exception, it\'s highly advisable to use one of those!</p>\n'}, {'answer_id': 72670, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 1, 'selected': False, 'text': '<p>For runtime try <a href="http://www.eurekalog.com/" rel="nofollow noreferrer">Eurekalog</a>. I do not know whether a tool exists for design time. You will have more dificoulties even when you have third party code without source. There is no need in Delphi to catch exceptions, so you do not have to declare them like in Java.</p>\n\n<p>What I wanted to say is that Delphi does not require that an exception is handled. It will just terminate the program. EurekaLog provides means to log handled and unhandled exceptions and provide a wealth of information on the sate of the program when the exception occured, including the line of code it occured at and the call stack at the time.</p>\n'}, {'answer_id': 72709, 'author': 'Lars Fosdal', 'author_id': 10002, 'author_profile': 'https://Stackoverflow.com/users/10002', 'pm_score': 2, 'selected': False, 'text': "<p>Any exception not explicitly or generally handled at a specific level will trickle upwards in the call stack. The Delphi RTL (Run Time Library) will generate a set of different exception classes - (mathematical errors, access errors, class specific errors etc). You can chose to handle them specifically or generally in the different try except blocks.</p>\n\n<p>You don't really need to declare any new exception classes unless you need to propagate a specific functional context with the exception.</p>\n\n<p>As previous commenters wrote, you can also add a mother of all exception handlers like MadExcept or EurekaLog to catch the uncaught.</p>\n\n<p>edit: This is a blanket insurance against unhandled exceptions</p>\n\n<pre><code>try\n ThisFunctionMayFail;\nexcept\n // but it sure won't crash the application\n on e:exception\n do begin\n // something sensible to handle the error \n // or perhaps log and/or display the the generic e.description message\n end\nend;\n</code></pre>\n"}, {'answer_id': 72797, 'author': 'Frederik Slijkerman', 'author_id': 12416, 'author_profile': 'https://Stackoverflow.com/users/12416', 'pm_score': 4, 'selected': False, 'text': "<p>My guess is that you're trying to make Delphi behave like Java, which is not a good approach. I'd advise not to worry too much about unhandled exceptions. In the worst case, they'll bubble up to the generic VCL exception handler and cause a Windows message dialog. In a normal application, they won't halt the application.</p>\n\n<p>Well-written code would document the different exceptions that can be raised so you can handle them in a meaningful way. Catch-all handlers aren't recommended since there is really no way to know what to do if you don't know why an exception was raised. I can also highly recommend madExcept.</p>\n"}, {'answer_id': 72839, 'author': 'Graza', 'author_id': 11820, 'author_profile': 'https://Stackoverflow.com/users/11820', 'pm_score': 5, 'selected': True, 'text': '<p>(Edit: It is now obvious that the question referred <em>only</em> to design-time checking.)</p>\n\n<p>New answer:</p>\n\n<p>I cannot state whether there are any tools to check this for you. Pascal Analyzer, for one, does not.</p>\n\n<p>I <em>can</em> tell you, however, that in most Delphi applications, even if there was a tool to check this for you, you would get no results.</p>\n\n<p><em>Why?</em> Because the main message loop in TApplication.Run() wraps all HandleMessage() calls in an exception handling block, which catches all exception types. Thus you will have implicit/default exception handling around 99.999% of code in most applications. And in most applications, this exception handling will be around 100% of your own code - the 0.001% of code which is not wrapped in exception handling will be the automatically generated code.</p>\n\n<p>If there was a tool available to check this for you, you would need to rewrite Application.run() such that it does not include exception handling.</p>\n\n<p>(Previous answer:\n<em>The Application.OnException event handler can be assigned to catch all exceptions that aren\'t handled by other exception handlers. Whilst this is run-time, and thus perhaps not exactly what you are after (it sounds like you want to identify them at design time), it does allow you to trap any exception not handled elsewhere. In conjunction with tools such as the JCLDebug stuff in the <a href="http://sourceforge.net/projects/jcl/" rel="noreferrer">Jedi Code Library</a>, you could log a stack trace to find out where & why an exception occurred, which would allow for further investigation and adding specific exception handling or prevention around the guilty code...</em>)</p>\n'}, {'answer_id': 73176, 'author': 'skamradt', 'author_id': 9217, 'author_profile': 'https://Stackoverflow.com/users/9217', 'pm_score': 2, 'selected': False, 'text': '<p>I will second (or is it third) <a href="http://www.madshi.net/" rel="nofollow noreferrer">MadExcept</a>. I have been using it successfully in several commercial applications without any problems. The nice thing about MadExcept is that it will generate a report for you with a full stack trace that will generally point you in the right direction as to what went wrong, and can even include a screenshot, as well has have this automatically emailed to you from the clients computer with a simple mouse click.</p>\n\n<p>However, you don\'t want to use this for ALL exceptions, just to catch the ones you miss. For instance, if you open a database and the login fails, it would be better for you to catch and handle this one yourself rather than give the user the MadExcept default error in your application occured message. </p>\n'}, {'answer_id': 73954, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 3, 'selected': False, 'text': "<p>The short answers is there is no tool that does what you say, and even a scan for the <strong>raise</strong> keyword wouldn't get you there. <em>EAccessViolation</em> or <em>EOutOfMemory</em> are just two of a number of exceptions that could get raised just about anywhere. </p>\n\n<p>One fundamental thing about Delphi is the exceptions are hierarchical: All defined language exceptions descend from <em>Exception</em>, although it is worth noting that it is actually possible to raise any <em>TObject</em> descendant.</p>\n\n<p>If you want to <strong>catch</strong> every exception that is raised in a particular procedure, just wrap it in a <strong>try / except</strong> block, but as was mentioned <strong><em>this is not recommended</em></strong>.</p>\n\n<pre><code>// Other code . . . \ntry\n SomeProcedure()\nexcept // BAD IDEA!\n ShowMessage('I caught them all!');\nend;\n</code></pre>\n\n<p>That will catch everything, even instances of a raised <em>TObject</em>. Although I would argue that this is rarely the best course of action. Usually you want to use a <strong>try / finally</strong> block and then allow your global exception handler (or one final <strong>try / except</strong> block) to actually handle the exceptions.</p>\n"}, {'answer_id': 104594, 'author': 'Frank Shearar', 'author_id': 10259, 'author_profile': 'https://Stackoverflow.com/users/10259', 'pm_score': 1, 'selected': False, 'text': '<p>As Jim McKeeth points out, you can\'t get a definitive answer, but it seems to me that one could <em>partially</em> answer the question by some static analysis: given a particular function/procedure, construct a call graph. Check each of the functions in that call graph for a raise statement. That would tell you, for instance, that TIdTcpClient.ReadString can raise an EIdNotConnected (among others).</p>\n\n<p>A clever analyser might also note that some code uses the / operator and include EDivByZero as a possibility, or that some procedure accesses an array and include ERangeError.</p>\n\n<p>That answer\'s a bit tighter than simply grepping for "raise".</p>\n'}, {'answer_id': 24093419, 'author': 'oOo', 'author_id': 700914, 'author_profile': 'https://Stackoverflow.com/users/700914', 'pm_score': 0, 'selected': False, 'text': "<p>Finalization sections of units can raise exceptions too. These will slip by I think... and are also somewhat problematic.</p>\n<p>I think Delphi IDE has a build-in "stack trace" or "stack tree" something like.</p>\n<p>This question reminds me of Skybuck's TRussianRoulette game... google it, it's code and answer may help.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11300/'] |
72,564 | <p>I'm kind of interested in getting some feedback about this technique I picked up from somewhere.</p>
<p>I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this.</p>
<p>Basically the technique involves returning true for success, and <em>something</em> which <em>equates</em> to false for failure. Here's an example to show what I mean:</p>
<pre><code>define ('DUPLICATE_USERNAME', false);
define ('DATABASE_ERROR', 0);
define ('INSUFFICIENT_DETAILS', 0.0);
define ('OK', true);
function createUser($username) {
// create the user and return the appropriate constant from the above
}
</code></pre>
<p>The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code:</p>
<pre><code>if (createUser('fred')) {
// yay, it worked!
} else {
// aww, it didn't work.
}
</code></pre>
<p>If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with ===</p>
<pre><code>$status = createUser('fred');
if ($status) {
// yay, it worked!
} else if ($status === DUPLICATE_USERNAME) {
// tell the user about it and get them to try again.
} else {
// aww, it didn't work. log it and show a generic error message? whatever.
}
</code></pre>
<p>The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false.</p>
<p>The downside is that you can only have <code>7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.</code> If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an <code>enum</code> where they all equate to false is <code>"ick"</code>.</p>
<hr>
<p>So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? </p>
| [{'answer_id': 72589, 'author': 'Chris Broadfoot', 'author_id': 3947, 'author_profile': 'https://Stackoverflow.com/users/3947', 'pm_score': 2, 'selected': False, 'text': "<p>As long as it's documented and contracted, and not too WTFy, then there shouldn't be a problem.</p>\n\n<p>Then again, I would recommend using exceptions for something like this. It makes more sense. If you can use PHP5, then that would be the way to go. Otherwise you don't have much choice.</p>\n"}, {'answer_id': 72634, 'author': 'mmaibaum', 'author_id': 12213, 'author_profile': 'https://Stackoverflow.com/users/12213', 'pm_score': 2, 'selected': False, 'text': "<p>A more common approach I have seen when exceptions aren't available is to store the error type in a 'last_error' variable somewhere and then when a failure happens (ie it returns false) look up the error. </p>\n\n<p>Another approach is to use the venerable unix tool approach numbered error codes - return 0 for success and any integer (that maps to some error) for the various error conditions. </p>\n\n<p>Most of these suffer in comparison to exceptions when I've seen them used however.</p>\n\n<p>Just to respond to Andrew's comment - \nI agree that the last_error should not be a global and perhaps the 'somewhere' in my answer was a little vague - other people have suggested better places already so I won't bother to repeat them</p>\n"}, {'answer_id': 72656, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 2, 'selected': False, 'text': '<p>Often you will return 0 to indicate success, and 1, 2, 3, etc. to indicate different failures. Your way of doing it is kind of hackish, because you can only have so many errors, and this kind of coding <em>will</em> bite you sooner or later.</p>\n\n<p>I like defining a struct/object that includes a Boolean to indicate success, and an error message or other value indicate what kind of error occurred. You can also include other fields to indicate what kind of action was executed. </p>\n\n<p>This makes logging very easy, since you can then just pass the status-struct into the logger, and it will then insert the appropriate log entry.</p>\n'}, {'answer_id': 72661, 'author': 'Argelbargel', 'author_id': 2992, 'author_profile': 'https://Stackoverflow.com/users/2992', 'pm_score': -1, 'selected': False, 'text': '<p>In my opinion, you should use this technique only if failure is a "normal part of operation" of your method / function. For example, it\'s as probable that a call suceeds as that it fails. If failure is a exceptional event, then you should use exception handling so your program can terminate as early and gracefully as possible.</p>\n\n<p>As for your use of different "false" values, I\'d better return an instance of a custom "Result"-class with an proper error code. Something like:</p>\n\n<pre><code>class Result\n{\n var $_result;\n var $_errormsg;\n\n function Result($res, $error)\n {\n $this->_result = $res;\n $ths->_errorMsg = $error\n }\n\n function getResult()\n {\n return $this->_result;\n }\n\n function isError()\n {\n return ! ((boolean) $this->_result);\n }\n\n function getErrorMessage()\n {\n return $this->_errorMsg;\n }\n</code></pre>\n'}, {'answer_id': 72665, 'author': 'Jonathan Adelson', 'author_id': 8092, 'author_profile': 'https://Stackoverflow.com/users/8092', 'pm_score': 0, 'selected': False, 'text': "<p>Ick.</p>\n\n<p>In Unix pre-exception this is done with errno. You return 0 for success or -1 for failure, then you have a value you can retrieve with an integer error code to get the actual error. This works in all cases, because you don't have a (realistic) limit to the number of error codes. INT_MAX is certainly more than 7, and you don't have to worry about the type (errno).</p>\n\n<p>I vote against the solution proposed in the question.</p>\n"}, {'answer_id': 72673, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': -1, 'selected': False, 'text': '<p>Look at COM HRESULT for a correct way to do it.</p>\n\n<p>But exceptions are generally better.</p>\n\n<p>Update: the correct way is: define as many error values as you want, not only "false" ones. Use function succeeded() to check if function succeeded.</p>\n\n<pre><code>if (succeeded(result = MyFunction()))\n ...\nelse\n ...\n</code></pre>\n'}, {'answer_id': 72730, 'author': 'Jeremy Privett', 'author_id': 560, 'author_profile': 'https://Stackoverflow.com/users/560', 'pm_score': 5, 'selected': True, 'text': "<p>I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as:</p>\n\n<pre><code>function createUser($username, &$error)\n</code></pre>\n\n<p>Then you can use:</p>\n\n<pre><code>if (createUser('fred', $error)) {\n echo 'success';\n}\nelse {\n echo $error;\n}\n</code></pre>\n\n<p>Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference.</p>\n"}, {'answer_id': 72838, 'author': 'ljorquera', 'author_id': 9132, 'author_profile': 'https://Stackoverflow.com/users/9132', 'pm_score': 0, 'selected': False, 'text': "<p>If you really want to do this kind of thing, you should have different values for each error, and check for success. Something like</p>\n\n<pre><code>define ('OK', 0);\ndefine ('DUPLICATE_USERNAME', 1);\ndefine ('DATABASE_ERROR', 2);\ndefine ('INSUFFICIENT_DETAILS', 3);\n</code></pre>\n\n<p>And check:</p>\n\n<pre><code>if (createUser('fred') == OK) {\n //OK\n\n}\nelse {\n //Fail\n}\n</code></pre>\n"}, {'answer_id': 72926, 'author': 'rami', 'author_id': 9629, 'author_profile': 'https://Stackoverflow.com/users/9629', 'pm_score': 0, 'selected': False, 'text': "<p>It does make sense that a successful execution returns true. Handling generic errors will be much easier:</p>\n\n<pre><code>if (!createUser($username)) {\n// the dingo ate my user.\n// deal with it.\n}\n</code></pre>\n\n<p>But it doesn't make sense at all to associate meaning with different types of false. False should mean one thing and one thing only, regardless of the type or how the programming language treats it. If you're going to define error status constants anyway, better stick with switch/case</p>\n\n<pre><code>define(DUPLICATE_USERNAME, 4)\ndefine(USERNAME_NOT_ALPHANUM, 8)\n\nswitch ($status) {\ncase DUPLICATE_USERNAME:\n // sorry hun, there's someone else\n break;\ncase USERNAME_NOT_ALPHANUM:\n break;\ndefault:\n // yay, it worked\n}\n</code></pre>\n\n<p>Also with this technique, you'll be able to bitwise AND and OR status messages, so you can return status messages that carry more than one meaning like <code>DUPLICATE_USERNAME & USERNAME_NOT_ALPHANUM</code> and treat it appropriately. This isn't always a good idea, it depends on how you use it.</p>\n"}, {'answer_id': 73049, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n <p>how acceptable is a practice like this?</p>\n</blockquote>\n\n<p>I\'d say it\'s unacceptable.</p>\n\n<ol>\n<li>Requires the === operator, which is very dangerous. If the user used ==, it leads to a very hard to find bug.</li>\n<li>Using "0" and "" to denote false may change in future PHP versions. Plus in a lot of other languages "0" and "" does not evaluate to false which leads to great confusion</li>\n</ol>\n\n<p>Using getLastError() type of global function is probably the best practice in PHP because it <em>ties in well with the language</em>, since PHP is still mostly a procedural langauge. I think another problem with the approach you just gave is that very few other systems work like that. The programmer has to learn this way of error checking which is the source of errors. It\'s best to make things work like how most people expect.</p>\n\n<pre><code>if ( makeClient() )\n{ // happy scenario goes here }\n\nelse\n{\n // error handling all goes inside this block\n switch ( getMakeClientError() )\n { case: // .. }\n}\n</code></pre>\n'}, {'answer_id': 73100, 'author': 'inxilpro', 'author_id': 12549, 'author_profile': 'https://Stackoverflow.com/users/12549', 'pm_score': 1, 'selected': False, 'text': '<p>When exceptions aren\'t available, I\'d use the <a href="http://en.wikipedia.org/wiki/PEAR" rel="nofollow noreferrer">PEAR</a> model and provide isError() functionality in all your classes.</p>\n'}, {'answer_id': 73455, 'author': 'Markowitch', 'author_id': 11964, 'author_profile': 'https://Stackoverflow.com/users/11964', 'pm_score': 0, 'selected': False, 'text': "<p>I like the way COM can handle both exception and non-exception capable callers. The example below show how a HRESULT is tested and an exception is thrown in case of failure. (usually autogenerated in tli files)</p>\n\n<pre><code>inline _bstr_t IMyClass::GetName ( ) {\n BSTR _result;\n HRESULT _hr = get_name(&_result);\n if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));\n return _bstr_t(_result, false);\n}\n</code></pre>\n\n<p>Using return values will affect readability by having error handling scattered and worst case, the return values are never checked by the code. That's why I prefer exception when a contract is breached.</p>\n"}, {'answer_id': 73589, 'author': 'Aquarion', 'author_id': 12696, 'author_profile': 'https://Stackoverflow.com/users/12696', 'pm_score': 0, 'selected': False, 'text': '<p>Other ways include exceptions:</p>\n\n<pre><code>throw new Validation_Exception_SQLDuplicate("There\'s someone else, hun");),\n</code></pre>\n\n<p>returning structures,</p>\n\n<pre><code>return new Result($status, $stuff);\nif ($result->status == 0) {\n $stuff = $result->data;\n}\nelse {\n die(\'Oh hell\');\n}\n</code></pre>\n\n<p>I would hate to be the person who came after you for using the code pattern you suggested originally.</p>\n\n<p>And I mean "Came after you" as in "followed you in employment and had to maintain the code" rather than "came after you" "with a wedgiematic", though both are options.</p>\n'}, {'answer_id': 86759, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Reinventing the wheel here. Using squares.</p>\n\n<p>OK, you don\'t have exceptions in PHP 4. Welcome in the year 1982, take a look at C.</p>\n\n<p>You can have error codes. Consider negative values, they seem more intuitive, so you would just have to check if (createUser() > 0).</p>\n\n<p>You can have an error log if you want, with error messages (or just arbitrary error codes) pushed onto an array, dealt with elegance afterwards.</p>\n\n<p>But PHP is a loosely typed language for a reason, and throwing error codes that have different types but evaluate to the same "false" is something that shouldn\'t be done. </p>\n\n<p>What happens when you run out of built-in types?</p>\n\n<p>What happens when you get a new coder and have to explain how this thing works? Say, in 6 months, you won\'t remember.</p>\n\n<p>Is PHP === operator fast enough to get through it? Is it faster than error codes? or any other method?</p>\n\n<p>Just drop it.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9021/'] |
72,568 | <p>What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API? </p>
| [{'answer_id': 73349, 'author': 'Aaron', 'author_id': 11176, 'author_profile': 'https://Stackoverflow.com/users/11176', 'pm_score': 2, 'selected': False, 'text': '<p>If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:</p>\n\n<pre><code>class Foo(models.Model):\n name = models.CharField(max_length=255)\n\nclass FizzBuzz(models.Model):\n bleh = models.CharField(max_length=255)\n\nclass Bar(models.Model):\n foo = models.ForeignKey(Foo)\n fizzbuzz = models.ForeignKey(FizzBuzz) \n</code></pre>\n\n<p>You can do something like:</p>\n\n<pre><code>Fizzbuzz.objects.filter(bar__foo__name = "Adrian")\n</code></pre>\n'}, {'answer_id': 73462, 'author': 'machineghost', 'author_id': 5921, 'author_profile': 'https://Stackoverflow.com/users/5921', 'pm_score': 2, 'selected': False, 'text': '<p>Don\'t use the API ;-) Seriously, if your JOIN are complex, you should see significant performance increases by dropping down in to SQL rather than by using the API. And this doesn\'t mean you need to get dirty dirty SQL all over your beautiful Python code; just make a custom manager to handle the JOINs and then have the rest of your code use it rather than direct SQL.</p>\n\n<p>Also, I was just at DjangoCon where they had a seminar on high-performance Django, and one of the key things I took away from it was that if performance is a real concern (and you plan to have significant traffic someday), you really shouldn\'t be doing JOINs in the first place, because they make scaling your app while maintaining decent performance virtually impossible.</p>\n\n<p>Here\'s a video Google made of the talk:\n<a href="http://www.youtube.com/watch?v=D-4UN4MkSyI&feature=PlayList&p=D415FAF806EC47A1&index=20" rel="nofollow noreferrer">http://www.youtube.com/watch?v=D-4UN4MkSyI&feature=PlayList&p=D415FAF806EC47A1&index=20</a></p>\n\n<p>Of course, if you know that your application is never going to have to deal with that kind of scaling concern, JOIN away :-) And if you\'re also not worried about the performance hit of using the API, then you really don\'t need to worry about the (AFAIK) miniscule, if any, performance difference between using one API method over another.</p>\n\n<p>Just use:\n<a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships</a></p>\n\n<p>Hope that helps (and if it doesn\'t, hopefully some true Django hacker can jump in and explain why method X actually does have some noticeable performance difference).</p>\n'}, {'answer_id': 372079, 'author': 'bnjmnhggns', 'author_id': 35254, 'author_profile': 'https://Stackoverflow.com/users/35254', 'pm_score': 1, 'selected': False, 'text': "<p>Use the queryset.query.join method, but only if the other method described here (using double underscores) isn't adequate.</p>\n"}, {'answer_id': 1894381, 'author': 'Viesturs', 'author_id': 1660, 'author_profile': 'https://Stackoverflow.com/users/1660', 'pm_score': 0, 'selected': False, 'text': '<p>Caktus blog has an answer to this: <a href="http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/" rel="nofollow noreferrer">http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/</a></p>\n\n<p>Basically there is a hidden QuerySet.query.join method that allows adding custom joins.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,573 | <p>Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?</p>
<p>The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.</p>
| [{'answer_id': 73033, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 2, 'selected': False, 'text': '<p>No, can\'t be done, at least not if you\'re talking about the Feature Pack version. Version 10 of the BCGSoft libraries do have this functionality, see for example: <a href="http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm" rel="nofollow noreferrer">http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm</a> and <a href="http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg" rel="nofollow noreferrer">http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg</a>. The MFC feature pack is more or less the previous version of the BCGSoft libraries, MS bought a license from them.</p>\n'}, {'answer_id': 93554, 'author': 'djeidot', 'author_id': 4880, 'author_profile': 'https://Stackoverflow.com/users/4880', 'pm_score': 0, 'selected': False, 'text': '<p>You need to add the Common Controls manifest to your project resources. Here is the code for the manifest file:</p>\n\n<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">\n<assemblyIdentity\n version="1.0.0.0"\n processorArchitecture="X86"\n name="Program Name"\n type="win32"\n/>\n<description>Description of Program</description>\n<dependency>\n <dependentAssembly>\n <assemblyIdentity\n type="win32"\n name="Microsoft.Windows.Common-Controls"\n version="6.0.0.0"\n processorArchitecture="X86"\n publicKeyToken="6595b64144ccf1df"\n language="*"\n />\n </dependentAssembly>\n</dependency>\n</assembly>\n</code></pre>\n'}, {'answer_id': 1467172, 'author': 'djeidot', 'author_id': 4880, 'author_profile': 'https://Stackoverflow.com/users/4880', 'pm_score': 0, 'selected': False, 'text': '<p>I think you can have some MFC-feature-pack features by implementing <code>OnApplicationLook</code> on your base <code>CDialog</code> (check Step 4 on <a href="http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/print.php/c14929__2" rel="nofollow noreferrer">this page</a>). It might be better to implement the whole <code>OnApplicationLook</code> method, but you can test your application simply by adding this to <code>OnInitDialog</code>:</p>\n\n<pre><code>CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);\nCMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));\nCDockingManager::SetDockingMode(DT_SMART);\nRedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);\n</code></pre>\n'}, {'answer_id': 26944194, 'author': 'Ziggyware', 'author_id': 4255207, 'author_profile': 'https://Stackoverflow.com/users/4255207', 'pm_score': 0, 'selected': False, 'text': '<p>This is the least amount of code to enable the Visual Styles. You should be able to pop your CDialog into the frame easily. The IDR_MAINFRAME is a menu resource.</p>\n\n<pre><code>class CMFCApplication2Dlg : public CFrameWndEx\n{\n CMFCMenuBar bar;\npublic:\n CMFCApplication2Dlg() : CFrameWndEx()\n {\n LoadFrame(IDR_MAINFRAME);\n bar.Create(this);\n }\n};\n\nclass CMFCApplication2App : public CWinAppEx\n{\npublic:\n virtual BOOL InitInstance()\n {\n CWinAppEx::InitInstance();\n\n CMFCVisualManagerOffice2007::SetStyle(\n CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);\n\n CMFCVisualManager::SetDefaultManager(\n RUNTIME_CLASS(CMFCVisualManagerOffice2007));\n\n SetRegistryKey(_T("Local AppWizard-Generated Applications"));\n\n m_pMainWnd = new CMFCApplication2Dlg();\n\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n\n return TRUE;\n }\n};\n\nCMFCApplication2App theApp;\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12346/'] |
72,580 | <p>I have an app that I've written in C#/WinForms (<a href="http://www.thekbase.com" rel="nofollow noreferrer" title="TheKBase">my little app</a>). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development?</p>
<p>By cross-platform I mean, currently, Mac OSX, Windows and Linux.</p>
<p>This question was <a href="https://stackoverflow.com/questions/116468/winforms-for-mono-on-mac-linux-and-pc-redux">asked again and answered with better success</a>.</p>
| [{'answer_id': 72604, 'author': 'Łukasz Sowa', 'author_id': 347616, 'author_profile': 'https://Stackoverflow.com/users/347616', 'pm_score': 2, 'selected': False, 'text': '<p>WinForms are fully supported by Mono, so they are cross-platform.</p>\n'}, {'answer_id': 72610, 'author': 'Michael Pliskin', 'author_id': 9777, 'author_profile': 'https://Stackoverflow.com/users/9777', 'pm_score': 1, 'selected': False, 'text': '<p>Well I think the only way to for cross-platform reliably with C# is <a href="http://www.silverlight.net" rel="nofollow noreferrer">Microsoft Silverlight</a>, but is not really WinForms, and browser-based. Other than that, yes Mono is a chance.</p>\n'}, {'answer_id': 72632, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': "<p>I don't think there is a future for WinForms at all. Since it appears to have been a stop-gap solution even in MSFT world ( a very thin wrapper around Win32). And virtually no changes seem to have been made to System.Windows.Forms in both .NET 3.0 and 3.5</p>\n\n<pre><code></speculation>\n</code></pre>\n\n<p>I would use Java or Air.</p>\n"}, {'answer_id': 72633, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 3, 'selected': False, 'text': '<p>As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though.</p>\n\n<p>But as <em>you already have a working C# code</em>, porting it to ActionScript might requires a redesign due to ActionScript having a different way of thinking/programming, they use different primitive data types, for example, they use just a <code>Number</code> instead of <code>int float double</code> etc. and the debugging tools are quiet lacking compared to VS IMO.</p>\n\n<p>And I heard that <a href="http://www.mono-project.com/GtkSharp" rel="nofollow noreferrer">Mono\'s GtkSharp</a> is quiet a decent platform.</p>\n\n<p>But if you don\'t mind the coding/debugging tooling problems, then AIR is a great platform. I like how Adobe integrates the Flash experience into it e.g. you can start an installation of AIR application via a button click in a flash movieclip, that kind of integration.</p>\n'}, {'answer_id': 72970, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to use the .net Framework, Microsoft Silverlight is a good (the only?) choice. The browser does a good job as a shell, but you could also write your own application shell for it. For example, Scott Handelman <a href="http://www.hanselman.com/blog/default.aspx?date=2008-09-05" rel="nofollow noreferrer">mentions</a> the NY Times Reader written in Silverlight and hostet on Cocoa on a Mac.</p>\n'}, {'answer_id': 72982, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>Why would you go with Air?</p>\n\n<p>Use <a href="http://www.mono-project.com/GtkSharp" rel="nofollow noreferrer">GTK#</a>, and you have a cross platform forms engine and you get to keep your C# code.</p>\n'}, {'answer_id': 219351, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I think that as long as you make sure that the business logic code you write is cross-platform (i.e. using backslashes in paths only works on Windows - forward slashes works on all OS's), then Mono shouldn't have major problems running an unmodified WinForms program. Just make sure you test for graphical glitches.</p>\n"}, {'answer_id': 219361, 'author': 'stephenbayer', 'author_id': 18893, 'author_profile': 'https://Stackoverflow.com/users/18893', 'pm_score': 0, 'selected': False, 'text': "<p>I asked a similar question last week. I've been using Mono all along, and have had no issues running the applications I compile to IL to run on SuSE linux (I usually run KDE) or windows, however, I've not gone out and got a mac yet to test it on. I will be soon, though, probably with in a couple weeks. But all and all development in Mono has been very good at creating application that will run on multiple platforms. </p>\n"}, {'answer_id': 385653, 'author': 'Emrah Diril', 'author_id': 30581, 'author_profile': 'https://Stackoverflow.com/users/30581', 'pm_score': 3, 'selected': True, 'text': '<blockquote>\n <p>I\'m thinking of redoing it in Adobe AIR</p>\n</blockquote>\n\n<p>Not having spent much time with AIR, my personal opinion is that it is best for bringing a webapp to the desktop and provide a shell to it or run your existing flash/flex project on the desktop. </p>\n\n<p>Btw, if you don\'t know ActionScript, I mean its details, quirks, etc, don\'t forget to factor in the time it will take googling for answers.</p>\n\n<blockquote>\n <p>Are there any arguments in favor of WinForms as a cross-platform app? \n Is there a cross-platform future for Winforms (e.g., Mono, etc.)?</p>\n</blockquote>\n\n<p>It\'s always hard to predict what will happen, but there is at least one project (Plastic SCM) I know of which uses Mono Winforms on Win, Mac and Linux, so it is certainly doable. However, they say they built most of their controls from the ground up (and claim they want to release them as open source, but not sure if or when), so you will need to put in some work to make things look "pretty". </p>\n\n<p>I played with Winforms on non-windows platforms and unfortunately, it isn\'t exactly "mature" (especially on Mac). So what you get out of the box may or may not be sufficient for your needs.</p>\n\n<p>If you decide a desktop app is not the best way to provide a cross-platform solution, you can always take your business logic written in C# and create either a full-blown webapp with ASP.NET or go with Silverlight, so many other options exist with C#.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8047/'] |
72,593 | <p>Why does the use of temp tables with a SELECT statement improve the logical I/O count? Wouldn't it increase the amount of hits to a database instead of decreasing it. Is this because the 'problem' is broken down into sections? I'd like to know what's going on behind the scenes.</p>
| [{'answer_id': 72631, 'author': 'Matthias Winkelmann', 'author_id': 4494, 'author_profile': 'https://Stackoverflow.com/users/4494', 'pm_score': 0, 'selected': False, 'text': '<p>AFAIK, at least with mysql, tmp tables are kept in RAM, making SELECTs much faster than anything that hits the HD</p>\n'}, {'answer_id': 73207, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 0, 'selected': False, 'text': "<p>There are a class of problems where building the result in a collection structure on the database side is much preferable to returning the result's parts to the client, roundtripping for each part.</p>\n\n<p>For example: arbitrary depth recursive relationships (boss of)</p>\n\n<p>There's another class of query problems where the data is not and will not be indexed in a manner that makes the query run efficiently. Pulling results into a collection structure, which can be indexed in a custom way, will reduce the logical IO for these queries.</p>\n"}, {'answer_id': 73977, 'author': 'Jeremiah Peschka', 'author_id': 11780, 'author_profile': 'https://Stackoverflow.com/users/11780', 'pm_score': 1, 'selected': False, 'text': "<p>I'm going to assume by temp tables you mean a sub-select in a WHERE clause. (This is referred to as a semijoin operation and you can usually see that in the text execution plan for your query.) </p>\n\n<p>When the query optimizer encounter a sub-select/temp table, it makes some assumptions about what to do with that data. Essentially, the optimizer will create an execution plan that performs a join on the sub-select's result set, reducing the number of rows that need to be read from the other tables. Since there are less rows, the query engine is able to read less pages from disk/memory and reduce the amount of I/O required.</p>\n"}, {'answer_id': 75707, 'author': 'Chris Smith', 'author_id': 9073, 'author_profile': 'https://Stackoverflow.com/users/9073', 'pm_score': 3, 'selected': True, 'text': '<p>There\'s no general answer. It depends on how the temp table is being used.</p>\n\n<p>The temp table may reduce IO by caching rows created after a complex filter/join that are used multiple times later in the batch. This way, the DB can avoid hitting the base tables multiple times when only a subset of the records are needed.</p>\n\n<p>The temp table may increase IO by storing records that are never used later in the query, or by taking up a lot of space in the engine\'s cache that could have been better used by other data.</p>\n\n<p>Creating a temp table to use all of its contents once is slower than including the temp\'s query in the main query because the query optimizer can\'t see past the temp table and it forces a (probably) unnecessary <a href="http://msdn.microsoft.com/en-us/library/ms181032.aspx" rel="nofollow noreferrer">spool</a> of the data instead of allowing it to stream from the source tables.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466/'] |
72,615 | <p>I have a non-.Net executable file that is included in my .net assembly as an embedded resource. Is there a way to run this executable that does not involve writing it out to disk and launching it?</p>
<p>This is .Net 2.0.</p>
| [{'answer_id': 72742, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 3, 'selected': True, 'text': '<p>You can load a .NET assembly from a byte array using an overload of <a href="http://msdn.microsoft.com/en-us/library/twt16z2x.aspx" rel="nofollow noreferrer">Assembly.Load</a>.</p>\n<p>However, there are implications for the security model that need to be considered which make things more complex. See the discussion <a href="http://blogs.msdn.com/shawnfa/archive/2007/04/18/loading-an-assembly-as-a-byte-array.aspx" rel="nofollow noreferrer">here</a>, and also this <a href="https://web.archive.org/web/20160513112857/http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.clr/2006-08/msg00069.html" rel="nofollow noreferrer">thread</a>.</p>\n<p>If your embedded executable is not .NET then I think you will have to write it out to disk first.</p>\n'}, {'answer_id': 79595, 'author': 'Jacob Krall', 'author_id': 3140, 'author_profile': 'https://Stackoverflow.com/users/3140', 'pm_score': 2, 'selected': False, 'text': '<p>You might try injecting your exe into a suspended process and then awakening the hijacked process, but this seems like a recipe for disaster.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9323/'] |
72,616 | <p>I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, <em>not</em> a source code file -- but embed that file in the executable file like a resource.</p>
<p>(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)</p>
<p>Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)</p>
| [{'answer_id': 72692, 'author': 'vava', 'author_id': 6258, 'author_profile': 'https://Stackoverflow.com/users/6258', 'pm_score': 2, 'selected': False, 'text': '<p>Use macros. Technically that file would be <em>source code</em> file but it wouldn\'t look like this.\nExample:</p>\n\n<pre><code>//queries.incl - SQL queries\nQ(SELECT * FROM Users)\nQ(INSERT [a] INTO Accounts)\n\n\n//source.cpp\n#define Q(query) #query,\nchar * queries[] = {\n#include "queries.incl"\n};\n#undef Q\n</code></pre>\n\n<p>Later on you could do all sorts of other processing on that file by the same file, say you\'d want to have array and a hash map of them, you could redefine Q to do another job and be done with it. </p>\n'}, {'answer_id': 72701, 'author': 'introp', 'author_id': 8398, 'author_profile': 'https://Stackoverflow.com/users/8398', 'pm_score': 1, 'selected': False, 'text': '<p>It\'s slightly ugly, but you can always use something like:</p>\n\n<pre>const char *query_foo =\n#include "query_foo.txt"\n\nconst char *query_bar =\n#include "query_bar.txt"\n</pre>\n\n<p>Where query_foo.txt would contain the quoted query text.</p>\n'}, {'answer_id': 72714, 'author': 'Trent', 'author_id': 9083, 'author_profile': 'https://Stackoverflow.com/users/9083', 'pm_score': 2, 'selected': False, 'text': '<p>You can always write a small program or script to convert your text file into a header file and run it as part of your build process.</p>\n'}, {'answer_id': 72751, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 0, 'selected': False, 'text': '<p>I have seen this to be done by converting the resource file to a C source file with only one char array defined containing the content of resource file in a hexadecimal format (to avoid problems with malicious characters). This automatically generated source file is then simply compiled and linked to the project. </p>\n\n<p>It should be pretty easy to implement the convertor to dump C file for each resource file also as to write some facade functions for accessing the resources.</p>\n'}, {'answer_id': 72786, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 6, 'selected': True, 'text': '<p>You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, <a href="http://www.linuxjournal.com/content/embedding-file-executable-aka-hello-world-version-5967" rel="noreferrer">here</a> for more information.</p>\n'}, {'answer_id': 73653, 'author': 'tfinniga', 'author_id': 9042, 'author_profile': 'https://Stackoverflow.com/users/9042', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a sample that we used for cross-platform embeddeding of files.\nIt\'s pretty simplistic, but will probably work for you.</p>\n\n<p>You may also need to change how it\'s handling linefeeds in the escapeLine function.</p>\n\n<pre><code>#include <string>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n\nusing namespace std;\n\nstd::string escapeLine( std::string orig )\n{\n string retme;\n for (unsigned int i=0; i<orig.size(); i++)\n {\n switch (orig[i])\n {\n case \'\\\\\':\n retme += "\\\\\\\\";\n break;\n case \'"\':\n retme += "\\\\\\"";\n break;\n case \'\\n\': // Strip out the final linefeed.\n break;\n default:\n retme += orig[i];\n }\n }\n retme += "\\\\n"; // Add an escaped linefeed to the escaped string.\n return retme;\n}\n\nint main( int argc, char ** argv )\n{\n string filenamein, filenameout;\n\n if ( argc > 1 )\n filenamein = argv[ 1 ];\n else\n {\n // Not enough arguments\n fprintf( stderr, "Usage: %s <file to convert.mel> [ <output file name.mel> ]\\n", argv[0] );\n exit( -1 );\n }\n\n if ( argc > 2 )\n filenameout = argv[ 2 ];\n else\n {\n string new_ending = "_mel.h";\n filenameout = filenamein;\n std::string::size_type pos;\n pos = filenameout.find( ".mel" );\n if (pos == std::string::npos)\n filenameout += new_ending;\n else\n filenameout.replace( pos, new_ending.size(), new_ending );\n }\n\n printf( "Converting \\"%s\\" to \\"%s\\"\\n", filenamein.c_str(), filenameout.c_str() );\n\n ifstream filein( filenamein.c_str(), ios::in );\n ofstream fileout( filenameout.c_str(), ios::out );\n\n if (!filein.good())\n {\n fprintf( stderr, "Unable to open input file %s\\n", filenamein.c_str() );\n exit( -2 );\n }\n if (!fileout.good())\n {\n fprintf( stderr, "Unable to open output file %s\\n", filenameout.c_str() );\n exit( -3 );\n }\n\n // Write the file.\n fileout << "tempstr = ";\n\n while( filein.good() )\n {\n string buff;\n if ( getline( filein, buff ) )\n {\n fileout << "\\"" << escapeLine( buff ) << "\\"" << endl;\n }\n }\n\n fileout << ";" << endl;\n\n filein.close();\n fileout.close();\n\n return 0;\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12193/'] |
72,626 | <p>I save stuff in an <a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx" rel="nofollow noreferrer">Isolated Storage</a> file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my <a href="http://en.wikipedia.org/wiki/Data_access_layer" rel="nofollow noreferrer">DAL</a> layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept:</p>
<pre><code> public void Save(int number)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream =
new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage);
StreamWriter writer = new StreamWriter(fileStream);
writer.WriteLine(number);
writer.Close();
}
public int Retrieve()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage);
StreamReader reader = new StreamReader(fileStream);
int number;
try
{
string line = reader.ReadLine();
number = int.Parse(line);
}
finally
{
reader.Close();
}
return number;
}
</code></pre>
<p>I've tried using all the GetMachineStoreFor* scopes.</p>
<p>EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> application.</p>
| [{'answer_id': 72736, 'author': 'icelava', 'author_id': 2663, 'author_profile': 'https://Stackoverflow.com/users/2663', 'pm_score': 3, 'selected': True, 'text': '<p>When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine?</p>\n\n<p>Ok now that you have illustrated your code style and I have gone back to retesting the behaviour of the methods, here is the explanation:</p>\n\n<ul>\n<li>GetMachineStoreForAssembly() - scoped to the machine and the assembly identity. Different assemblies in the same application would have their own isolated storage.</li>\n<li>GetMachineStoreForDomain() - a misnomer in my opinion. scoped to the machine and the domain identity <em>on top of</em> the assembly identity. There should have been an option for just AppDomain alone.</li>\n<li>GetMachineStoreForApplication() - this is the one you are looking for. I have tested it and different assemblies can pick up the values written in another assembly. The only catch is, the <em>application identity</em> must be verifiable. When running locally, it cannot be properly determined and it will end up with exception "Unable to determine application identity of the caller". It can be verified by deploying the application via Click Once. Only then can this method apply and achieve its desired effect of shared isolated storage.</li>\n</ul>\n'}, {'answer_id': 73400, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 1, 'selected': False, 'text': '<p>When you are saving, you are calling GetMachineStoreForDomain, but when you are retrieving, you are calling GetMachineStoreForAssembly.</p>\n\n<p>GetMachineStoreForAssembly is scoped to the assembly that the code is executing in, while the GetMachineStoreForDomain is scoped to the currently running AppDomain and the assembly where the code is executing. Just change your these calls to GetMachineStoreForApplication, and it should work.</p>\n\n<p>The documentation for IsolatedStorageFile can be found at <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3397/'] |
72,639 | <p>I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007.
The trouble is finding a technique to read ALL versions.</p>
<p>More info: </p>
<pre><code> - I am currently using php-ExcelReader.
- A script in a language other than php that can convert Excel to CSV would be an acceptable solution.
</code></pre>
| [{'answer_id': 72669, 'author': 'Erratic', 'author_id': 2246765, 'author_profile': 'https://Stackoverflow.com/users/2246765', 'pm_score': 2, 'selected': False, 'text': '<p>Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end.</p>\n\n<p>Assuming that isn\'t an option a quick google search turned up <a href="http://sourceforge.net/projects/phpexcelreader/" rel="nofollow noreferrer">http://sourceforge.net/projects/phpexcelreader/</a> which might suit your needs.</p>\n'}, {'answer_id': 75493, 'author': 'gobansaor', 'author_id': 8967, 'author_profile': 'https://Stackoverflow.com/users/8967', 'pm_score': 0, 'selected': False, 'text': '<p>The open-source ETL tool Talend (<a href="http://wwww.talend.com" rel="nofollow noreferrer">http://wwww.talend.com</a>) will generate Java or Perl code and package such code with the necessary 3rd party libraries. </p>\n\n<p>Talend should be able to handle all versions of Excel and output the result set in any format you require (including loading it directly into a database if need be).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12231/'] |
72,667 | <p>I have a repeatable business process that I execute every week as part of my configuration management responsibilities. The process does not change: I download change details into Excel, open the spreadsheet and copy out details based on a macro, create a Word document from an agenda template, update the agenda with the Excel data, create PDFs from the Word document, and email them out.</p>
<p>This process is very easily represented in a sequence workflow and that's how I have it so far, with COM automation to handle the Excel and Word pieces automatically. The wrench in the gears is that there is a human step between "create agenda" and "send it out," wherein I review the change details and formulate questions about them, which are added to the agenda. I currently have a Suspend activity to suspend the workflow while I manually do this piece of the process.</p>
<p>My question is, should I rewrite my workflow to make it a state machine to follow a best practice for human interaction in a business process, or is the Suspend activity a reasonable solution?</p>
| [{'answer_id': 72669, 'author': 'Erratic', 'author_id': 2246765, 'author_profile': 'https://Stackoverflow.com/users/2246765', 'pm_score': 2, 'selected': False, 'text': '<p>Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end.</p>\n\n<p>Assuming that isn\'t an option a quick google search turned up <a href="http://sourceforge.net/projects/phpexcelreader/" rel="nofollow noreferrer">http://sourceforge.net/projects/phpexcelreader/</a> which might suit your needs.</p>\n'}, {'answer_id': 75493, 'author': 'gobansaor', 'author_id': 8967, 'author_profile': 'https://Stackoverflow.com/users/8967', 'pm_score': 0, 'selected': False, 'text': '<p>The open-source ETL tool Talend (<a href="http://wwww.talend.com" rel="nofollow noreferrer">http://wwww.talend.com</a>) will generate Java or Perl code and package such code with the necessary 3rd party libraries. </p>\n\n<p>Talend should be able to handle all versions of Excel and output the result set in any format you require (including loading it directly into a database if need be).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7565/'] |
72,671 | <p>I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.</p>
<p>However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?</p>
<p>E.g. batch file</p>
<pre><code>start "c:\path with spaces\app.exe" param1 "param with spaces"
</code></pre>
| [{'answer_id': 72726, 'author': 'Curro', 'author_id': 10688, 'author_profile': 'https://Stackoverflow.com/users/10688', 'pm_score': -1, 'selected': False, 'text': '<p>Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.</p>\n'}, {'answer_id': 72758, 'author': 'Steffen', 'author_id': 6919, 'author_profile': 'https://Stackoverflow.com/users/6919', 'pm_score': 4, 'selected': False, 'text': '<p>Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>start "Dummy Title" "c:\\path with spaces\\app.exe" param1 "param with spaces"\n</code></pre>\n'}, {'answer_id': 72796, 'author': 'Andy', 'author_id': 3857, 'author_profile': 'https://Stackoverflow.com/users/3857', 'pm_score': 8, 'selected': True, 'text': '<p>Actually, his example won\'t work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:</p>\n\n<pre><code>start "" "c:\\path with spaces\\app.exe" param1 "param with spaces"\n</code></pre>\n\n<p>You can change the first argument to be whatever you want the title of the new command prompt to be. If it\'s a Windows app that is created, then the command prompt won\'t be displayed, and the title won\'t matter.</p>\n'}, {'answer_id': 2005695, 'author': 'user243871', 'author_id': 243871, 'author_profile': 'https://Stackoverflow.com/users/243871', 'pm_score': 0, 'selected': False, 'text': '<p>You are to use something like this:</p>\n<blockquote>\n<p>start /d C:\\Windows\\System32\\calc.exe</p>\n<p>start /d "C:\\Program Files\\Mozilla</p>\n<p>Firefox" firefox.exe start /d</p>\n<p>"C:\\Program Files\\Microsoft</p>\n<p>Office\\Office12" EXCEL.EXE</p>\n</blockquote>\n<p>Also I advice you to use special batch files editor - <a href="http://www.drbatcher.com" rel="nofollow noreferrer">Dr.Batcher</a></p>\n'}, {'answer_id': 11968030, 'author': 'Mark Agate', 'author_id': 1600397, 'author_profile': 'https://Stackoverflow.com/users/1600397', 'pm_score': 1, 'selected': False, 'text': '<p>Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.</p>\n'}, {'answer_id': 19316499, 'author': 'Anupam Kapoor', 'author_id': 2870697, 'author_profile': 'https://Stackoverflow.com/users/2870697', 'pm_score': -1, 'selected': False, 'text': '<p>I researched successfully and it is working fine for me. My requirement is to sent an email using vbscript which needs to be call from a batch file in windows. Here is the exact command I am using with no errors.</p>\n\n<pre><code>START C:\\Windows\\System32\\cscript.exe "C:\\Documents and Settings\\akapoor\\Desktop\\Mail.vbs"\n</code></pre>\n'}, {'answer_id': 43467194, 'author': 'Mustafa Kemal', 'author_id': 3835640, 'author_profile': 'https://Stackoverflow.com/users/3835640', 'pm_score': 2, 'selected': False, 'text': '<pre><code>start "" "c:\\path with spaces\\app.exe" "C:\\path parameter\\param.exe"\n</code></pre>\n\n<p>When I used above suggestion, I\'ve got:</p>\n\n<blockquote>\n <p>\'c:\\path\' is not recognized a an internal or external command, operable program or batch file. </p>\n</blockquote>\n\n<p>I think second qoutation mark prevent command to run. After some search below solution save my day:</p>\n\n<pre><code>start "" CALL "c:\\path with spaces\\app.exe" "C:\\path parameter\\param.exe"\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,672 | <p>Has anyone written an 'UnFormat' routine for Delphi?</p>
<p>What I'm imagining is the <em>inverse</em> of <em>SysUtils.Format</em> and looks something like this </p>
<p>UnFormat('a number %n and another %n',[float1, float2]); </p>
<p>So you could unpack a string into a series of variables using format strings.</p>
<p>I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.</p>
| [{'answer_id': 72713, 'author': 'PatrickvL', 'author_id': 12170, 'author_profile': 'https://Stackoverflow.com/users/12170', 'pm_score': 5, 'selected': True, 'text': '<p>This is called scanf in C, I\'ve made a Delphi look-a-like for this :</p>\n\n<pre><code>function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;\nvar\n InputOffset: Integer;\n FormatOffset: Integer;\n InputChar: Char;\n FormatChar: Char;\n\n function _GetInputChar: Char;\n begin\n if InputOffset <= Length(Input) then\n begin\n Result := Input[InputOffset];\n Inc(InputOffset);\n end\n else\n Result := #0;\n end;\n\n function _PeekFormatChar: Char;\n begin\n if FormatOffset <= Length(Format) then\n Result := Format[FormatOffset]\n else\n Result := #0;\n end;\n\n function _GetFormatChar: Char;\n begin\n Result := _PeekFormatChar;\n if Result <> #0 then\n Inc(FormatOffset);\n end;\n\n function _ScanInputString(const Arg: Pointer = nil): string;\n var\n EndChar: Char;\n begin\n Result := \'\';\n EndChar := _PeekFormatChar;\n InputChar := _GetInputChar;\n while (InputChar > \' \')\n and (InputChar <> EndChar) do\n begin\n Result := Result + InputChar;\n InputChar := _GetInputChar;\n end;\n\n if InputChar <> #0 then\n Dec(InputOffset);\n\n if Assigned(Arg) then\n PString(Arg)^ := Result;\n end;\n\n function _ScanInputInteger(const Arg: Pointer): Boolean;\n var\n Value: string;\n begin\n Value := _ScanInputString;\n Result := TryStrToInt(Value, {out} PInteger(Arg)^);\n end;\n\n procedure _Raise;\n begin\n raise EConvertError.CreateFmt(\'Unknown ScanFormat character : "%s"!\', [FormatChar]);\n end;\n\nbegin\n Result := 0;\n InputOffset := 1;\n FormatOffset := 1;\n FormatChar := _GetFormatChar;\n while FormatChar <> #0 do\n begin\n if FormatChar <> \'%\' then\n begin\n InputChar := _GetInputChar;\n if (InputChar = #0)\n or (FormatChar <> InputChar) then\n Exit;\n end\n else\n begin\n FormatChar := _GetFormatChar;\n case FormatChar of\n \'%\':\n if _GetInputChar <> \'%\' then\n Exit;\n \'s\':\n begin\n _ScanInputString(Args[Result]);\n Inc(Result);\n end;\n \'d\', \'u\':\n begin\n if not _ScanInputInteger(Args[Result]) then\n Exit;\n\n Inc(Result);\n end;\n else\n _Raise;\n end;\n end;\n\n FormatChar := _GetFormatChar;\n end;\nend;\n</code></pre>\n'}, {'answer_id': 73750, 'author': 'skamradt', 'author_id': 9217, 'author_profile': 'https://Stackoverflow.com/users/9217', 'pm_score': 1, 'selected': False, 'text': '<p>I tend to take care of this using a simple parser. I have two functions, one is called NumStringParts which returns the number of "parts" in a string with a specific delimiter (in your case above the space) and GetStrPart returns the specific part from a string with a specific delimiter. Both of these routines have been used since my Turbo Pascal days in many a project.</p>\n\n<pre><code>function NumStringParts(SourceStr,Delimiter:String):Integer;\nvar\n offset : integer;\n curnum : integer;\nbegin\n curnum := 1;\n offset := 1;\n while (offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n Inc(CurNum);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n end;\n end;\n result := CurNum;\nend;\n\nfunction GetStringPart(SourceStr,Delimiter:String;Num:Integer):string;\nvar\n offset : integer;\n CurNum : integer;\n CurPart : String;\nbegin\n CurNum := 1;\n Offset := 1;\n While (CurNum <= Num) and (Offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n CurPart := Copy(SourceStr,1,Offset-1);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n Inc(CurNum)\n end\n else\n CurPart := SourceStr;\n end;\n if CurNum >= Num then\n Result := CurPart\n else\n Result := \'\';\nend;\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code> var\n st : string;\n f1,f2 : double; \n begin\n st := \'a number 12.35 and another 13.415\';\n ShowMessage(\'Total String parts = \'+IntToStr(NumStringParts(st,#32)));\n f1 := StrToFloatDef(GetStringPart(st,#32,3),0.0);\n f2 := StrToFloatDef(GetStringPart(st,#32,6),0.0);\n ShowMessage(\'Float 1 = \'+FloatToStr(F1)+\' and Float 2 = \'+FloatToStr(F2)); \n end; \n</code></pre>\n\n<p>These routines work wonders for simple or strict comma delimited strings too. These routines work wonderfully in Delphi 2009/2010.</p>\n'}, {'answer_id': 76566, 'author': 'Toby Allen', 'author_id': 6244, 'author_profile': 'https://Stackoverflow.com/users/6244', 'pm_score': 2, 'selected': False, 'text': '<p>I know it tends to scare people, but you could write a simple function to do this using regular expressions </p>\n\n<pre><code>\'a number (.*?) and another (.*?)\n</code></pre>\n\n<p>If you are worried about reg expressions take a look at <a href="http://www.regexbuddy.com" rel="nofollow noreferrer">www.regexbuddy.com</a> and you\'ll never look back.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12376/'] |
72,677 | <p>Imagine I have String in C#: "I Don’t see ya.."</p>
<p>I want to remove (replace to nothing or etc.) these "’" symbols. </p>
<p>How do I do this?</p>
| [{'answer_id': 72698, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 0, 'selected': False, 'text': '<p>The ASCII / Integer code for these characters would be out of the normal alphabetic Ranges. Seek and replace with empty characters. String has a Replace method I believe.</p>\n'}, {'answer_id': 72752, 'author': 'itsmatt', 'author_id': 7862, 'author_profile': 'https://Stackoverflow.com/users/7862', 'pm_score': 1, 'selected': False, 'text': '<p>Consider Regex.Replace(your_string, regex, "") - that\'s what I use.</p>\n'}, {'answer_id': 72759, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre><code>"I Don’t see ya..".Replace( "’", string.Empty);\n</code></pre>\n\n<p>How did that junk get in there the first place? That\'s the real question.</p>\n'}, {'answer_id': 72770, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 1, 'selected': False, 'text': '<p>Test each character in turn to see if it is a valid alphabetic or numeric character and if not then remove it from the string. The character test is very simple, just use...</p>\n\n<pre><code>char.IsLetterOrDigit;\n</code></pre>\n\n<p>Please there are various others such as...</p>\n\n<pre><code>char.IsSymbol;\nchar.IsControl;\n</code></pre>\n'}, {'answer_id': 72844, 'author': 'Allan Wind', 'author_id': 9706, 'author_profile': 'https://Stackoverflow.com/users/9706', 'pm_score': 0, 'selected': False, 'text': '<p>Either use a blacklist of stuff you do not want, or preferably a white list (set). With a white list you iterate over the string and only copy the letters that are in your white list to the result string. You said remove, and the way you do that is having two pointers one you read from (R) and one you write to (W):</p>\n\n<pre><code>I Donââ‚\n W R\n</code></pre>\n\n<p>if comma is in your whitelist then you would in this case read the comma and write it where à is then advance both pointers. UTF-8 is a multi-byte encoding, so you advancing the pointer may not just be adding to the address.</p>\n\n<p>With C an easy to way to get a white list by using one of the predefined functions (or macros): isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit. In this case you send up with a white list function instead of a set of course.</p>\n\n<p>Usually when I see data like you have I look for memory corruption, or evidence to suggest that the encoding I expect is different than the one the data was entered with.</p>\n\n<p>/Allan</p>\n'}, {'answer_id': 72933, 'author': 'willasaywhat', 'author_id': 12234, 'author_profile': 'https://Stackoverflow.com/users/12234', 'pm_score': 2, 'selected': False, 'text': '<p>This looks disturbingly familiar to a character encoding issue dealing with the Windows character set being stored in a database using the standard character encoding. I see someone voted Will down, but he has a point. You may be solving the immediate issue, but the combinations of characters are limitless if this is the issue.</p>\n'}, {'answer_id': 72972, 'author': 'Marc Hughes', 'author_id': 6791, 'author_profile': 'https://Stackoverflow.com/users/6791', 'pm_score': 2, 'selected': False, 'text': '<p>By removing any non-latin character you\'ll be intentionally breaking some internationalization support.</p>\n\n<p>Don\'t forget the poor guy who\'s name has a "â" in it.</p>\n'}, {'answer_id': 72989, 'author': 'Liedman', 'author_id': 890, 'author_profile': 'https://Stackoverflow.com/users/890', 'pm_score': 2, 'selected': False, 'text': "<p>If you really have to do this, regular expressions are probably the best solution.</p>\n\n<p>I would strongly recommend that you think about why you have to do this, though - at least some of the characters your listing as undesirable are perfectly valid and useful in other languages, and just filtering them out will most likely annoy at least some of your international users. As a swede, I can't emphasize enough how much I <i>hate</i> systems that can't handle our å, ä and ö characters correctly.</p>\n"}, {'answer_id': 73302, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 5, 'selected': True, 'text': "<p>That 'junk' looks a lot like someone interpreted UTF-8 data as ISO 8859-1 or Windows-1252, probably repeatedly.</p>\n\n<p>’ is the sequence C3 A2, E2 82 AC, E2 84 A2.</p>\n\n<ul>\n<li>UTF-8 C3 A2 = U+00E2 = â</li>\n<li>UTF-8 E2 82 AC = U+20AC = €</li>\n<li>UTF-8 E2 84 A2 = U+2122 = ™</li>\n</ul>\n\n<p>We then do it again: in Windows 1252 this sequence is E2 80 99, so the character should have been U+2019, RIGHT SINGLE QUOTATION MARK (’)</p>\n\n<p>You could make multiple passes with byte arrays, Encoding.UTF8 and Encoding.GetEncoding(1252) to correctly turn the junk back into what was originally entered. You will need to check your processing to find the two places that UTF-8 data was incorrectly interpreted as Windows-1252.</p>\n"}, {'answer_id': 73587, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Regex.Replace("The string", "[^a-zA-Z ]","");</p>\n\n<p>That\'s how you\'d do it in C#, although that regular expression ([^a-zA-Z ]) should work in most languages.</p>\n\n<p>[Edited: forgot the space in the regex]</p>\n'}, {'answer_id': 16419143, 'author': 'Chandra Sekhar k', 'author_id': 2358323, 'author_profile': 'https://Stackoverflow.com/users/2358323', 'pm_score': 0, 'selected': False, 'text': '<p>If String having the any Junk date , This is good to way remove those junk date </p>\n\n<pre><code> string InputString = "This is grate kingdom¢Ã‚¬â"; \n string replace = "’";\n string OutputString= Regex.Replace(InputString, replace, "");\n\n //OutputString having the following result \n</code></pre>\n\n<p>It\'s working good to me , thanks for looking this review.</p>\n'}, {'answer_id': 27134222, 'author': 'BrianP007', 'author_id': 4282598, 'author_profile': 'https://Stackoverflow.com/users/4282598', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same problem with extraneous junk thrown in by adobe in an EXIF dump. I spent an hour looking for a straight answer and trying numerous half-baked suggestions which did not work here.</p>\n\n<p>This thread more than most I have read was replete with deep, probing questions like \'how did it get there?\', \'what if somebody has this character in their name?\', \'are you sure you want to break internationalization?\'. </p>\n\n<p>There were some impressive displays of erudition positing how this junk could have gotten here and explaining the evolution of the various character encoding schemes. The person wanted to know how to remove it, not how it came to be or what the standards orgs are up to, interesting as this trivia may be. </p>\n\n<p>I wrote a tiny program which gave me the right answer. Instead of paraphrasing the main concept, here is the entire, self-contained, working (at least on my system) program and the output I used to nuke the junk:</p>\n\n<pre><code>#!/usr/local/bin/perl -w\n\n# This runs in a dos window and shows the char, integer and hex values\n# for the weird chars. Install the HEX values in the REGEXP below until\n# the final test line looks normal. \n$str = \'s: “Brian\'; # Nuke the 3 werid chars in front of Brian.\n@str = split(//, $str);\nprintf("len str \'$str\' = %d, scalar \\@str = %d\\n", \n length $str, scalar @str);\n$ii = -1;\nforeach $c (@str) {\n $ii++;\n printf("$ii) char \'$c\', ord=%03d, hex=\'%s\'\\n", \n ord($c), unpack("H*", $c));\n}\n# Take the hex characters shown above, plug them into the below regexp\n# until the junk disappears!\n($s2 = $str) =~ s/[\\xE2\\x80\\x9C]//g; # << Insert HEX values HERE\nprint("S2=>$s2<\\n"); # Final test\n\nResult:\nM:\\new\\6s-2014.1031-nef.halloween>nuke_junk.pl\nlen str \'s: GÇ£Brian\' = 11, scalar @str = 11\n0) char \'s\', ord=115, hex=\'73\'\n1) char \':\', ord=058, hex=\'3a\'\n2) char \' \', ord=032, hex=\'20\'\n3) char \'G\', ord=226, hex=\'e2\'\n4) char \'Ç\', ord=128, hex=\'80\'\n5) char \'£\', ord=156, hex=\'9c\'\n6) char \'B\', ord=066, hex=\'42\'\n7) char \'r\', ord=114, hex=\'72\'\n8) char \'i\', ord=105, hex=\'69\'\n9) char \'a\', ord=097, hex=\'61\'\n10) char \'n\', ord=110, hex=\'6e\'\nS2=>s: Brian<\n</code></pre>\n\n<p>It\'s NORMAL!!!</p>\n\n<p>One other actionable, working suggestion I ran across:\n iconv -c -t ASCII < 6s-2014.1031-238246.halloween.exf.dif > exf.ascii.dif</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5369/'] |
72,682 | <p>Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.</p>
<p>Now you have a method, and you want to return a value. You <em>also</em> want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:</p>
<pre><code>class FunctionResult<T>
{
public T payload;
public int result;
}
</code></pre>
<p>And then declare your functions like this:</p>
<pre><code>FunctionResult<string> MyFunction()
{
FunctionResult<string> result;
//...
return result;
}
</code></pre>
<p>One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?</p>
| [{'answer_id': 72729, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 1, 'selected': False, 'text': '<p>How about the "Can\'t decide whether this is an error or not" pattern. Seems like if you really had an exception but wanted to return a partial result, you\'d wrap the result in the exception.</p>\n'}, {'answer_id': 72808, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 2, 'selected': False, 'text': '<p>I am not sure this is an anti-pattern. I have commonly seen this used instead of exceptions for performance reasons, or perhaps to make the fact that the method can fail more explicit. To me, it seems to be a personal preference rather than an anti-pattern.</p>\n'}, {'answer_id': 72840, 'author': 'rmaruszewski', 'author_id': 6856, 'author_profile': 'https://Stackoverflow.com/users/6856', 'pm_score': 4, 'selected': False, 'text': '<p>It is called "<a href="http://www.refactoring.com/catalog/replaceErrorCodeWithException.html" rel="nofollow noreferrer">Replace Error Code with Exception</a>"</p>\n'}, {'answer_id': 72846, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 3, 'selected': False, 'text': "<p>Well, it's <em>not</em> an antipattern. The C++ standard library makes use of this feature and .NET even offers a special <code>FunctionResult</code> class in the .NET framework. It's called <code>Nullable</code>. Yes, this isn't restricted to function results but it can be used for such cases and is actually very useful here. If .NET 1.0 had already had the <code>Nullable</code> class, it would certainly have been used for the <code>NumberType.TryParse</code> methods, instead of the <code>out</code> parameter.</p>\n"}, {'answer_id': 72884, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 2, 'selected': False, 'text': '<p>This approach is actually much better than some others that I have seen. Some functions in C, for example, when they encounter an error they return and seem to succeed. The only way to tell that they failed is to call a function that will get the latest error.</p>\n\n<p>I spent hours trying to debug semaphore code on my MacBook before I finally found out that sem_init doesn\'t work on OSX! It compiled without error and ran without causing any errors - yet the semaphore didn\'t work and I couldn\'t figure out why. I pity the people that port an application that uses <a href="http://www.csc.villanova.edu/~mdamian/threads/posixsem.html" rel="nofollow noreferrer">POSIX semaphores</a> to OSX and must deal with resource contention issues that have already been debugged.</p>\n'}, {'answer_id': 72906, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 3, 'selected': False, 'text': "<p>I usually pass the payload as (not const) reference and the error code as a return value.</p>\n\n<p>I'm a game developer, we banish exceptions</p>\n"}, {'answer_id': 72922, 'author': 'Dan Fleet', 'author_id': 7470, 'author_profile': 'https://Stackoverflow.com/users/7470', 'pm_score': 5, 'selected': True, 'text': "<p>I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters).</p>\n\n<p>There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary.</p>\n\n<p>This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response.</p>\n"}, {'answer_id': 72980, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 1, 'selected': False, 'text': "<p>If you don't want to use exceptions, the cleanest way to do it is to have the function return the error/success code and take either a reference or pointer argument that gets filled in with the result.</p>\n\n<p>I would not call it an anti-pattern. It's a very well proven workable method that's often preferable to using exceptions. </p>\n"}, {'answer_id': 73016, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 1, 'selected': False, 'text': "<p>If you expect your method to fail occasionally, but don't consider that exceptional, I prefer this pattern as used in the .NET Framework:</p>\n\n<pre><code>bool TryMyFunction(out FunctionResult result){ \n\n //... \n result = new FunctionResult();\n}\n</code></pre>\n"}, {'answer_id': 73020, 'author': 'Peter Davis', 'author_id': 12508, 'author_profile': 'https://Stackoverflow.com/users/12508', 'pm_score': 3, 'selected': False, 'text': '<p>Konrad is right, C# uses dual return values all the time. But I kind of like the TryParse, Dictionary.TryGetValue, etc. methods in C#.</p>\n\n<pre><code>int value;\nif (int.TryParse("123", out value)) {\n // use value\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>int? value = int.TryParse("123");\nif (value != null) {\n // use value\n}\n</code></pre>\n\n<p>...mostly because the Nullable pattern does not scale to non-Value return types (i.e., class instances). This wouldn\'t work with Dictionary.TryGetValue(). And TryGetValue is both nicer than a KeyNotFoundException (no "first chance exceptions" constantly in the debugger, arguably more efficient), nicer than Java\'s practice of get() returning null (what if null values are expected), and more efficient than having to call ContainsKey() first.</p>\n\n<p>But this <em>is</em> still a little bit screwy -- since this looks like C#, then it should be using an out parameter. All efficiency gains are probably lost by instantiating the class.</p>\n\n<p>(Could be Java except for the "string" type being in lowercase. In Java of course you have to use a class to emulate dual return values.)</p>\n'}, {'answer_id': 73706, 'author': 'ARKBAN', 'author_id': 11889, 'author_profile': 'https://Stackoverflow.com/users/11889', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with those that say this is not an anti-pattern. Its a perfectly valid pattern in certain contexts. Exceptions are for <em>exceptional</em> situations, return values (like in your example) should be used in expected situations. Some domains expect valid and invalid results from classes, and neither of those should be modeled as exceptions.</p>\n\n<p>For example, given X amount of gas, can a car get from A to B, and if so how much gas is left over? That kind of question is ideal for the data structure you provided. Not being able to make the trip from A to B is expected, hence an exception should not be used.</p>\n'}, {'answer_id': 74585, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': "<p>In defense of the anti-pattern designation, this code lends itself to being used in a few ways:</p>\n\n<ol>\n<li>Object x = MyFunction().payload; <em>(ignoring the return result - very bad)</em> </li>\n<li>int code = MyFunction().result; <em>(throwing away the payload - may be okay if that's the intended use.)</em> </li>\n<li>FunctionResult x = MyFunction(); //... <em>(a bunch of extra FunctionResult objects and extra code to check them all over the place)</em></li>\n</ol>\n\n<p>If you need to use return codes, that's fine. But then use return codes. Don't try to pack an extra payload in with it. That's what <em>ref</em> and <em>out</em> parameters (C#) are for. Nullable types might be an exception, but only because there's extra sugar baked in the language to support it.</p>\n\n<p>If you still disagree with this assessment, DOWNVOTE this answer (not the whole question). If you do think it's an anti-pattern, then UPVOTE it. We'll use this answer to see what the community thinks.</p>\n"}, {'answer_id': 300661, 'author': 'Mike Dunlavey', 'author_id': 23771, 'author_profile': 'https://Stackoverflow.com/users/23771', 'pm_score': 1, 'selected': False, 'text': '<p>Debates about smells and anti-patterns remind me the "Survivor" TV shows, where you have various programming constructs trying to vote each other off the island. I\'d prefer to see "construct X has such-and-so pros and cons", rather than a continually evolving list of edicts of what should and should not be done.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3043/'] |
72,696 | <p>I have some code like this:</p>
<pre><code>If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
DoSomething()
End If
</code></pre>
<p>I don't care about the case. Should I use <code>OrdinalIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>CurrentCultureIgnoreCase</code>?</p>
| [{'answer_id': 72718, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>It depends on what you want, though I'd shy away from invariantculture unless you're <em>very</em> sure you'll never want to localize the code for other languages. Use CurrentCulture instead.</p>\n\n<p>Also, OrdinalIgnoreCase should respect numbers, which may or may not be what you want.</p>\n"}, {'answer_id': 72766, 'author': 'Robert Taylor', 'author_id': 6375, 'author_profile': 'https://Stackoverflow.com/users/6375', 'pm_score': 9, 'selected': True, 'text': '<p><strong><a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call" rel="noreferrer">Newer .Net Docs now has a table to help you decide which is best to use in your situation.</a></strong></p>\n\n<p>From MSDN\'s "<a href="https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms973919(v=msdn.10)" rel="noreferrer">New Recommendations for Using Strings in Microsoft .NET 2.0</a>"</p>\n\n<blockquote>\n <p>Summary: Code owners previously using the <code>InvariantCulture</code> for string comparison, casing, and sorting should strongly consider using a new set of <code>String</code> overloads in Microsoft .NET 2.0. <em>Specifically, data that is designed to be culture-agnostic and linguistically irrelevant</em> should begin specifying overloads using either the <code>StringComparison.Ordinal</code> or <code>StringComparison.OrdinalIgnoreCase</code> members of the new <code>StringComparison</code> enumeration. These enforce a byte-by-byte comparison similar to <code>strcmp</code> that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.</p>\n</blockquote>\n'}, {'answer_id': 72780, 'author': 'Bullines', 'author_id': 27870, 'author_profile': 'https://Stackoverflow.com/users/27870', 'pm_score': 2, 'selected': False, 'text': "<p>I guess it depends on your situation. Since ordinal comparisons are actually looking at the characters' numeric Unicode values, they won't be the best choice when you're sorting alphabetically. For string comparisons, though, ordinal would be a tad faster.</p>\n"}, {'answer_id': 6406284, 'author': 'Sam Saffron', 'author_id': 17174, 'author_profile': 'https://Stackoverflow.com/users/17174', 'pm_score': 6, 'selected': False, 'text': '<h3>It all depends</h3>\n<p>Comparing unicode strings is hard:</p>\n<blockquote>\n<p>The implementation of Unicode string\nsearches and comparisons in text\nprocessing software must take into\naccount the presence of equivalent\ncode points. In the absence of this\nfeature, users searching for a\nparticular code point sequence would\nbe unable to find other visually\nindistinguishable glyphs that have a\ndifferent, but canonically equivalent,\ncode point representation.</p>\n</blockquote>\n<p>see: <a href="http://en.wikipedia.org/wiki/Unicode_equivalence" rel="noreferrer">http://en.wikipedia.org/wiki/Unicode_equivalence</a></p>\n<hr />\n<p>If you are trying to compare 2 unicode strings in a case insensitive way and want it to work <strong>EVERYWHERE</strong>, you have an impossible problem.</p>\n<p>The classic example is the <a href="http://en.wikipedia.org/wiki/Turkish_dotted_and_dotless_I" rel="noreferrer">Turkish i</a>, which when uppercased becomes İ (notice the dot)</p>\n<p>By default, the .Net framework usually uses the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx" rel="noreferrer">CurrentCulture</a> for string related functions, with a very important exception of <code>.Equals</code> that uses an ordinal (byte by byte) compare.</p>\n<p>This leads, by design, to the various string functions behaving differently depending on the computer\'s culture.</p>\n<hr />\n<p>Nonetheless, sometimes we want a "general purpose", case insensitive, comparison.</p>\n<p>For example, you may want your string comparison to behave the same way, no matter what computer your application is installed on.</p>\n<p>To achieve this we have 3 options:</p>\n<ol>\n<li>Set the culture explicitly and perform a case insensitive compare using unicode equivalence rules.</li>\n<li>Set the culture to the Invariant Culture and perform case insensitive compare using unicode equivalence rules.</li>\n<li>Use <a href="http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx" rel="noreferrer">OrdinalIgnoreCase</a> which will uppercase the string using the InvariantCulture and then perform a byte by byte comparison.</li>\n</ol>\n<p>Unicode equivalence rules are complicated, which means using method 1) or 2) is more expensive than <code>OrdinalIgnoreCase</code>. The fact that <code>OrdinalIgnoreCase</code> does not perform any special unicode normalization, means that some strings that render in the same way on a computer screen, <em>will not</em> be considered identical. For example: <code>"\\u0061\\u030a"</code> and <code>"\\u00e5"</code> both render å. However in a ordinal compare will be considered different.</p>\n<p>Which you choose heavily depends on the application you are building.</p>\n<ul>\n<li>If I was writing a line-of-business app which was only used by Turkish users, I would be sure to use method 1.</li>\n<li>If I just needed a simple "fake" case insensitive compare, for say a column name in a db, which is usually English I would probably use method 3.</li>\n</ul>\n<p>Microsoft has their <a href="http://msdn.microsoft.com/en-us/library/ms973919.aspx" rel="noreferrer">set of recommendations</a> with explicit guidelines. However, it is really important to understand the notion of unicode equivalence prior to approaching these problems.</p>\n<p>Also, please keep in mind that OrdinalIgnoreCase is a <a href="http://www.siao2.com/2004/12/29/344136.aspx" rel="noreferrer">very special kind</a> of beast, that is picking and choosing a bit of an ordinal compare with some mixed in lexicographic aspects. This can be confusing.</p>\n'}, {'answer_id': 11548935, 'author': 'TheMoot', 'author_id': 130112, 'author_profile': 'https://Stackoverflow.com/users/130112', 'pm_score': -1, 'selected': False, 'text': '<p>The very simple answer is, unless you are using Turkish, you don\'t need to use InvariantCulture.</p>\n\n<p>See the following link:</p>\n\n<p><a href="https://stackoverflow.com/questions/3550213/in-c-sharp-what-is-the-difference-between-toupper-and-toupperinvariant">In C# what is the difference between ToUpper() and ToUpperInvariant()?</a> </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7072/'] |
72,699 | <p>For example which is better:</p>
<pre><code>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
</code></pre>
<p>or</p>
<pre><code>select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id
</code></pre>
<p>better as in less work for the database, faster results.</p>
<p><strong>Note:</strong> Sybase, and there's an index on both tables of <code>country+id</code>.</p>
| [{'answer_id': 72738, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': "<p>I'd lean towards only including your constant in the code once. There might be a performance advantage one way or the other, but it's probably so small the maintenance advantage of only one parameter trumps it.</p>\n"}, {'answer_id': 72743, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>The correct answer probably depends on your SQL engine. For MS SQL Server, the first approach is clearly the better because the statistical optimizer is given an additional clue which may help it find a better (more optimal) resolution path.</p>\n'}, {'answer_id': 72745, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I think it depends on the library and database engine. Each one will execute the SQL differently, and there's no telling which one will be optimized.</p>\n"}, {'answer_id': 72746, 'author': 'Alan', 'author_id': 5878, 'author_profile': 'https://Stackoverflow.com/users/5878', 'pm_score': 0, 'selected': False, 'text': "<p>If you ever wish to make the query more general, perhaps substituting a parameter for the target country, then I'd go with your first example, as it requires only a single change. That's less to worry about getting wrong in the future.</p>\n"}, {'answer_id': 72754, 'author': 'mmaibaum', 'author_id': 12213, 'author_profile': 'https://Stackoverflow.com/users/12213', 'pm_score': 0, 'selected': False, 'text': '<p>I suspect this is going to depend on the tables, the data and the meta-data. I expect I could work up examples that would show results both ways - benchmark!</p>\n'}, {'answer_id': 72764, 'author': 'Dave Costa', 'author_id': 6568, 'author_profile': 'https://Stackoverflow.com/users/6568', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think there is a global answer to your question. It depends on the specific query. You would have to compare the execution plans for the two queries to see if there are significant differences.</p>\n\n<p>I personally prefer the first form:</p>\n\n<p>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id </p>\n\n<p>because if I want to change the literal there is only one change needed.</p>\n"}, {'answer_id': 72774, 'author': 'aggergren', 'author_id': 7742, 'author_profile': 'https://Stackoverflow.com/users/7742', 'pm_score': 0, 'selected': False, 'text': "<p>The extressions should be equivalent with any decent optimizer, but it depends on which database you're using and what indexes are defined on your table. </p>\n\n<p>I would suggest using the EXPLAIN feature to figure out which of expressions is the most optimal.</p>\n"}, {'answer_id': 72804, 'author': 'Clinton Pierce', 'author_id': 8173, 'author_profile': 'https://Stackoverflow.com/users/8173', 'pm_score': 2, 'selected': False, 'text': '<p>There are a lot of factors at play here that you\'ve left out. What kind of database is it? Are those tables indexed? How are they indexed? How large are those tables?</p>\n\n<p>(Premature optimization is the root of all evil!)</p>\n\n<p>It could be that if "t1.id" and "t2.id" are indexed, the database engine joins them together based on those fields, and then uses the rest of the WHERE clause to filter out rows.</p>\n\n<p>They could be indexed but incredibly small tables, and both fit in a page of memory. In which case the database engine might just do a full scan of both rather than bother loading up the index.</p>\n\n<p>You just don\'t know, really, until you try.</p>\n'}, {'answer_id': 73172, 'author': 'Lost in Alabama', 'author_id': 5285, 'author_profile': 'https://Stackoverflow.com/users/5285', 'pm_score': 0, 'selected': False, 'text': "<p>I think a better SQL would be:</p>\n\n<p>select * from t1, t2 where t1.id=t2.id \nand t1.country ='US'</p>\n\n<p>There's no need to use the second comparison to 'US' unless it's possisble that the country in t2 could be different than t1 for the same id.</p>\n"}, {'answer_id': 73890, 'author': 'Jeremiah Peschka', 'author_id': 11780, 'author_profile': 'https://Stackoverflow.com/users/11780', 'pm_score': 0, 'selected': False, 'text': "<p>Rather than use an implicit inner join, I would explicitly join the tables. </p>\n\n<p>Since you want both the id fields and country fields to be the same, and you mentioned that both are indexed (I'm presuming in the same index), I would include both columns in the join so you can make use of an index seek instead of a scan. Finally, add your where clause.</p>\n\n<pre><code>SELECT *\n FROM t1\n JOIN t2 ON t1.id = t2.id AND t1.country = t2.country\n WHERE t1.country = 'US'\n</code>\n</pre>\n"}, {'answer_id': 74676, 'author': 'Arthur Miller', 'author_id': 13085, 'author_profile': 'https://Stackoverflow.com/users/13085', 'pm_score': 2, 'selected': True, 'text': "<p>I had a situation similar to this and this was the solution I resorted to:</p>\n\n<p>Select * \nFROM t1 \nINNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US'</p>\n\n<p>I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12386/'] |
72,723 | <p>I have a svn repository, R, that depends on a library, l, in another repository.</p>
<p>The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.</p>
<p>I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.</p>
<p>If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.</p>
| [{'answer_id': 72925, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 2, 'selected': False, 'text': '<p>I suggest using a script wrapper for svn co. </p>\n\n<pre><code>#!/bin/sh\nsvn co path://server/R svn-R\ngit clone path://server/l git-l\n</code></pre>\n\n<p>Or similar.</p>\n'}, {'answer_id': 72930, 'author': 'Avi', 'author_id': 1605, 'author_profile': 'https://Stackoverflow.com/users/1605', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html" rel="noreferrer">svn:externals</a> is the way svn can be made to check out sources from more than one repository into one working copy. But it is only meant for dealing with svn repositories - it doesn\'t know how to check out a git repository.</p>\n\n<p>You might be able to do it the other way \'round, by including an svn repository inside a git repository, using something like \'git svn\'.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,732 | <p>In textmate, when there's a current selection, I hit the " key and the selection gets surrounded by quotes. The same thing happens with other balanced characters like (, {, [ and '.</p>
<p>Am I missing something obvious in Emacs configuration that would enable similar behaviour when using transient mark mode, or do I need to break out elisp and write something?</p>
| [{'answer_id': 72802, 'author': 'Clinton Dreisbach', 'author_id': 6262, 'author_profile': 'https://Stackoverflow.com/users/6262', 'pm_score': 3, 'selected': False, 'text': '<p>wrap-region.el from <a href="http://sami.samhuri.net/2007/6/23/emacs-for-textmate-junkies" rel="nofollow noreferrer">this guy\'s blog post</a> will do what you\'re looking for.</p>\n\n<p><a href="http://mumble.net/~campbell/emacs/paredit.el" rel="nofollow noreferrer">Paredit</a> will complete the TextMate-style quoting. When you type one part of a matched pair (quotes, brackets, parentheses, etc), the second will be inserted and the insertion point is moved between them, much like TextMate.</p>\n'}, {'answer_id': 2534374, 'author': 'joao', 'author_id': 177259, 'author_profile': 'https://Stackoverflow.com/users/177259', 'pm_score': 3, 'selected': True, 'text': '<p>Try <a href="http://autopair.googlecode.com" rel="nofollow noreferrer">http://autopair.googlecode.com</a></p>\n'}, {'answer_id': 2551209, 'author': 'Singletoned', 'author_id': 46715, 'author_profile': 'https://Stackoverflow.com/users/46715', 'pm_score': 0, 'selected': False, 'text': '<p>You should check out these older, very similar, questions:</p>\n\n<p><a href="https://stackoverflow.com/questions/1023770/automatically-closing-braces-in-emacs/1024531#1024531">Automatically closing braces in Emacs?</a></p>\n\n<p><a href="https://stackoverflow.com/questions/848647/emacs-typeover-skeleton-pair-insert-maybe/849218#849218">Emacs typeover skeleton-pair-insert-maybe</a></p>\n\n<p>Although the correct answer is Joao\'s above; I\'m about to go and change my answer to those questions, to point to autopair.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423836/'] |
72,768 | <p>I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?</p>
| [{'answer_id': 72801, 'author': 'senfo', 'author_id': 10792, 'author_profile': 'https://Stackoverflow.com/users/10792', 'pm_score': 11, 'selected': True, 'text': '<p>The credit/debit card number is referred to as a <strong>PAN</strong>, or <em>Primary Account Number</em>. The first six digits of the PAN are taken from the <strong>IIN</strong>, or <em>Issuer Identification Number</em>, belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, <a href="http://en.wikipedia.org/wiki/ISO/IEC_7812" rel="noreferrer">ISO/IEC 7812</a>, and can be used to determine the type of card from the number.</p>\n<p>Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including <a href="http://en.wikipedia.org/wiki/Bank_card_number" rel="noreferrer">on Wikipedia</a>.</p>\n<p>Anyway, to detect the type from the number, you can use a regular expression like the ones below: <a href="http://www.regular-expressions.info/creditcard.html" rel="noreferrer">Credit for original expressions</a></p>\n<p><strong>Visa:</strong> <code>^4[0-9]{6,}$</code> Visa card numbers start with a 4.</p>\n<p><strong>MasterCard:</strong> <code>^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$</code> Before 2016, MasterCard numbers start with the numbers 51 through 55, <strong>but this will only detect MasterCard credit cards</strong>; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099).</p>\n<p><strong>American Express:</strong> <code>^3[47][0-9]{5,}$</code> American Express card numbers start with 34 or 37.</p>\n<p><strong>Diners Club:</strong> <code>^3(?:0[0-5]|[68][0-9])[0-9]{4,}$</code> Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard.</p>\n<p><strong>Discover:</strong> <code>^6(?:011|5[0-9]{2})[0-9]{3,}$</code> Discover card numbers begin with 6011 or 65.</p>\n<p><strong>JCB:</strong> <code>^(?:2131|1800|35[0-9]{3})[0-9]{3,}$</code> JCB cards begin with 2131, 1800 or 35.</p>\n<p>Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, <strong>it may be best to assume that any card that is not of some other type you accept must be a MasterCard</strong>.</p>\n<p><strong>Important</strong>: card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. <strong>Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits</strong> (for a complete IIN plus one check digit, which should match the value predicted by <a href="http://en.wikipedia.org/wiki/Luhn_algorithm" rel="noreferrer">the Luhn algorithm</a>).</p>\n<p>One further hint: <strong>before processing a cardholder PAN, strip any whitespace and punctuation characters from the input</strong>. Why? Because it’s typically <em>much</em> easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e.</p>\n<pre><code>4444 4444 4444 4444\n</code></pre>\n<p>is much easier to enter correctly than</p>\n<pre><code>4444444444444444\n</code></pre>\n<p>There’s really no benefit in chastising the user because they’ve entered characters you don\'t expect here.</p>\n<p><strong>This also implies making sure that your entry fields have room for <em>at least</em> 24 characters, otherwise users who enter spaces will run out of room.</strong> I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion.</p>\n<p>Here\'s an image that gives a little more insight:</p>\n<p><strong>UPDATE (2016):</strong> Mastercard is to implement new BIN ranges starting <a href="http://achpayment.net/" rel="noreferrer">Ach Payment</a>.</p>\n<p><img src="https://i.stack.imgur.com/Cu7PG.jpg" alt="Credit Card Verification" /></p>\n'}, {'answer_id': 73248, 'author': 'Shoban', 'author_id': 12178, 'author_profile': 'https://Stackoverflow.com/users/12178', 'pm_score': 3, 'selected': False, 'text': '<p>The first numbers of the credit card can be used to approximate the vendor:</p>\n\n<ul>\n<li>Visa: 49,44 or 47</li>\n<li>Visa electron: 42, 45, 48, 49</li>\n<li>MasterCard: 51</li>\n<li>Amex:34</li>\n<li>Diners: 30, 36, 38</li>\n<li>JCB: 35</li>\n</ul>\n'}, {'answer_id': 1780382, 'author': 'Simon_Weaver', 'author_id': 16940, 'author_profile': 'https://Stackoverflow.com/users/16940', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s <a href="http://www.codeproject.com/Articles/20271/Ultimate-NET-Credit-Card-Utility-Class" rel="noreferrer">Complete C# or VB code for all kinds of CC related things</a> on codeproject.</p>\n\n<ul>\n<li>IsValidNumber</li>\n<li>GetCardTypeFromNumber</li>\n<li>GetCardTestNumber</li>\n<li>PassesLuhnTest</li>\n</ul>\n\n<p>This article has been up for a couple years with no negative comments.</p>\n'}, {'answer_id': 2408585, 'author': 'Rashy', 'author_id': 289587, 'author_profile': 'https://Stackoverflow.com/users/289587', 'pm_score': 4, 'selected': False, 'text': '<p>Check this out:</p>\n\n<p><a href="http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B" rel="nofollow noreferrer">http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B</a></p>\n\n<pre class="lang-js prettyprint-override"><code>function isValidCreditCard(type, ccnum) {\n /* Visa: length 16, prefix 4, dashes optional.\n Mastercard: length 16, prefix 51-55, dashes optional.\n Discover: length 16, prefix 6011, dashes optional.\n American Express: length 15, prefix 34 or 37.\n Diners: length 14, prefix 30, 36, or 38. */\n\n var re = new Regex({\n "visa": "/^4\\d{3}-?\\d{4}-?\\d{4}-?\\d",\n "mc": "/^5[1-5]\\d{2}-?\\d{4}-?\\d{4}-?\\d{4}$/",\n "disc": "/^6011-?\\d{4}-?\\d{4}-?\\d{4}$/",\n "amex": "/^3[47]\\d{13}$/",\n "diners": "/^3[068]\\d{12}$/"\n }[type.toLowerCase()])\n\n if (!re.test(ccnum)) return false;\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split("-").join("");\n // Checksum ("Mod 10")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {\n checksum += parseInt(ccnum.charAt(i - 1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {\n var digit = parseInt(ccnum.charAt(i - 1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }\n }\n if ((checksum % 10) == 0) return true;\n else return false;\n}\n</code></pre>\n'}, {'answer_id': 11529211, 'author': 'Parvez', 'author_id': 1531583, 'author_profile': 'https://Stackoverflow.com/users/1531583', 'pm_score': 2, 'selected': False, 'text': '<pre><code>// abobjects.com, parvez ahmad ab bulk mailer\nuse below script\n\nfunction isValidCreditCard2(type, ccnum) {\n if (type == "Visa") {\n // Visa: length 16, prefix 4, dashes optional.\n var re = /^4\\d{3}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == "MasterCard") {\n // Mastercard: length 16, prefix 51-55, dashes optional.\n var re = /^5[1-5]\\d{2}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == "Discover") {\n // Discover: length 16, prefix 6011, dashes optional.\n var re = /^6011?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == "AmEx") {\n // American Express: length 15, prefix 34 or 37.\n var re = /^3[4,7]\\d{13}$/;\n } else if (type == "Diners") {\n // Diners: length 14, prefix 30, 36, or 38.\n var re = /^3[0,6,8]\\d{12}$/;\n }\n if (!re.test(ccnum)) return false;\n return true;\n /*\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split("-").join("");\n // Checksum ("Mod 10")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {\n checksum += parseInt(ccnum.charAt(i-1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {\n var digit = parseInt(ccnum.charAt(i-1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }\n }\n if ((checksum % 10) == 0) return true; else return false;\n */\n\n }\njQuery.validator.addMethod("isValidCreditCard", function(postalcode, element) { \n return isValidCreditCard2($("#cardType").val(), $("#cardNum").val()); \n\n}, "<br>credit card is invalid");\n\n\n Type</td>\n <td class="text">&nbsp; <form:select path="cardType" cssclass="fields" style="border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;">\n <option value="SELECT">SELECT</option>\n <option value="MasterCard">Mastercard</option>\n <option value="Visa">Visa</option>\n <option value="AmEx">American Express</option>\n <option value="Discover">Discover</option>\n </form:select> <font color="#FF0000">*</font> \n\n$("#signupForm").validate({\n\n rules:{\n companyName:{required: true},\n address1:{required: true},\n city:{required: true},\n state:{required: true},\n zip:{required: true},\n country:{required: true},\n chkAgree:{required: true},\n confPassword:{required: true},\n lastName:{required: true},\n firstName:{required: true},\n ccAddress1:{required: true},\n ccZip:{ \n postalcode : true\n },\n phone:{required: true},\n email:{\n required: true,\n email: true\n },\n userName:{\n required: true,\n minlength: 6\n },\n password:{\n required: true,\n minlength: 6\n }, \n cardNum:{ \n isValidCreditCard : true\n },\n</code></pre>\n'}, {'answer_id': 13842374, 'author': 'Usman Younas', 'author_id': 1728403, 'author_profile': 'https://Stackoverflow.com/users/1728403', 'pm_score': 5, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>public string GetCreditCardType(string CreditCardNumber)\n{\n Regex regVisa = new Regex("^4[0-9]{12}(?:[0-9]{3})?$");\n Regex regMaster = new Regex("^5[1-5][0-9]{14}$");\n Regex regExpress = new Regex("^3[47][0-9]{13}$");\n Regex regDiners = new Regex("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");\n Regex regDiscover = new Regex("^6(?:011|5[0-9]{2})[0-9]{12}$");\n Regex regJCB = new Regex("^(?:2131|1800|35\\\\d{3})\\\\d{11}$");\n\n\n if (regVisa.IsMatch(CreditCardNumber))\n return "VISA";\n else if (regMaster.IsMatch(CreditCardNumber))\n return "MASTER";\n else if (regExpress.IsMatch(CreditCardNumber))\n return "AEXPRESS";\n else if (regDiners.IsMatch(CreditCardNumber))\n return "DINERS";\n else if (regDiscover.IsMatch(CreditCardNumber))\n return "DISCOVERS";\n else if (regJCB.IsMatch(CreditCardNumber))\n return "JCB";\n else\n return "invalid";\n}\n</code></pre>\n\n<p>Here is the function to check Credit card type using Regex , c#</p>\n'}, {'answer_id': 15499262, 'author': 'Fivell', 'author_id': 246544, 'author_profile': 'https://Stackoverflow.com/users/246544', 'pm_score': 4, 'selected': False, 'text': '<p>recently I needed such functionality, I was porting Zend Framework Credit Card Validator to ruby.\nruby gem: <a href="https://github.com/Fivell/credit_card_validations" rel="nofollow noreferrer">https://github.com/Fivell/credit_card_validations</a> \nzend framework: <a href="https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php" rel="nofollow noreferrer">https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php</a></p>\n\n<p>They both use INN ranges for detecting type. Here you can read <a href="http://en.wikipedia.org/wiki/Bank_card_number" rel="nofollow noreferrer">about INN</a></p>\n\n<p>According to this you can detect credit card alternatively (without regexps,but declaring some rules about prefixes and possible length)</p>\n\n<p>So we have next rules for most used cards</p>\n\n<pre><code>######## most used brands #########\n\n visa: [\n {length: [13, 16], prefixes: [\'4\']}\n ],\n mastercard: [\n {length: [16], prefixes: [\'51\', \'52\', \'53\', \'54\', \'55\']}\n ],\n\n amex: [\n {length: [15], prefixes: [\'34\', \'37\']}\n ],\n ######## other brands ########\n diners: [\n {length: [14], prefixes: [\'300\', \'301\', \'302\', \'303\', \'304\', \'305\', \'36\', \'38\']},\n ],\n\n #There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard\n # will be removed in next major version\n\n diners_us: [\n {length: [16], prefixes: [\'54\', \'55\']}\n ],\n\n discover: [\n {length: [16], prefixes: [\'6011\', \'644\', \'645\', \'646\', \'647\', \'648\',\n \'649\', \'65\']}\n ],\n\n jcb: [\n {length: [16], prefixes: [\'3528\', \'3529\', \'353\', \'354\', \'355\', \'356\', \'357\', \'358\', \'1800\', \'2131\']}\n ],\n\n\n laser: [\n {length: [16, 17, 18, 19], prefixes: [\'6304\', \'6706\', \'6771\']}\n ],\n\n solo: [\n {length: [16, 18, 19], prefixes: [\'6334\', \'6767\']}\n ],\n\n switch: [\n {length: [16, 18, 19], prefixes: [\'633110\', \'633312\', \'633304\', \'633303\', \'633301\', \'633300\']}\n\n ],\n\n maestro: [\n {length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: [\'5010\', \'5011\', \'5012\', \'5013\', \'5014\', \'5015\', \'5016\', \'5017\', \'5018\',\n \'502\', \'503\', \'504\', \'505\', \'506\', \'507\', \'508\',\n \'6012\', \'6013\', \'6014\', \'6015\', \'6016\', \'6017\', \'6018\', \'6019\',\n \'602\', \'603\', \'604\', \'605\', \'6060\',\n \'677\', \'675\', \'674\', \'673\', \'672\', \'671\', \'670\',\n \'6760\', \'6761\', \'6762\', \'6763\', \'6764\', \'6765\', \'6766\', \'6768\', \'6769\']}\n ],\n\n # Luhn validation are skipped for union pay cards because they have unknown generation algoritm\n unionpay: [\n {length: [16, 17, 18, 19], prefixes: [\'622\', \'624\', \'625\', \'626\', \'628\'], skip_luhn: true}\n ],\n\n dankrot: [\n {length: [16], prefixes: [\'5019\']}\n ],\n\n rupay: [\n {length: [16], prefixes: [\'6061\', \'6062\', \'6063\', \'6064\', \'6065\', \'6066\', \'6067\', \'6068\', \'6069\', \'607\', \'608\'], skip_luhn: true}\n ]\n\n}\n</code></pre>\n\n<p>Then by searching prefix and comparing length you can detect credit card brand. Also don\'t forget about luhn algoritm (it is descibed here <a href="http://en.wikipedia.org/wiki/Luhn" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Luhn</a>).</p>\n\n<p>UPDATE </p>\n\n<p>updated list of rules can be found here <a href="https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml" rel="nofollow noreferrer">https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml</a></p>\n'}, {'answer_id': 18216511, 'author': 'ismail', 'author_id': 2679740, 'author_profile': 'https://Stackoverflow.com/users/2679740', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a php class function returns CCtype by CCnumber. \n<br>This code not validates the card or not runs Luhn algorithm only try to find credit card type based on table in <a href="http://en.wikipedia.org/wiki/Credit_card_number#Major_Industry_Identifier_.28MII.29" rel="nofollow noreferrer">this page</a>. basicly uses CCnumber length and CCcard prefix to determine CCcard type.</p>\n\n<pre class="lang-php prettyprint-override"><code><?php\nclass CreditcardType\n{\n public static $creditcardTypes = [\n [\n \'Name\' => \'American Express\',\n \'cardLength\' => [15],\n \'cardPrefix\' => [\'34\', \'37\'],\n ], [\n \'Name\' => \'Maestro\',\n \'cardLength\' => [12, 13, 14, 15, 16, 17, 18, 19],\n \'cardPrefix\' => [\'5018\', \'5020\', \'5038\', \'6304\', \'6759\', \'6761\', \'6763\'],\n ], [\n \'Name\' => \'Mastercard\',\n \'cardLength\' => [16],\n \'cardPrefix\' => [\'51\', \'52\', \'53\', \'54\', \'55\'],\n ], [\n \'Name\' => \'Visa\',\n \'cardLength\' => [13, 16],\n \'cardPrefix\' => [\'4\'],\n ], [\n \'Name\' => \'JCB\',\n \'cardLength\' => [16],\n \'cardPrefix\' => [\'3528\', \'3529\', \'353\', \'354\', \'355\', \'356\', \'357\', \'358\'],\n ], [\n \'Name\' => \'Discover\',\n \'cardLength\' => [16],\n \'cardPrefix\' => [\'6011\', \'622126\', \'622127\', \'622128\', \'622129\', \'62213\',\'62214\', \'62215\', \'62216\', \'62217\', \'62218\', \'62219\',\'6222\', \'6223\', \'6224\', \'6225\', \'6226\', \'6227\', \'6228\',\'62290\', \'62291\', \'622920\', \'622921\', \'622922\', \'622923\',\'622924\', \'622925\', \'644\', \'645\', \'646\', \'647\', \'648\',\'649\', \'65\'],\n ], [\n \'Name\' => \'Solo\',\n \'cardLength\' => [16, 18, 19],\n \'cardPrefix\' => [\'6334\', \'6767\'],\n ], [\n \'Name\' => \'Unionpay\',\n \'cardLength\' => [16, 17, 18, 19],\n \'cardPrefix\' => [\'622126\', \'622127\', \'622128\', \'622129\', \'62213\', \'62214\',\'62215\', \'62216\', \'62217\', \'62218\', \'62219\', \'6222\', \'6223\',\'6224\', \'6225\', \'6226\', \'6227\', \'6228\', \'62290\', \'62291\',\'622920\', \'622921\', \'622922\', \'622923\', \'622924\', \'622925\'],\n ], [\n \'Name\' => \'Diners Club\',\n \'cardLength\' => [14],\n \'cardPrefix\' => [\'300\', \'301\', \'302\', \'303\', \'304\', \'305\', \'36\'],\n ], [\n \'Name\' => \'Diners Club US\',\n \'cardLength\' => [16],\n \'cardPrefix\' => [\'54\', \'55\'],\n ], [\n \'Name\' => \'Diners Club Carte Blanche\',\n \'cardLength\' => [14],\n \'cardPrefix\' => [\'300\', \'305\'],\n ], [\n \'Name\' => \'Laser\',\n \'cardLength\' => [16, 17, 18, 19],\n \'cardPrefix\' => [\'6304\', \'6706\', \'6771\', \'6709\'],\n ],\n ];\n\n public static function getType($CCNumber)\n {\n $CCNumber = trim($CCNumber);\n $type = \'Unknown\';\n foreach (CreditcardType::$creditcardTypes as $card) {\n if (! in_array(strlen($CCNumber), $card[\'cardLength\'])) {\n continue;\n }\n $prefixes = \'/^(\' . implode(\'|\', $card[\'cardPrefix\']) . \')/\';\n if (preg_match($prefixes, $CCNumber) == 1) {\n $type = $card[\'Name\'];\n break;\n }\n }\n return $type;\n }\n}\n\n</code></pre>\n'}, {'answer_id': 19138852, 'author': 'Anatoliy', 'author_id': 161832, 'author_profile': 'https://Stackoverflow.com/users/161832', 'pm_score': 7, 'selected': False, 'text': '<p>In javascript:</p>\n\n<pre class="lang-js prettyprint-override"><code>function detectCardType(number) {\n var re = {\n electron: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n dankort: /^(5019)\\d+$/,\n interpayment: /^(636)\\d+$/,\n unionpay: /^(62|88)\\d+$/,\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n }\n\n for(var key in re) {\n if(re[key].test(number)) {\n return key\n }\n }\n}\n</code></pre>\n\n<p>Unit test:</p>\n\n<pre class="lang-js prettyprint-override"><code>describe(\'CreditCard\', function() {\n describe(\'#detectCardType\', function() {\n\n var cards = {\n \'8800000000000000\': \'UNIONPAY\',\n\n \'4026000000000000\': \'ELECTRON\',\n \'4175000000000000\': \'ELECTRON\',\n \'4405000000000000\': \'ELECTRON\',\n \'4508000000000000\': \'ELECTRON\',\n \'4844000000000000\': \'ELECTRON\',\n \'4913000000000000\': \'ELECTRON\',\n \'4917000000000000\': \'ELECTRON\',\n\n \'5019000000000000\': \'DANKORT\',\n\n \'5018000000000000\': \'MAESTRO\',\n \'5020000000000000\': \'MAESTRO\',\n \'5038000000000000\': \'MAESTRO\',\n \'5612000000000000\': \'MAESTRO\',\n \'5893000000000000\': \'MAESTRO\',\n \'6304000000000000\': \'MAESTRO\',\n \'6759000000000000\': \'MAESTRO\',\n \'6761000000000000\': \'MAESTRO\',\n \'6762000000000000\': \'MAESTRO\',\n \'6763000000000000\': \'MAESTRO\',\n \'0604000000000000\': \'MAESTRO\',\n \'6390000000000000\': \'MAESTRO\',\n\n \'3528000000000000\': \'JCB\',\n \'3589000000000000\': \'JCB\',\n \'3529000000000000\': \'JCB\',\n\n \'6360000000000000\': \'INTERPAYMENT\',\n\n \'4916338506082832\': \'VISA\',\n \'4556015886206505\': \'VISA\',\n \'4539048040151731\': \'VISA\',\n \'4024007198964305\': \'VISA\',\n \'4716175187624512\': \'VISA\',\n\n \'5280934283171080\': \'MASTERCARD\',\n \'5456060454627409\': \'MASTERCARD\',\n \'5331113404316994\': \'MASTERCARD\',\n \'5259474113320034\': \'MASTERCARD\',\n \'5442179619690834\': \'MASTERCARD\',\n\n \'6011894492395579\': \'DISCOVER\',\n \'6011388644154687\': \'DISCOVER\',\n \'6011880085013612\': \'DISCOVER\',\n \'6011652795433988\': \'DISCOVER\',\n \'6011375973328347\': \'DISCOVER\',\n\n \'345936346788903\': \'AMEX\',\n \'377669501013152\': \'AMEX\',\n \'373083634595479\': \'AMEX\',\n \'370710819865268\': \'AMEX\',\n \'371095063560404\': \'AMEX\'\n };\n\n Object.keys(cards).forEach(function(number) {\n it(\'should detect card \' + number + \' as \' + cards[number], function() {\n Basket.detectCardType(number).should.equal(cards[number]);\n });\n });\n });\n});\n</code></pre>\n'}, {'answer_id': 21487404, 'author': 'Pinch', 'author_id': 1513082, 'author_profile': 'https://Stackoverflow.com/users/1513082', 'pm_score': 2, 'selected': False, 'text': '<p>Just a little spoon feeding:</p>\n\n<pre><code>$("#CreditCardNumber").focusout(function () {\n\n\n var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;\n var regMasterCard = /^5[1-5][0-9]{14}$/;\n var regAmex = /^3[47][0-9]{13}$/;\n var regDiscover = /^6(?:011|5[0-9]{2})[0-9]{12}$/;\n\n if (regVisa.test($(this).val())) {\n $("#CCImage").html("<img height=\'40px\' src=\'@Url.Content("~/images/visa.png")\'>"); \n\n }\n\n else if (regMasterCard.test($(this).val())) {\n $("#CCImage").html("<img height=\'40px\' src=\'@Url.Content("~/images/mastercard.png")\'>");\n\n }\n\n else if (regAmex.test($(this).val())) {\n\n $("#CCImage").html("<img height=\'40px\' src=\'@Url.Content("~/images/amex.png")\'>");\n\n }\n else if (regDiscover.test($(this).val())) {\n\n $("#CCImage").html("<img height=\'40px\' src=\'@Url.Content("~/images/discover.png")\'>");\n\n }\n else {\n $("#CCImage").html("NA");\n\n }\n\n });\n</code></pre>\n'}, {'answer_id': 21617574, 'author': 'Janos Szabo', 'author_id': 1176373, 'author_profile': 'https://Stackoverflow.com/users/1176373', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Updated: 15th June 2016</strong> (as an ultimate solution currently)</p>\n\n<p>Please note that I even give vote up for the one is top voted, but to make it clear these are the regexps actually works i tested it with thousands of real BIN codes. <strong>The most important is to use start strings (^) otherwise it will give false results in real world!</strong></p>\n\n<p><strong>JCB</strong> <code>^(?:2131|1800|35)[0-9]{0,}$</code> Start with: <strong>2131, 1800, 35 (3528-3589)</strong></p>\n\n<p><strong>American Express</strong> <code>^3[47][0-9]{0,}$</code> Start with: <strong>34, 37</strong></p>\n\n<p><strong>Diners Club</strong> <code>^3(?:0[0-59]{1}|[689])[0-9]{0,}$</code> Start with: <strong>300-305, 309, 36, 38-39</strong></p>\n\n<p><strong>Visa</strong> <code>^4[0-9]{0,}$</code> Start with: <strong>4</strong></p>\n\n<p><strong>MasterCard</strong> <code>^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$</code> Start with: <strong>2221-2720, 51-55</strong></p>\n\n<p><strong>Maestro</strong> <code>^(5[06789]|6)[0-9]{0,}$</code> Maestro always growing in the range: <strong>60-69</strong>, started with / not something else, but starting 5 must be encoded as mastercard anyway. Maestro cards must be detected in the end of the code because some others has in the range of 60-69. Please look at the code.</p>\n\n<p><strong>Discover</strong> <code>^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$</code> Discover quite difficult to code, start with: <strong>6011, 622126-622925, 644-649, 65</strong></p>\n\n<p>In <strong>javascript</strong> I use this function. This is good when u assign it to an onkeyup event and it give result as soon as possible.</p>\n\n<pre class="lang-js prettyprint-override"><code>function cc_brand_id(cur_val) {\n // the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars\n // regexp string length {0} provided for soonest detection of beginning of the card numbers this way it could be used for BIN CODE detection also\n\n //JCB\n jcb_regex = new RegExp(\'^(?:2131|1800|35)[0-9]{0,}$\'); //2131, 1800, 35 (3528-3589)\n // American Express\n amex_regex = new RegExp(\'^3[47][0-9]{0,}$\'); //34, 37\n // Diners Club\n diners_regex = new RegExp(\'^3(?:0[0-59]{1}|[689])[0-9]{0,}$\'); //300-305, 309, 36, 38-39\n // Visa\n visa_regex = new RegExp(\'^4[0-9]{0,}$\'); //4\n // MasterCard\n mastercard_regex = new RegExp(\'^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$\'); //2221-2720, 51-55\n maestro_regex = new RegExp(\'^(5[06789]|6)[0-9]{0,}$\'); //always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway\n //Discover\n discover_regex = new RegExp(\'^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$\');\n ////6011, 622126-622925, 644-649, 65\n\n\n // get rid of anything but numbers\n cur_val = cur_val.replace(/\\D/g, \'\');\n\n // checks per each, as their could be multiple hits\n //fix: ordering matter in detection, otherwise can give false results in rare cases\n var sel_brand = "unknown";\n if (cur_val.match(jcb_regex)) {\n sel_brand = "jcb";\n } else if (cur_val.match(amex_regex)) {\n sel_brand = "amex";\n } else if (cur_val.match(diners_regex)) {\n sel_brand = "diners_club";\n } else if (cur_val.match(visa_regex)) {\n sel_brand = "visa";\n } else if (cur_val.match(mastercard_regex)) {\n sel_brand = "mastercard";\n } else if (cur_val.match(discover_regex)) {\n sel_brand = "discover";\n } else if (cur_val.match(maestro_regex)) {\n if (cur_val[0] == \'5\') { //started 5 must be mastercard\n sel_brand = "mastercard";\n } else {\n sel_brand = "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n }\n }\n\n return sel_brand;\n}\n</code></pre>\n\n<p>Here you can play with it:</p>\n\n<p><a href="http://jsfiddle.net/upN3L/69/" rel="noreferrer">http://jsfiddle.net/upN3L/69/</a></p>\n\n<p><strong>For PHP use this function, this detects some sub VISA/MC cards too:</strong></p>\n\n<pre class="lang-php prettyprint-override"><code>/**\n * Obtain a brand constant from a PAN\n *\n * @param string $pan Credit card number\n * @param bool $include_sub_types Include detection of sub visa brands\n * @return string\n */\npublic static function getCardBrand($pan, $include_sub_types = false)\n{\n //maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm\n\n //these regexps accept not whole cc numbers too\n //visa\n $visa_regex = "/^4[0-9]{0,}$/";\n $vpreca_regex = "/^428485[0-9]{0,}$/";\n $postepay_regex = "/^(402360|402361|403035|417631|529948){0,}$/";\n $cartasi_regex = "/^(432917|432930|453998)[0-9]{0,}$/";\n $entropay_regex = "/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/";\n $o2money_regex = "/^(422793|475743)[0-9]{0,}$/";\n\n // MasterCard\n $mastercard_regex = "/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/";\n $maestro_regex = "/^(5[06789]|6)[0-9]{0,}$/";\n $kukuruza_regex = "/^525477[0-9]{0,}$/";\n $yunacard_regex = "/^541275[0-9]{0,}$/";\n\n // American Express\n $amex_regex = "/^3[47][0-9]{0,}$/";\n\n // Diners Club\n $diners_regex = "/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/";\n\n //Discover\n $discover_regex = "/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/";\n\n //JCB\n $jcb_regex = "/^(?:2131|1800|35)[0-9]{0,}$/";\n\n //ordering matter in detection, otherwise can give false results in rare cases\n if (preg_match($jcb_regex, $pan)) {\n return "jcb";\n }\n\n if (preg_match($amex_regex, $pan)) {\n return "amex";\n }\n\n if (preg_match($diners_regex, $pan)) {\n return "diners_club";\n }\n\n //sub visa/mastercard cards\n if ($include_sub_types) {\n if (preg_match($vpreca_regex, $pan)) {\n return "v-preca";\n }\n if (preg_match($postepay_regex, $pan)) {\n return "postepay";\n }\n if (preg_match($cartasi_regex, $pan)) {\n return "cartasi";\n }\n if (preg_match($entropay_regex, $pan)) {\n return "entropay";\n }\n if (preg_match($o2money_regex, $pan)) {\n return "o2money";\n }\n if (preg_match($kukuruza_regex, $pan)) {\n return "kukuruza";\n }\n if (preg_match($yunacard_regex, $pan)) {\n return "yunacard";\n }\n }\n\n if (preg_match($visa_regex, $pan)) {\n return "visa";\n }\n\n if (preg_match($mastercard_regex, $pan)) {\n return "mastercard";\n }\n\n if (preg_match($discover_regex, $pan)) {\n return "discover";\n }\n\n if (preg_match($maestro_regex, $pan)) {\n if ($pan[0] == \'5\') { //started 5 must be mastercard\n return "mastercard";\n }\n return "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n\n }\n\n return "unknown"; //unknown for this system\n}\n</code></pre>\n'}, {'answer_id': 21998527, 'author': 'rajan', 'author_id': 3348405, 'author_profile': 'https://Stackoverflow.com/users/3348405', 'pm_score': 0, 'selected': False, 'text': '<p>The regular expression rules that match the <a href="http://www.techrecite.com/credit-card-validation-regex-script-in-php-using-luhn-algorithm/" rel="nofollow">respective card vendors</a>:</p>\n\n<ul>\n<li><code>(4\\d{12}(?:\\d{3})?)</code> for VISA.</li>\n<li><code>(5[1-5]\\d{14})</code> for MasterCard.</li>\n<li><code>(3[47]\\d{13})</code> for AMEX.</li>\n<li><code>((?:5020|5038|6304|6579|6761)\\d{12}(?:\\d\\d)?)</code> for Maestro.</li>\n<li><code>(3(?:0[0-5]|[68][0-9])[0-9]{11})</code> for Diners Club.</li>\n<li><code>(6(?:011|5[0-9]{2})[0-9]{12})</code> for Discover.</li>\n<li><code>(35[2-8][89]\\d\\d\\d{10})</code> for JCB.</li>\n</ul>\n'}, {'answer_id': 22034170, 'author': 'Gajus', 'author_id': 368691, 'author_profile': 'https://Stackoverflow.com/users/368691', 'pm_score': 3, 'selected': False, 'text': '<p>Do not try to detect credit card type as part of processing a payment. You are risking of declining valid transactions.</p>\n\n<p>If you need to provide information to your payment processor (e.g. PayPal credit card object requires to name the <a href="https://developer.paypal.com/docs/api/#store-a-credit-card" rel="nofollow">card type</a>), then guess it from the least information available, e.g.</p>\n\n<pre class="lang-php prettyprint-override"><code>$credit_card[\'pan\'] = preg_replace(\'/[^0-9]/\', \'\', $credit_card[\'pan\']);\n$inn = (int) mb_substr($credit_card[\'pan\'], 0, 2);\n\n// @see http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers#Overview\nif ($inn >= 40 && $inn <= 49) {\n $type = \'visa\';\n} else if ($inn >= 51 && $inn <= 55) {\n $type = \'mastercard\';\n} else if ($inn >= 60 && $inn <= 65) {\n $type = \'discover\';\n} else if ($inn >= 34 && $inn <= 37) {\n $type = \'amex\';\n} else {\n throw new \\UnexpectedValueException(\'Unsupported card type.\');\n}\n</code></pre>\n\n<p>This implementation (using only the first two digits) is enough to identify all of the major (and in PayPal\'s case all of the supported) card schemes. In fact, you might want to skip the exception altogether and default to the most popular card type. Let the payment gateway/processor tell you if there is a validation error in response to your request.</p>\n\n<p>The reality is that your payment gateway <a href="http://qr.ae/tOcrH" rel="nofollow">does not care about the value you provide</a>.</p>\n'}, {'answer_id': 22631832, 'author': 'Nick', 'author_id': 956278, 'author_profile': 'https://Stackoverflow.com/users/956278', 'pm_score': 3, 'selected': False, 'text': '<p>Compact javascript version</p>\n\n<pre><code> var getCardType = function (number) {\n var cards = {\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n };\n for (var card in cards) {\n if (cards[card].test(number)) {\n return card;\n }\n }\n };\n</code></pre>\n'}, {'answer_id': 24615110, 'author': 'ZurabWeb', 'author_id': 1016530, 'author_profile': 'https://Stackoverflow.com/users/1016530', 'pm_score': 2, 'selected': False, 'text': '<p>My solution with jQuery:</p>\n\n<pre><code>function detectCreditCardType() {\n var type = new Array;\n type[1] = \'^4[0-9]{12}(?:[0-9]{3})?$\'; // visa\n type[2] = \'^5[1-5][0-9]{14}$\'; // mastercard\n type[3] = \'^6(?:011|5[0-9]{2})[0-9]{12}$\'; // discover\n type[4] = \'^3[47][0-9]{13}$\'; // amex\n\n var ccnum = $(\'.creditcard\').val().replace(/[^\\d.]/g, \'\');\n var returntype = 0;\n\n $.each(type, function(idx, re) {\n var regex = new RegExp(re);\n if(regex.test(ccnum) && idx>0) {\n returntype = idx;\n }\n });\n\n return returntype;\n}\n</code></pre>\n\n<p>In case 0 is returned, credit card type is undetected.</p>\n\n<p>"creditcard" class should be added to the credit card input field.</p>\n'}, {'answer_id': 27600969, 'author': 'MikeRoger', 'author_id': 459655, 'author_profile': 'https://Stackoverflow.com/users/459655', 'pm_score': 3, 'selected': False, 'text': '<p>In Card Range Recognition (CRR), a drawback with algorithms that use a series of regex or other hard-coded ranges, is that the BINs/IINs do change over time in my experience. The co-branding of cards is an ongoing complication. Different Card Acquirers / merchants may need you treat the same card differently, depending on e.g. geolocation. </p>\n\n<p>Additionally, in the last few years with e.g. UnionPay cards in wider circulation, existing models do not cope with new ranges that sometimes interleave with broader ranges that they supersede.<br>\nKnowing the geography your system needs to cover may help, as some ranges are restricted to use in particular countries. For example, ranges 62 include some AAA sub-ranges in the US, but if your merchant base is outside the US, you may be able to treat all 62 as UnionPay.<br>\nYou may be also asked to treat a card differently based on merchant location. E.g. to treat certain UK cards as debit domestically, but as credit internationally. </p>\n\n<p>There are very useful set of rules maintained by one major Acquiring Bank. E.g. <a href="https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf" rel="nofollow noreferrer">https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf</a> and <a href="https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf" rel="nofollow noreferrer">https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf</a>. (Valid links as of June 2017, thanks to the user who provided a link to updated reference.) But be aware of the caveat that, while these CRR rules may represent the Card Issuing universe as it applies to the merchants acquired by that entity, it does not include e.g. ranges identified as CUP/UPI.</p>\n\n<p>These comments apply to magnetic stripe (MagStripe) or PKE (Pan Key Entry) scenarios. The situation is different again in the ICC/EMV world.</p>\n\n<p>Update: Other answers on this page (and also the linked WikiPedia page) have JCB as always 16 long. However, in my company we have a dedicated team of engineers who certify our POS devices and software across multiple acquiring banks and geographies. The most recent Certification Pack of cards this team have from JCB, had a pass case for a 19 long PAN.</p>\n'}, {'answer_id': 29937208, 'author': 'Nagama Inamdar', 'author_id': 2240243, 'author_profile': 'https://Stackoverflow.com/users/2240243', 'pm_score': 2, 'selected': False, 'text': '<p>Stripe has provided this fantastic <strong>javascript</strong> library for card scheme detection. Let me add few code snippets and show you how to use it. </p>\n\n<p>Firstly Include it to your web page as</p>\n\n<pre><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js " ></script>\n</code></pre>\n\n<p>Secondly use the function cardType for detecting the card scheme.</p>\n\n<pre><code>$(document).ready(function() { \n var type = $.payment.cardType("4242 4242 4242 4242"); //test card number\n console.log(type); \n}); \n</code></pre>\n\n<p>Here are the reference links for more examples and demos.</p>\n\n<ol>\n<li><a href="https://stripe.com/blog/jquery-payment" rel="noreferrer">Stripe blog for jquery.payment.js</a></li>\n<li><a href="https://github.com/stripe/jquery.payment" rel="noreferrer">Github repository</a></li>\n</ol>\n'}, {'answer_id': 30957202, 'author': 'angelcool.net', 'author_id': 2425880, 'author_profile': 'https://Stackoverflow.com/users/2425880', 'pm_score': 3, 'selected': False, 'text': '<p>Anatoliy\'s answer in PHP:</p>\n\n<pre><code> public static function detectCardType($num)\n {\n $re = array(\n "visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",\n "mastercard" => "/^5[1-5][0-9]{14}$/",\n "amex" => "/^3[47][0-9]{13}$/",\n "discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",\n );\n\n if (preg_match($re[\'visa\'],$num))\n {\n return \'visa\';\n }\n else if (preg_match($re[\'mastercard\'],$num))\n {\n return \'mastercard\';\n }\n else if (preg_match($re[\'amex\'],$num))\n {\n return \'amex\';\n }\n else if (preg_match($re[\'discover\'],$num))\n {\n return \'discover\';\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n'}, {'answer_id': 31734477, 'author': 'ShadeTreeDeveloper', 'author_id': 633527, 'author_profile': 'https://Stackoverflow.com/users/633527', 'pm_score': 2, 'selected': False, 'text': '<p>I searched around quite a bit for credit card formatting and phone number formatting. Found lots of good tips but nothing really suited my exact desires so I created <a href="http://quercusv.github.io/smartForm/" rel="nofollow">this bit of code</a>. You use it like this:</p>\n\n<pre><code>var sf = smartForm.formatCC(myInputString);\nvar cardType = sf.cardType;\n</code></pre>\n'}, {'answer_id': 36483754, 'author': 'Daisy R.', 'author_id': 1855263, 'author_profile': 'https://Stackoverflow.com/users/1855263', 'pm_score': 3, 'selected': False, 'text': '<p>Swift 2.1 Version of Usman Y\'s answer.\nUse a print statement to verify so call by some string value</p>\n\n<pre><code>print(self.validateCardType(self.creditCardField.text!))\n\nfunc validateCardType(testCard: String) -> String {\n\n let regVisa = "^4[0-9]{12}(?:[0-9]{3})?$"\n let regMaster = "^5[1-5][0-9]{14}$"\n let regExpress = "^3[47][0-9]{13}$"\n let regDiners = "^3(?:0[0-5]|[68][0-9])[0-9]{11}$"\n let regDiscover = "^6(?:011|5[0-9]{2})[0-9]{12}$"\n let regJCB = "^(?:2131|1800|35\\\\d{3})\\\\d{11}$"\n\n\n let regVisaTest = NSPredicate(format: "SELF MATCHES %@", regVisa)\n let regMasterTest = NSPredicate(format: "SELF MATCHES %@", regMaster)\n let regExpressTest = NSPredicate(format: "SELF MATCHES %@", regExpress)\n let regDinersTest = NSPredicate(format: "SELF MATCHES %@", regDiners)\n let regDiscoverTest = NSPredicate(format: "SELF MATCHES %@", regDiscover)\n let regJCBTest = NSPredicate(format: "SELF MATCHES %@", regJCB)\n\n\n if regVisaTest.evaluateWithObject(testCard){\n return "Visa"\n }\n else if regMasterTest.evaluateWithObject(testCard){\n return "MasterCard"\n }\n\n else if regExpressTest.evaluateWithObject(testCard){\n return "American Express"\n }\n\n else if regDinersTest.evaluateWithObject(testCard){\n return "Diners Club"\n }\n\n else if regDiscoverTest.evaluateWithObject(testCard){\n return "Discover"\n }\n\n else if regJCBTest.evaluateWithObject(testCard){\n return "JCB"\n }\n\n return ""\n\n}\n</code></pre>\n'}, {'answer_id': 36882835, 'author': 'radtek', 'author_id': 2023392, 'author_profile': 'https://Stackoverflow.com/users/2023392', 'pm_score': 2, 'selected': False, 'text': '<p>Here is an example of some boolean functions written in Python that return <code>True</code> if the card is detected as per the function name. </p>\n\n<pre><code>def is_american_express(cc_number):\n """Checks if the card is an american express. If us billing address country code, & is_amex, use vpos\n https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^3[47][0-9]{13}$\', cc_number))\n\n\ndef is_visa(cc_number):\n """Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.\n :param cc_number: unicode card number\n """\n\n # Standard Visa is 13 or 16, debit can be 19\n if bool(re.match(r\'^4\', cc_number)) and len(cc_number) in [13, 16, 19]:\n return True\n\n return False\n\n\ndef is_mastercard(cc_number):\n """Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.\n :param cc_number: unicode card number\n """\n if len(cc_number) == 16 and cc_number.isdigit(): # Check digit, before cast to int\n return bool(re.match(r\'^5[1-5]\', cc_number)) or int(cc_number[:4]) in range(2221, 2721)\n return False\n\n\ndef is_discover(cc_number):\n """Checks if the card is discover, re would be too hard to maintain. Not a supported card.\n :param cc_number: unicode card number\n """\n if len(cc_number) == 16:\n try:\n # return bool(cc_number[:4] == \'6011\' or cc_number[:2] == \'65\' or cc_number[:6] in range(622126, 622926))\n return bool(cc_number[:4] == \'6011\' or cc_number[:2] == \'65\' or 622126 <= int(cc_number[:6]) <= 622925)\n except ValueError:\n return False\n return False\n\n\ndef is_jcb(cc_number):\n """Checks if the card is a jcb. Not a supported card.\n :param cc_number: unicode card number\n """\n # return bool(re.match(r\'^(?:2131|1800|35\\d{3})\\d{11}$\', cc_number)) # wikipedia\n return bool(re.match(r\'^35(2[89]|[3-8][0-9])[0-9]{12}$\', cc_number)) # PawelDecowski\n\n\ndef is_diners_club(cc_number):\n """Checks if the card is a diners club. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^3(?:0[0-6]|[68][0-9])[0-9]{11}$\', cc_number)) # 0-5 = carte blance, 6 = international\n\n\ndef is_laser(cc_number):\n """Checks if the card is laser. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^(6304|670[69]|6771)\', cc_number))\n\n\ndef is_maestro(cc_number):\n """Checks if the card is maestro. Not a supported card.\n :param cc_number: unicode card number\n """\n possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]\n return bool(re.match(r\'^(50|5[6-9]|6[0-9])\', cc_number)) and len(cc_number) in possible_lengths\n\n\n# Child cards\n\ndef is_visa_electron(cc_number):\n """Child of visa. Checks if the card is a visa electron. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^(4026|417500|4508|4844|491(3|7))\', cc_number)) and len(cc_number) == 16\n\n\ndef is_total_rewards_visa(cc_number):\n """Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^41277777[0-9]{8}$\', cc_number))\n\n\ndef is_diners_club_carte_blanche(cc_number):\n """Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^30[0-5][0-9]{11}$\', cc_number)) # github PawelDecowski, jquery-creditcardvalidator\n\n\ndef is_diners_club_carte_international(cc_number):\n """Child card of diners. Checks if the card is a diners club international. Not a supported card.\n :param cc_number: unicode card number\n """\n return bool(re.match(r\'^36[0-9]{12}$\', cc_number)) # jquery-creditcardvalidator\n</code></pre>\n'}, {'answer_id': 37559946, 'author': 'Vidyalaxmi', 'author_id': 2930683, 'author_profile': 'https://Stackoverflow.com/users/2930683', 'pm_score': 2, 'selected': False, 'text': '<p>In swift you can create an enum to detect the credit card type.</p>\n\n<pre><code>enum CreditCardType: Int { // Enum which encapsulates different card types and method to find the type of card.\n\ncase Visa\ncase Master\ncase Amex\ncase Discover\n\nfunc validationRegex() -> String {\n var regex = ""\n switch self {\n case .Visa:\n regex = "^4[0-9]{6,}$"\n\n case .Master:\n regex = "^5[1-5][0-9]{5,}$"\n\n case .Amex:\n regex = "^3[47][0-9]{13}$"\n\n case .Discover:\n regex = "^6(?:011|5[0-9]{2})[0-9]{12}$"\n }\n\n return regex\n}\n\nfunc validate(cardNumber: String) -> Bool {\n let predicate = NSPredicate(format: "SELF MATCHES %@", validationRegex())\n return predicate.evaluateWithObject(cardNumber)\n}\n\n// Method returns the credit card type for given card number\nstatic func cardTypeForCreditCardNumber(cardNumber: String) -> CreditCardType? {\n var creditCardType: CreditCardType?\n\n var index = 0\n while let cardType = CreditCardType(rawValue: index) {\n if cardType.validate(cardNumber) {\n creditCardType = cardType\n break\n } else {\n index++\n }\n }\n return creditCardType\n }\n}\n</code></pre>\n\n<p>Call the method CreditCardType.cardTypeForCreditCardNumber("#card number") which returns CreditCardType enum value.</p>\n'}, {'answer_id': 42667959, 'author': 'Anoop M Maddasseri', 'author_id': 4694013, 'author_profile': 'https://Stackoverflow.com/users/4694013', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n <p>The first six digits of a card number (including the initial MII\n digit) are known as the <a href="https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_.28IIN.29" rel="nofollow noreferrer">issuer identification number</a> (IIN). These\n identify the card issuing institution that issued the card to the card\n holder. The rest of the number is allocated by the card issuer. The\n card number\'s length is its number of digits. Many card issuers print\n the entire IIN and account number on their card.</p>\n</blockquote>\n\n<p>Based on the above facts I would like to keep a snippet of <strong>JAVA</strong> code to identify card brand.</p>\n\n<blockquote>\n <p>Sample card types</p>\n</blockquote>\n\n<pre><code>public static final String AMERICAN_EXPRESS = "American Express";\npublic static final String DISCOVER = "Discover";\npublic static final String JCB = "JCB";\npublic static final String DINERS_CLUB = "Diners Club";\npublic static final String VISA = "Visa";\npublic static final String MASTERCARD = "MasterCard";\npublic static final String UNKNOWN = "Unknown";\n</code></pre>\n\n<blockquote>\n <p>Card Prefixes</p>\n</blockquote>\n\n<pre><code>// Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29\npublic static final String[] PREFIXES_AMERICAN_EXPRESS = {"34", "37"};\npublic static final String[] PREFIXES_DISCOVER = {"60", "62", "64", "65"};\npublic static final String[] PREFIXES_JCB = {"35"};\npublic static final String[] PREFIXES_DINERS_CLUB = {"300", "301", "302", "303", "304", "305", "309", "36", "38", "39"};\npublic static final String[] PREFIXES_VISA = {"4"};\npublic static final String[] PREFIXES_MASTERCARD = {\n "2221", "2222", "2223", "2224", "2225", "2226", "2227", "2228", "2229",\n "223", "224", "225", "226", "227", "228", "229",\n "23", "24", "25", "26",\n "270", "271", "2720",\n "50", "51", "52", "53", "54", "55"\n };\n</code></pre>\n\n<blockquote>\n <p>Check to see if the input number has any of the given prefixes.</p>\n</blockquote>\n\n<pre><code>public String getBrand(String number) {\n\nString evaluatedType;\nif (StripeTextUtils.hasAnyPrefix(number, PREFIXES_AMERICAN_EXPRESS)) {\n evaluatedType = AMERICAN_EXPRESS;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DISCOVER)) {\n evaluatedType = DISCOVER;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_JCB)) {\n evaluatedType = JCB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DINERS_CLUB)) {\n evaluatedType = DINERS_CLUB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_VISA)) {\n evaluatedType = VISA;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_MASTERCARD)) {\n evaluatedType = MASTERCARD;\n} else {\n evaluatedType = UNKNOWN;\n}\n return evaluatedType;\n}\n</code></pre>\n\n<blockquote>\n <p>Finally, The Utility method</p>\n</blockquote>\n\n<pre><code>/**\n * Check to see if the input number has any of the given prefixes.\n *\n * @param number the number to test\n * @param prefixes the prefixes to test against\n * @return {@code true} if number begins with any of the input prefixes\n*/\n\npublic static boolean hasAnyPrefix(String number, String... prefixes) {\n if (number == null) {\n return false;\n }\n for (String prefix : prefixes) {\n if (number.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><a href="https://github.com/stripe/stripe-android/blob/master/stripe/src/main/java/com/stripe/android/model/Card.java" rel="nofollow noreferrer">Stripe Card Builder</a></li>\n</ul>\n'}, {'answer_id': 49531091, 'author': 'gaurav gupta', 'author_id': 5695805, 'author_profile': 'https://Stackoverflow.com/users/5695805', 'pm_score': 0, 'selected': False, 'text': '<pre><code>follow Luhn’s algorithm\n\n private boolean validateCreditCardNumber(String str) {\n\n int[] ints = new int[str.length()];\n for (int i = 0; i < str.length(); i++) {\n ints[i] = Integer.parseInt(str.substring(i, i + 1));\n }\n for (int i = ints.length - 2; i >= 0; i = i - 2) {\n int j = ints[i];\n j = j * 2;\n if (j > 9) {\n j = j % 10 + 1;\n }\n ints[i] = j;\n }\n int sum = 0;\n for (int i = 0; i < ints.length; i++) {\n sum += ints[i];\n }\n if (sum % 10 == 0) {\n return true;\n } else {\n return false;\n }\n\n\n }\n\nthen call this method\n\nEdittext mCreditCardNumberEt;\n\n mCreditCardNumberEt.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n\n int cardcount= s.toString().length();\n if(cardcount>=16) {\n boolean cardnumbervalid= validateCreditCardNumber(s.toString());\n if(cardnumbervalid) {\n cardvalidtesting.setText("Valid Card");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.green));\n }\n else {\n cardvalidtesting.setText("Invalid Card");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n }\n else if(cardcount>0 &&cardcount<16) {\n cardvalidtesting.setText("Invalid Card");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n\n else {\n cardvalidtesting.setText("");\n\n }\n\n\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n</code></pre>\n'}, {'answer_id': 58241706, 'author': 'OhhhThatVarun', 'author_id': 7436566, 'author_profile': 'https://Stackoverflow.com/users/7436566', 'pm_score': 1, 'selected': False, 'text': '<p>Try this for kotlin. Add Regex and add to the when statement.</p>\n\n<pre><code>private fun getCardType(number: String): String {\n\n val visa = Regex("^4[0-9]{12}(?:[0-9]{3})?$")\n val mastercard = Regex("^5[1-5][0-9]{14}$")\n val amx = Regex("^3[47][0-9]{13}$")\n\n return when {\n visa.matches(number) -> "Visa"\n mastercard.matches(number) -> "Mastercard"\n amx.matches(number) -> "American Express"\n else -> "Unknown"\n }\n }\n</code></pre>\n'}, {'answer_id': 62955455, 'author': 'Emanuel', 'author_id': 6638583, 'author_profile': 'https://Stackoverflow.com/users/6638583', 'pm_score': 2, 'selected': False, 'text': '<p>A javascript improve of @Anatoliy answer</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function getCardType (number) {\n const numberFormated = number.replace(/\\D/g, \'\')\n var patterns = {\n VISA: /^4[0-9]{12}(?:[0-9]{3})?$/,\n MASTER: /^5[1-5][0-9]{14}$/,\n AMEX: /^3[47][0-9]{13}$/,\n ELO: /^((((636368)|(438935)|(504175)|(451416)|(636297))\\d{0,10})|((5067)|(4576)|(4011))\\d{0,12})$/,\n AURA: /^(5078\\d{2})(\\d{2})(\\d{11})$/,\n JCB: /^(?:2131|1800|35\\d{3})\\d{11}$/,\n DINERS: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n DISCOVERY: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n HIPERCARD: /^(606282\\d{10}(\\d{3})?)|(3841\\d{15})$/,\n ELECTRON: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n MAESTRO: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n DANKORT: /^(5019)\\d+$/,\n INTERPAYMENT: /^(636)\\d+$/,\n UNIONPAY: /^(62|88)\\d+$/,\n }\n for (var key in patterns) {\n if (patterns[key].test(numberFormated)) {\n return key\n }\n }\n}\n\nconsole.log(getCardType("4539 5684 7526 2091"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 64923841, 'author': 'Saharat Sittipanya', 'author_id': 10767168, 'author_profile': 'https://Stackoverflow.com/users/10767168', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n<p><strong>Swift 5+</strong></p>\n</blockquote>\n<pre><code>extension String {\n \n func isMatch(_ Regex: String) -> Bool {\n \n do {\n let regex = try NSRegularExpression(pattern: Regex)\n let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))\n return results.map {\n String(self[Range($0.range, in: self)!])\n }.count > 0\n } catch {\n return false\n }\n \n }\n \n func getCreditCardType() -> String? {\n \n let VISA_Regex = "^4[0-9]{6,}$"\n let MasterCard_Regex = "^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$"\n let AmericanExpress_Regex = "^3[47][0-9]{5,}$"\n let DinersClub_Regex = "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$"\n let Discover_Regex = "^6(?:011|5[0-9]{2})[0-9]{3,}$"\n let JCB_Regex = "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$"\n \n if self.isMatch(VISA_Regex) {\n return "VISA"\n } else if self.isMatch(MasterCard_Regex) {\n return "MasterCard"\n } else if self.isMatch(AmericanExpress_Regex) {\n return "AmericanExpress"\n } else if self.isMatch(DinersClub_Regex) {\n return "DinersClub"\n } else if self.isMatch(Discover_Regex) {\n return "Discover"\n } else if self.isMatch(JCB_Regex) {\n return "JCB"\n } else {\n return nil\n }\n \n }\n \n}\n</code></pre>\n<blockquote>\n<p><strong>Use.</strong></p>\n</blockquote>\n<pre><code>"1234123412341234".getCreditCardType()\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12382/'] |
72,769 | <p>Problem (simplified to make things clearer):</p>
<ul>
1. there is one statically-linked static.lib that has a function that increments:
<pre><code>
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount;
printf("Function called");
return CallCount++;
}
</code></pre>
2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
<pre><code>
int Managed::CallLibFunc()
{
return TheFunction();
}
</code></pre>
3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:
<pre><code>
static void Main(string[] args)
{
Managed c1 = new Managed();
int val1 = c1.CallLibFunc();
// value is zero
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// value is one
}
</code></pre>
</ul>
<p>Question:</p>
<p>Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p>
<p>Thank you very much everyone!</p>
| [{'answer_id': 73075, 'author': 'gnobal', 'author_id': 7748, 'author_profile': 'https://Stackoverflow.com/users/7748', 'pm_score': 3, 'selected': True, 'text': '<p>My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.</p>\n\n<p><a href="http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/" rel="nofollow noreferrer">This link</a> shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.</p>\n\n<p><a href="http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/" rel="nofollow noreferrer">This link</a> is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I\'m not sure this can help you but maybe you\'ll find this useful to create some kind of a workaround.</p>\n'}, {'answer_id': 73135, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 0, 'selected': False, 'text': "<p>In short, maybe. AppDomains are purely a managed concept. When an AppDomain is instantiated it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)</p>\n\n<p>Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.</p>\n\n<p>You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride. For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.</p>\n"}, {'answer_id': 73289, 'author': 'Seb Rose', 'author_id': 12405, 'author_profile': 'https://Stackoverflow.com/users/12405', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t think we\'re getting to the actual issue here - <a href="http://www.ddj.com/windows/184405853" rel="nofollow noreferrer">see this DDJ article</a>.</p>\n\n<p>The default value of the loader optimization attribute is SingleDomain, which "causes the AppDomain to load a private copy of each necessary assembly\'s code". Even if it were one of the Multi domain values "every AppDomain always maintains a distinct copy of static fields".</p>\n\n<p>\'managed.dll\' is (as its name implies) is a managed assembly. The code in static.lib has been statically compiled (as IL code) into \'managed.dll\', so I would expect the same behaviour as Lenik expects....</p>\n\n<p>... unless static.lib is a static export library for an unmanaged DLL. Lenik says this is not the case, so I\'m still unsure what\'s going on here.</p>\n'}, {'answer_id': 93134, 'author': 'Rick Minerich', 'author_id': 9251, 'author_profile': 'https://Stackoverflow.com/users/9251', 'pm_score': 0, 'selected': False, 'text': '<p>Have you tried running in separate processes? A static library should not share memory instances outside of it\'s own process.</p>\n\n<p>This can be a pain to manage, I know. I\'m not sure what your other options would be in this case though.</p>\n\n<p>Edit: After a little looking around I think you could do everything you needed to with the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process_members.aspx" rel="nofollow noreferrer">System.Diagnostics.Process</a> class. You would have a lot of options at this point for communication but <a href="http://msdn.microsoft.com/en-us/library/kwdt6w2k(VS.71).aspx" rel="nofollow noreferrer">.NET Remoting</a> or WCF would probably be good and easy choices.</p>\n'}, {'answer_id': 157738, 'author': 'Lou Franco', 'author_id': 3937, 'author_profile': 'https://Stackoverflow.com/users/3937', 'pm_score': 0, 'selected': False, 'text': '<p>These are the best two articles I found on the subject</p>\n\n<ul>\n<li><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx</a></li>\n<li><a href="http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx</a></li>\n</ul>\n\n<p>The important part is:</p>\n\n<blockquote>\n <p>RVA-based static fields are process-global. These are restricted to scalars and value types, because we do not want to allow objects to bleed across AppDomain boundaries. That would cause all sorts of problems, especially during AppDomain unloads. Some languages like ILASM and MC++ make it convenient to define RVA-based static fields. Most languages do not.</p>\n</blockquote>\n\n<p>Ok, so if you control the code in the .lib, I\'d try</p>\n\n<pre><code>class CallCountHolder {\n public:\n CallCountHolder(int i) : count(i) {}\n int count;\n};\n\nstatic CallCountHolder cc(0);\nint TheFunction()\n{\n printf("Function called");\n return cc.count++;\n}\n</code></pre>\n\n<p>Since he said that RVA-based static fields are limited to scalars and value types. An int array might also work.</p>\n'}, {'answer_id': 693295, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>After you call </p>\n\n<pre><code>Managed c1 = new Managed(); \n</code></pre>\n\n<p>Your managed.dll wrapper will be loaded into main app domain of you application. Till it will be there domain unmanaged stuff from static.lib will be shared with other domains. \nInstead of creating separate process you just need to be sure (before each call) that managed.dll is not loaded into any application domain. </p>\n\n<p>Compare with that </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain("NewDomain");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero\n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain("NewDomain");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is zero\n\n AppDomain.Unload(ad)\n }\n\n\n}\n`\n</code></pre>\n\n<p>IMPORTANT and : If you add just one line JIT compiler will load managed.dll and the magic disappears. </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain("NewDomain");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero \n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain("NewDomain");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is one\n\n AppDomain.Unload(ad)\n }\nManaged c1 = new Managed(); \n\n\n}\n</code></pre>\n\n<p>If you don\'t want to depend on such lines you can create another one wrapper ManagedIsolated.dll that will reference managed.dll and will make each call in separate domain with domain unload just after the call. Main application will depend only on ManagedIsolated.dll types and Managed.dll will not be loaded into main app domain.</p>\n\n<p>That looks like a trick but may be it will be usefull for somebody.\n `</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341/'] |
72,773 | <p>SharePoint 2007 (both Moss and Wss) exposes document libraries via web dav, allowing you to create documents via essentially file system level activities (e.g. saving documents to a location).</p>
<p>SharePoint also seems to expose lists via the same web dav interface, as directories but they are usually empty. Is it possible to create or manipulate a list item somehow via this exposure?</p>
| [{'answer_id': 77207, 'author': 'x0n', 'author_id': 6920, 'author_profile': 'https://Stackoverflow.com/users/6920', 'pm_score': 1, 'selected': False, 'text': '<p>In short: No. </p>\n\n<p>Longer answer: Kinda. Any item stored in sharepoint is in a list, including files. But not all lists have files. A document library is a list with each element being a file+metadata. Other lists (like announcments) are just metadata. Only lists that contain files are exposed via webdav, and even then you are limited to mucking around with the file - there is no way to use webdav (afaik) to edit the metadata.</p>\n\n<p>Hope this helps.</p>\n\n<p>Oisin.</p>\n'}, {'answer_id': 77301, 'author': 'user8625', 'author_id': 8625, 'author_profile': 'https://Stackoverflow.com/users/8625', 'pm_score': 0, 'selected': False, 'text': '<p>Agreed. The only thing exposed to webdav is a list item\'s attachment (or a library\'s documents). Even if you bring up a file\'s properties in explorer, there\'s no options for list data.</p>\n\n<p>If you\'re working with Office 2007 documents, you can create a <a href="http://msdn.microsoft.com/en-us/library/ms550037.aspx" rel="nofollow noreferrer">document information panel</a> that can be tied into sharepoint.</p>\n'}, {'answer_id': 79838, 'author': 'Sam Yates', 'author_id': 14911, 'author_profile': 'https://Stackoverflow.com/users/14911', 'pm_score': 0, 'selected': False, 'text': '<p>No, but in my experience most things looking to speak WebDAV to something are pretty much expecting to work with files or documents of some sort. Since non-library lists in SharePoint don\'t really have an associated file (yeah, they can have attachments, but that\'s not the same), then effectively the primary construct WebDAV is built around (document) is missing. What would you be Authoring and Versioning?</p>\n\n<p>If you are writing your own client, there are <a href="http://msdn.microsoft.com/en-us/library/lists.aspx" rel="nofollow noreferrer">robust web services</a> for interacting with lists (both the library and non-library varieties)</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,789 | <p>I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?</p>
| [{'answer_id': 72848, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': '<p>This will get you halfway there: <a href="http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx</a></p>\n\n<p>Then you need to find the Win32 call which will set the displayed icon from the list of embedded icons.</p>\n'}, {'answer_id': 72857, 'author': 'Thomas', 'author_id': 4980, 'author_profile': 'https://Stackoverflow.com/users/4980', 'pm_score': 0, 'selected': False, 'text': "<p>I don't know a way in visual studio, because the application settings are bound to the hole project. But a simple way is to use a PreBuild event and copy the app.demo.ico to app.ico or the app.release.ico to app.ico demanding on the value of the key $(ConfigurationName) and refer to the app.ico in your project directory.</p>\n"}, {'answer_id': 72877, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': 4, 'selected': True, 'text': '<p>According to <a href="http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx" rel="noreferrer">this page</a> you may use preprocessor directives in your *.rc file. You should write something like this</p>\n\n<pre><code>#ifdef _DEMO_VERSION_\nIDR_MAINFRAME ICON "demo.ico"\n#else\nIDR_MAINFRAME ICON "full.ico"\n#endif\n</code></pre>\n'}, {'answer_id': 72880, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 2, 'selected': False, 'text': "<p>What I would do is setup a pre-build event (Project properties -> Configuration Properties -> Build Events -> Pre-Build Event). The pre-build event is a command line. I would use this to copy the appropriate icon file to the build icon. </p>\n\n<p>For example, let's say your build icon is 'app.ico'. I would make my fullicon 'app_full.ico' and my demo icon 'app_demo.ico'. Then I would set my pre-build events as follows:</p>\n\n<p>Full mode pre-build event:</p>\n\n<pre><code>del app.ico | copy app_full.ico app.ico\n</code></pre>\n\n<p>Demo mode pre-build event:</p>\n\n<pre><code>del app.ico | copy app_demo.ico app.ico\n</code></pre>\n\n<p>I hope that helps!</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12117/'] |
72,791 | <p>In my .NET/Forms app I have a DataGridView which is bound to a DataTable. The user selects a row of the DataGridView by double-clicking and does some interaction with the app. After that the content of the row is updated programmatically.</p>
<p>When the user selects a new row the changes on the previous one are automagically propagated to the DataTable by the framework. How can I trigger this update from my code so the user does not have to select a new row?</p>
| [{'answer_id': 73224, 'author': 'Nicholas', 'author_id': 8054, 'author_profile': 'https://Stackoverflow.com/users/8054', 'pm_score': 0, 'selected': False, 'text': '<p>I guess it depends on what triggers the update to take place, if it is in a validation routine you could simply call that after the user clicks OK on editing the data. Your question is vague it would be easier to answer with more information. What is this interaction? Is it a dialog? What actually updates the data?</p>\n'}, {'answer_id': 74210, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Here is the process to clarify this:</p>\n\n<ol>\n<li>user doubleclicks row</li>\n<li>app fetches data from db, processes fetched data and fills controls on the same form as the DataGridView</li>\n<li>user interacts with controls and finally presses apply button on the same form</li>\n<li><p>app processes state of controls, writes data to db and writes data to DataGridView</p></li>\n<li><p>IF user moves selection on DataGridView</p></li>\n<li><p>THEN changes are propagated to the bound DataTable</p></li>\n</ol>\n\n<p>I would like to trigger 6 instantly after modifying the DataGridView from my code.</p>\n'}, {'answer_id': 78521, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 2, 'selected': False, 'text': '<p>I just had the same issue, and found the answer <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.iscurrentrowdirty.aspx" rel="nofollow noreferrer">here</a>:</p>\n\n<blockquote>\n <p>When the user navigates away from the\n row, the control commits all row\n changes. The user can also press\n CTRL+ENTER to commit row changes\n without leaving the row. To commit row\n changes programmatically, call the\n form\'s Validate method. If your data\n source is a BindingSource, you can\n also call BindingSource.EndEdit.</p>\n</blockquote>\n\n<p>Calling Validate() worked for me.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,799 | <p>If you had a differential of either venturing into Delphi land or Qt land which would you choose? I know they are not totally comparable. I for one have Windows development experience with Builder C++ (almost Delphi) and MFC (almost Qt), with a bit more time working with Builder C++. Please take out the cross platform ability of Qt in your analysis.</p>
<p>I'm hoping for replies of people who have worked with both and how he or she would compare the framework, environment, etc.?</p>
<p>Thank you in advance for your replies.</p>
| [{'answer_id': 72827, 'author': 'cleg', 'author_id': 29503, 'author_profile': 'https://Stackoverflow.com/users/29503', 'pm_score': 1, 'selected': False, 'text': "<p>I'd choose delphi. Only because I have more experience with it. I don't think that there is other reasonabl criterias. </p>\n"}, {'answer_id': 72873, 'author': 'kemiller2002', 'author_id': 1942, 'author_profile': 'https://Stackoverflow.com/users/1942', 'pm_score': 2, 'selected': False, 'text': '<p>I would pick Delphi, but that is probably because I have programmed it before. It seems there are still a number of companies which use it, and almost everyone who has 8+ years expierence has encountered it somewhere. It seems that most programmers can relate to using it or at least learning Pascal. Not to mention the fact that newer languages (C#) are based on it (at least partially).</p>\n'}, {'answer_id': 72882, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Qt is cross-platform, Delphi not much if we count Kylix. Lazarus is cross-platform, but not quite feature-complete yet.</p>\n'}, {'answer_id': 73003, 'author': 'Mick', 'author_id': 12458, 'author_profile': 'https://Stackoverflow.com/users/12458', 'pm_score': 5, 'selected': False, 'text': "<p>If you are talking UI frameworks, then you should be comparing Qt with the VCL, not the IDE (Delphi in this case). I know I'm being a stickler, but Delphi is the IDE, Object-Pascal is the language, and VCL is the graphical framework.</p>\n\n<p>That being said, I don't think there is anything that even comes close to matching the power and simplicity of the VCL. Qt is great, but it is no VCL.</p>\n"}, {'answer_id': 73581, 'author': 'skamradt', 'author_id': 9217, 'author_profile': 'https://Stackoverflow.com/users/9217', 'pm_score': 4, 'selected': False, 'text': '<p>I would pick Delphi. Of course you ask any pascalholic and he is sure to answer just the same. ;)</p>\n\n<p>Qt again is fine, but the VCL just feels more polished. But then that could be my years of working with it so it just feels right. My experience with Qt was limited to a short lived project that ended up being rewritten in Delphi after it was determined that cross platform was not really needed thanks to the power of <a href="http://www.resource-dynamics.com/goglobal.asp" rel="noreferrer">GoGlobal</a> which can make any win32 app a web application, and therefore run on any platform.</p>\n'}, {'answer_id': 82202, 'author': 'mxcl', 'author_id': 6444, 'author_profile': 'https://Stackoverflow.com/users/6444', 'pm_score': 5, 'selected': True, 'text': "<p><strong>Edit: This answer was written in <em>2008</em>. It probably is no longer so apt, though probably it is not entirely useless. Take with salt.</strong></p>\n\n<p>I have used both and have ended up going the Qt route. These are the reasons:</p>\n\n<ul>\n<li>Trolltech offer quick and one-to-one support via email</li>\n<li>Qt innovates, and introduces powerful new features regularly</li>\n<li>The Qt documentation is amazing, and in the rare cases where it isn't, you can read the source code</li>\n<li>Having the source code for Qt also allows you to debug inside your base libraries, which has been a life saver for me on many an occasion</li>\n<li>The API is very consistent and well designed. We have put new people on the project and within a month they show deep knowledge of the toolkit and can learn new classes very quickly</li>\n<li>It has bindings to other languages, eg. Ruby and Python.</li>\n</ul>\n\n<p>C++ is somewhat of a downside, eg. compile times, packaging, and a less integrated IDE. However Qt does make C++ feel more like a higher level language. QStrings take all the pain out of string handling for example. Thus the additional issues with C++ that you would normally face, eg. more buggy code, are less prevalent in my experience when using Qt.</p>\n\n<p>Also, there are more libraries for Delphi than for Qt, but this is mitigated due to the fact you can just use a c or c++ library in a Qt project, and also because Qt is so fully featured you often don't have to look any further.</p>\n\n<p>It would be a strange situation where I would choose Delphi over Qt for a new project.</p>\n"}, {'answer_id': 92324, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>It really depends on your needs and experience. I have worked with both (though have to say that the last Delphi version I really worked with was Delphi 6, and I\'m currently working with Qt 4.4).</p>\n\n<p><strong>The language</strong> </p>\n\n<p>C++ pros:</p>\n\n<ul>\n<li>C++ is more "standard", e.g. you will find more code, libraries, examples etc., and you may freely use the STL and boost, while Object Pascal is more of an exotic language </li>\n<li>Qt compiles on different platforms and compilers (Kylix is based on Qt, BTW)</li>\n</ul>\n\n<p>Object Pascal pros:</p>\n\n<ul>\n<li>some dynamic properties are build right into the language, no ugly workarounds like the MOC are needed </li>\n<li>the compiler is highly optimized for the language and indeed very fast</li>\n<li>the language is less complex than C++ and therefore less error prone </li>\n</ul>\n\n<p><strong>The IDE</strong></p>\n\n<p>Qt pros:</p>\n\n<ul>\n<li>Strictly spoken, there is no IDE for Qt besides the Designer, but it integrates nicely into your preferred IDE (at least Visual Studio and Eclipse) </li>\n<li>the designer does a better job with layouts than Delphi forms (Note: this is based on\n Delphi 6 experience and may not be true with current versions)</li>\n</ul>\n\n<p>Delphi pros:</p>\n\n<ul>\n<li>The IDE is really polished and easy to use now, and it beats Visual Studio clearly IMO (I have no experience with Eclipse)</li>\n<li>there is no point 2... but if I had to assign the buzzword "integrated" I would assign it to the Delphi IDE </li>\n</ul>\n\n<p><strong>The framework</strong></p>\n\n<p>I will leave a comparison to others, as I don\'t know the newest VCL good enough. I have some remarks:</p>\n\n<ul>\n<li>both frameworks cover most of the needed functionality</li>\n<li>both have the source code available, which is a must IMO</li>\n<li>both have a more or less consistent structure - I prefer Qt, but this depends on your preferences (remark: I would never say that Qt is almost MFC - I have used MFC for a long time, and both Qt and Delphi - and .NET, for that matter - are way better) </li>\n<li>the VCL has more DB-oriented functionality, especially the connection with the visual components</li>\n<li>Qt has more painting (2D / 3D / OpenGL) oriented functionality</li>\n</ul>\n\n<p>Other reasons that speak for Qt IMO are the very good support and the licensing, but that depends on your needs. There are large communities for both frameworks, </p>\n'}, {'answer_id': 124309, 'author': 'Aurélien Gâteau', 'author_id': 20107, 'author_profile': 'https://Stackoverflow.com/users/20107', 'pm_score': 3, 'selected': False, 'text': "<p>A big difference between Delphi and Qt is the Qt signal/slots system, which makes it really easy to create N-to-N relationship between objects and avoid tight coupling.</p>\n\n<p>I don't think such a thing exists in Delphi (at least there was no such thing when I used to use it).</p>\n"}, {'answer_id': 877686, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Pick Delphi if your concern are native Win32 speed, a first class RAD environment and executable size. Pick QT if you need a truly cross-platform framework coupled with a now-flexible licensing policy and don't mind slightly bloated code. </p>\n\n<p>I ported an old Delphi program under QT/C++, and I must say that QT is the framework that comes closest to VCL in terms of ease of use and power (IMHO)</p>\n"}, {'answer_id': 1127800, 'author': 'Gad D Lord', 'author_id': 69358, 'author_profile': 'https://Stackoverflow.com/users/69358', 'pm_score': 2, 'selected': False, 'text': '<p>I just started experimenting with Qt/C++/Qt Creator and I must admit I was surprised that this "little cute bastard" was just below my nose for some many years and I pay attention to it just now.</p>\n\n<p>It (the framework) looks neat, feature-complete (even was stuff that .NET lacks such as inbuld XQuery support).</p>\n\n<p>Seems that most of the Qt applications written are dealing with 2D/3D/Games.</p>\n\n<p>I believe the downsides are only: having to know C++ and the lack of DevExpress goodies like QuantumGrid.</p>\n\n<p>I am seriously considering porting one of my simple applications (a picture viewer like ThumbsView).</p>\n\n<p>And it REALLY runs from same codebase. FOR REAL!</p>\n\n<p>Forget about Kylix, Mono, Lazarus, Free Pascal. This Qt thing beats them all in 10 times.</p>\n\n<p>Qt Creator is far from IDE. But I hope in the future they will add a more powerfull debugger, code insight and refactoring (at least the "Rename" one) and more meaningful compiler errors.</p>\n\n<p>I would seriously recommend to someone without experience in Pascal/C++ to take the Qt learning curve.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11994/'] |
72,829 | <p>Can anyone recommend a good (preferably open source) tool for creating WSDL files for some soap web services?</p>
<p>I've tried playing around with some of the eclipse plug ins available and was less than impressed with what I found.</p>
| [{'answer_id': 72948, 'author': 'pjesi', 'author_id': 1296737, 'author_profile': 'https://Stackoverflow.com/users/1296737', 'pm_score': 2, 'selected': False, 'text': '<p>I am tired of generating massive amounts of files on the filesystem just to transport over SOAP. Now I use <a href="http://cxf.apache.org/" rel="nofollow noreferrer">Apache CXF</a> for both WS producers and consumers and let it handle the WSDL/stubs generation dynamically.</p>\n'}, {'answer_id': 72969, 'author': 'toluju', 'author_id': 12457, 'author_profile': 'https://Stackoverflow.com/users/12457', 'pm_score': 0, 'selected': False, 'text': '<p>Depends on which language you\'re working in, but if you\'re active in Java then I\'d recommend looking at <a href="http://cxf.apache.org/" rel="nofollow noreferrer">Apache CXF</a>. It\'s a pretty solid framework for publishing java code as a SOAP web service. It also includes a tool for directly generating WSDL files: <a href="http://cwiki.apache.org/CXF20DOC/java-to-wsdl.html" rel="nofollow noreferrer">java2wsdl</a></p>\n'}, {'answer_id': 73251, 'author': 'Michael Sharek', 'author_id': 1958, 'author_profile': 'https://Stackoverflow.com/users/1958', 'pm_score': 3, 'selected': False, 'text': '<p>As mentioned above, probably the easiest thing to do is use Apache CXF or Apache Axis2 to automatically generate your WSDL for you.</p>\n\n<p>If you have downloaded the Java EE version of Eclipse, you should be able to create a Dynamic Web Project with the Axis2 facets. If you create a simple Java class in the project, you should be able to right-click on it, and choose Web Services->Create Web Service. That should automatically create an Axis2 service for you.</p>\n\n<p>WSDL would then be available from some URL like: <code>http://localhost/axis/{yourservice}?WSDL</code></p>\n'}, {'answer_id': 570900, 'author': 'John Greeley', 'author_id': 62209, 'author_profile': 'https://Stackoverflow.com/users/62209', 'pm_score': 2, 'selected': False, 'text': '<p>One of the more interesting tools for bypassing all the associated headaches with WSDL is the XSLT script created by Arjen Poutsma (the lead developer of Spring Web Services):</p>\n\n<p><a href="http://blog.springframework.com/arjen/archives/2006/07/27/xslt-that-transforms-from-xsd-to-wsdl/" rel="nofollow noreferrer">http://blog.springframework.com/arjen/archives/2006/07/27/xslt-that-transforms-from-xsd-to-wsdl/</a></p>\n\n<p>Basically it allows you to develop simple schemas that correspond to your desired operations (i.e. <code><BuyItem></code> and <code><BuyItemResponse></code>) and then generate all the associated WSDL crap from the XSD. I highly recommend it if you are interested in \'contract-first\' web-services but the idea of using a WSDL as the starting point for that contract makes you feel green.</p>\n'}, {'answer_id': 45962473, 'author': 'info', 'author_id': 8538442, 'author_profile': 'https://Stackoverflow.com/users/8538442', 'pm_score': 0, 'selected': False, 'text': '<p>Nice tool can be found as SAAS solution at www.cofiq.com. Its strong point is the datamodel repository from which WSDL and REST JSON can be generated and impact analysis on datamodel changes.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2246765/'] |
72,831 | <p>Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?</p>
| [{'answer_id': 72862, 'author': 'ageektrapped', 'author_id': 631, 'author_profile': 'https://Stackoverflow.com/users/631', 'pm_score': 9, 'selected': True, 'text': '<p><code>TextInfo.ToTitleCase()</code> capitalizes the first character in each token of a string.<br />\nIf there is no need to maintain Acronym Uppercasing, then you should include <code>ToLower()</code>.</p>\n\n<pre><code>string s = "JOHN DOE";\ns = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());\n// Produces "John Doe"\n</code></pre>\n\n<p>If CurrentCulture is unavailable, use:</p>\n\n<pre><code>string s = "JOHN DOE";\ns = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());\n</code></pre>\n\n<p>See the <a href="http://msdn2.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx" rel="noreferrer">MSDN Link</a> for a detailed description.</p>\n'}, {'answer_id': 72864, 'author': 'ckal', 'author_id': 10276, 'author_profile': 'https://Stackoverflow.com/users/10276', 'pm_score': 3, 'selected': False, 'text': '<p>ToTitleCase() should work for you.</p>\n\n<p><a href="http://support.microsoft.com/kb/312890" rel="noreferrer">http://support.microsoft.com/kb/312890</a></p>\n'}, {'answer_id': 72871, 'author': 'Nathan Baulch', 'author_id': 8799, 'author_profile': 'https://Stackoverflow.com/users/8799', 'pm_score': 7, 'selected': False, 'text': '<pre><code>CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");\n</code></pre>\n'}, {'answer_id': 72888, 'author': 'rjzii', 'author_id': 1185, 'author_profile': 'https://Stackoverflow.com/users/1185', 'pm_score': 2, 'selected': False, 'text': '<p>The most direct option is going to be to use the <a href="http://support.microsoft.com/kb/312890" rel="nofollow noreferrer">ToTitleCase</a> function that is available in .NET which should take care of the name most of the time. As <a href="https://stackoverflow.com/questions/72831/how-do-i-capitalize-first-letter-of-first-name-and-last-name-in-c#72850">edg</a> pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.</p>\n\n<p>However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.</p>\n\n<pre><code>firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();\nlastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();\n</code></pre>\n\n<p>However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and <a href="http://msdn.microsoft.com/en-us/library/ms228388(VS.80).aspx" rel="nofollow noreferrer">split it</a> accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.</p>\n'}, {'answer_id': 72901, 'author': 'David C', 'author_id': 12385, 'author_profile': 'https://Stackoverflow.com/users/12385', 'pm_score': 2, 'selected': False, 'text': '<p>CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");</p>\n\n<p>returns ~ My Name</p>\n\n<p>But the problem still exists with names like McFly as stated earlier.</p>\n'}, {'answer_id': 72910, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': '<p>If your using vS2k8, you can use an extension method to add it to the String class:</p>\n\n<pre><code>public static string FirstLetterToUpper(this String input)\n{\n return input = input.Substring(0, 1).ToUpper() + \n input.Substring(1, input.Length - 1);\n}\n</code></pre>\n'}, {'answer_id': 72939, 'author': 'Michael Haren', 'author_id': 29, 'author_profile': 'https://Stackoverflow.com/users/29', 'pm_score': -1, 'selected': False, 'text': "<p>Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).</p>\n\n<p>Something like this untested c# should handle the simple case you requested:</p>\n\n<pre><code>public string SentenceCase(string input)\n{\n return input(0, 1).ToUpper + input.Substring(1).ToLower;\n}\n</code></pre>\n"}, {'answer_id': 73688, 'author': 'Tundey', 'author_id': 1453, 'author_profile': 'https://Stackoverflow.com/users/1453', 'pm_score': 2, 'selected': False, 'text': "<p>The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.</p>\n"}, {'answer_id': 73691, 'author': 'Jamie Ide', 'author_id': 12752, 'author_profile': 'https://Stackoverflow.com/users/12752', 'pm_score': 3, 'selected': False, 'text': '<p>Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn\'t handle those cases and shouldn\'t be used for this purpose. Here\'s how I\'m doing it:</p>\n\n<pre><code> public static string ToTitleCase(string str)\n {\n string result = str;\n if (!string.IsNullOrEmpty(str))\n {\n var words = str.Split(\' \');\n for (int index = 0; index < words.Length; index++)\n {\n var s = words[index];\n if (s.Length > 0)\n {\n words[index] = s[0].ToString().ToUpper() + s.Substring(1);\n }\n }\n result = string.Join(" ", words);\n }\n return result;\n }\n</code></pre>\n'}, {'answer_id': 74008, 'author': 'Eddie Velasquez', 'author_id': 12851, 'author_profile': 'https://Stackoverflow.com/users/12851', 'pm_score': 2, 'selected': False, 'text': '<p>This class does the trick. You can add new prefixes to the <strong>_prefixes</strong> static string array. </p>\n\n<pre><code>public static class StringExtensions\n{\n public static string ToProperCase( this string original )\n {\n if( String.IsNullOrEmpty( original ) )\n return original;\n\n string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );\n return result;\n }\n\n public static string WordToProperCase( this string word )\n {\n if( String.IsNullOrEmpty( word ) )\n return word;\n\n if( word.Length > 1 )\n return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );\n\n return word.ToUpper( CultureInfo.CurrentCulture );\n }\n\n private static readonly Regex _properNameRx = new Regex( @"\\b(\\w+)\\b" );\n private static readonly string[] _prefixes = {\n "mc"\n };\n\n private static string HandleWord( Match m )\n {\n string word = m.Groups[1].Value;\n\n foreach( string prefix in _prefixes )\n {\n if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )\n return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();\n }\n\n return word.WordToProperCase();\n }\n}\n</code></pre>\n'}, {'answer_id': 74023, 'author': 'Andy Rose', 'author_id': 1762, 'author_profile': 'https://Stackoverflow.com/users/1762', 'pm_score': 0, 'selected': False, 'text': '<p>To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\\\'") to determine special cases that need more specific attention.</p>\n\n<pre><code>inputString = inputString.ToLower();\ninputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);\nint indexOfMc = inputString.IndexOf(" Mc");\nif(indexOfMc > 0)\n{\n inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);\n}\n</code></pre>\n'}, {'answer_id': 3169381, 'author': 'Ganesan SubbiahPandian', 'author_id': 382422, 'author_profile': 'https://Stackoverflow.com/users/382422', 'pm_score': 5, 'selected': False, 'text': '<pre><code>String test = "HELLO HOW ARE YOU";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);\n</code></pre>\n\n<p>The above code wont work .....</p>\n\n<p>so put the below code by convert to lower then apply the function</p>\n\n<pre><code>String test = "HELLO HOW ARE YOU";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());\n</code></pre>\n'}, {'answer_id': 4759134, 'author': 'Ton Snoei', 'author_id': 584472, 'author_profile': 'https://Stackoverflow.com/users/584472', 'pm_score': 2, 'selected': False, 'text': '<p>I use my own method to get this fixed:</p>\n\n<p>For example the phrase: "hello world. hello this is the stackoverflow world." will be "Hello World. Hello This Is The Stackoverflow World.". Regex \\b (start of a word) \\w (first charactor of the word) will do the trick. </p>\n\n<pre><code>/// <summary>\n/// Makes each first letter of a word uppercase. The rest will be lowercase\n/// </summary>\n/// <param name="Phrase"></param>\n/// <returns></returns>\npublic static string FormatWordsWithFirstCapital(string Phrase)\n{\n MatchCollection Matches = Regex.Matches(Phrase, "\\\\b\\\\w");\n Phrase = Phrase.ToLower();\n foreach (Match Match in Matches)\n Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());\n\n return Phrase;\n}\n</code></pre>\n'}, {'answer_id': 12413336, 'author': 'TrentVB', 'author_id': 1118056, 'author_profile': 'https://Stackoverflow.com/users/1118056', 'pm_score': 0, 'selected': False, 'text': '<p>I like this way:</p>\n\n<pre><code>using System.Globalization;\n...\nTextInfo myTi = new CultureInfo("en-Us",false).TextInfo;\nstring raw = "THIS IS ALL CAPS";\nstring firstCapOnly = myTi.ToTitleCase(raw.ToLower());\n</code></pre>\n\n<p>Lifted from this <a href="http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase%28v=vs.100%29.aspx" rel="nofollow">MSDN article</a>.</p>\n'}, {'answer_id': 14121370, 'author': 'Arun', 'author_id': 1063254, 'author_profile': 'https://Stackoverflow.com/users/1063254', 'pm_score': 0, 'selected': False, 'text': '<p>Hope this helps you.</p>\n\n<pre><code>String fName = "firstname";\nString lName = "lastname";\nString capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);\nString capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);\n</code></pre>\n'}, {'answer_id': 19517670, 'author': 'polkduran', 'author_id': 848634, 'author_profile': 'https://Stackoverflow.com/users/848634', 'pm_score': 4, 'selected': False, 'text': '<p>There are some cases that <code>CultureInfo.CurrentCulture.TextInfo.ToTitleCase</code> cannot handle, for example : the apostrophe <code>\'</code>.</p>\n\n<pre><code>string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("o\'reilly, m\'grego, d\'angelo");\n// input = O\'reilly, M\'grego, D\'angelo\n</code></pre>\n\n<p>A <strong>regex</strong> can also be used <code>\\b[a-zA-Z]</code> to identify the starting character of a word after a word boundary <code>\\b</code>, then we need just to replace the match by its upper case equivalence thanks to the <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/ht1sxswy%28v=vs.110%29.aspx"><code>Regex.Replace(string input,string pattern,MatchEvaluator evaluator)</code></a> method : </p>\n\n<pre><code>string input = "o\'reilly, m\'grego, d\'angelo";\ninput = Regex.Replace(input.ToLower(), @"\\b[a-zA-Z]", m => m.Value.ToUpper());\n// input = O\'Reilly, M\'Grego, D\'Angelo\n</code></pre>\n\n<p>The <strong>regex</strong> can be tuned if needed, for instance, if we want to handle the <code>MacDonald</code> and <code>McFry</code> cases the regex becomes : <code>(?<=\\b(?:mc|mac)?)[a-zA-Z]</code></p>\n\n<pre><code>string input = "o\'reilly, m\'grego, d\'angelo, macdonald\'s, mcfry";\ninput = Regex.Replace(input.ToLower(), @"(?<=\\b(?:mc|mac)?)[a-zA-Z]", m => m.Value.ToUpper());\n// input = O\'Reilly, M\'Grego, D\'Angelo, MacDonald\'S, McFry\n</code></pre>\n\n<p>If we need to handle more prefixes we only need to modify the group <code>(?:mc|mac)</code>, for example to add french prefixes <code>du, de</code> : <code>(?:mc|mac|du|de)</code>.</p>\n\n<p>Finally, we can realize that this <strong>regex</strong> will also match the case <code>MacDonald\'S</code> for the last <code>\'s</code> so we need to handle it in the <strong>regex</strong> with a negative look behind <code>(?<!\'s\\b)</code>. At the end we have :</p>\n\n<pre><code>string input = "o\'reilly, m\'grego, d\'angelo, macdonald\'s, mcfry";\ninput = Regex.Replace(input.ToLower(), @"(?<=\\b(?:mc|mac)?)[a-zA-Z](?<!\'s\\b)", m => m.Value.ToUpper());\n// input = O\'Reilly, M\'Grego, D\'Angelo, MacDonald\'s, McFry\n</code></pre>\n'}, {'answer_id': 40882007, 'author': 'Govind Singh Rawat', 'author_id': 5580191, 'author_profile': 'https://Stackoverflow.com/users/5580191', 'pm_score': 0, 'selected': False, 'text': '<pre><code> public static string ConvertToCaptilize(string input)\n {\n if (!string.IsNullOrEmpty(input))\n {\n string[] arrUserInput = input.Split(\' \');\n\n\n // Initialize a string builder object for the output\n StringBuilder sbOutPut = new StringBuilder();\n\n\n // Loop thru each character in the string array\n foreach (string str in arrUserInput)\n {\n if (!string.IsNullOrEmpty(str))\n {\n var charArray = str.ToCharArray();\n int k = 0;\n foreach (var cr in charArray)\n {\n char c;\n c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);\n sbOutPut.Append(c);\n k++;\n }\n\n\n }\n sbOutPut.Append(" ");\n }\n return sbOutPut.ToString();\n }\n return string.Empty;\n\n }\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9938/'] |
72,832 | <p>When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options.</p>
<ol>
<li>Suppress a violation in code.</li>
<li>Suppress a violation in a GlobalSupression.cs file.</li>
<li>Disable the violation check in the project file (via Project -> Properties -> Code Analysic).</li>
</ol>
<p>The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2.</p>
<p>The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like: </p>
<pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")]
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")]
</code></pre>
<p>We would love to do something like this ing GlobalSuppressions.cs:</p>
<pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")]
</code></pre>
<p>But is this possible?</p>
| [{'answer_id': 73369, 'author': 'Ishmaeel', 'author_id': 227, 'author_profile': 'https://Stackoverflow.com/users/227', 'pm_score': 4, 'selected': True, 'text': '<p>Suppressing multiple violations with a single <strong>SuppressMessage</strong> attribute is officially not supported. Apparently, this is by design.</p>\n\n<p>I agree, it might be annoying at times, but I can\'t say I disagree with the decision, since the attribute is their way to force you to say, "Yes, I know what I am doing", which should be evaluated in a case-by-case basis.</p>\n'}, {'answer_id': 18930943, 'author': 'RenniePet', 'author_id': 253938, 'author_profile': 'https://Stackoverflow.com/users/253938', 'pm_score': 1, 'selected': False, 'text': '<p>I think things have changed since this question was posted and answered. For Visual Studio 2010 and 2012 you can create a custom "rule set" file where you can specify which code analysis rules you want to suppress. </p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/dd380660.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd380660.aspx</a></p>\n\n<p>So what I\'ve done is to create a single custom rule set file which is in the top level folder of my repository source collection, and I reference this file in each Visual Studio project. This means I have one central place where I can suppress the code analysis rules that I simply can\'t stand. But if I ever change my mind, or decide I should reconsider my bad coding habits, I can very simply reenable the rule and see how many code analysis messages I get. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8547/'] |
72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>
| [{'answer_id': 73149, 'author': 'John B', 'author_id': 9597, 'author_profile': 'https://Stackoverflow.com/users/9597', 'pm_score': 10, 'selected': True, 'text': '<p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>\n\n<p>The problem is that you\'re running the module as \'__main__\' by passing the mod1.py as an argument to the interpreter.</p>\n\n<p>From <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328</a>:</p>\n\n<blockquote>\n <p>Relative imports use a module\'s __name__ attribute to determine that module\'s position in the package hierarchy. If the module\'s name does not contain any package information (e.g. it is set to \'__main__\') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>\n</blockquote>\n\n<p>In Python 2.6, they\'re adding the ability to reference modules relative to the main module. <a href="http://python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> describes the change.</p>\n\n<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p>\n'}, {'answer_id': 465129, 'author': 'nosklo', 'author_id': 17160, 'author_profile': 'https://Stackoverflow.com/users/17160', 'pm_score': 7, 'selected': False, 'text': "<pre><code>main.py\nsetup.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n module_a.py\n package_b/ ->\n __init__.py\n module_b.py\n</code></pre>\n\n<ol>\n<li>You run <code>python main.py</code>.</li>\n<li><code>main.py</code> does: <code>import app.package_a.module_a</code></li>\n<li><code>module_a.py</code> does <code>import app.package_b.module_b</code></li>\n</ol>\n\n<p>Alternatively 2 or 3 could use: <code>from app.package_a import module_a</code></p>\n\n<p>That will work as long as you have <code>app</code> in your PYTHONPATH. <code>main.py</code> could be anywhere then.</p>\n\n<p>So you write a <code>setup.py</code> to copy (install) the whole app package and subpackages to the target system's python folders, and <code>main.py</code> to target system's script folders.</p>\n"}, {'answer_id': 1083169, 'author': 'iElectric', 'author_id': 133235, 'author_profile': 'https://Stackoverflow.com/users/133235', 'pm_score': 5, 'selected': False, 'text': '<pre><code>def import_path(fullpath):\n """ \n Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do. \n """\n path, filename = os.path.split(fullpath)\n filename, ext = os.path.splitext(filename)\n sys.path.append(path)\n module = __import__(filename)\n reload(module) # Might be out of date\n del sys.path[-1]\n return module\n</code></pre>\n\n<p>I\'m using this snippet to import modules from paths, hope that helps</p>\n'}, {'answer_id': 6524846, 'author': 'jung rhew', 'author_id': 821632, 'author_profile': 'https://Stackoverflow.com/users/821632', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="nofollow">Python doc</a>,</p>\n\n<blockquote>\n <p>In Python 2.5, you can switch import‘s behaviour to absolute imports using a <code>from __future__ import absolute_import</code> directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, <code>import string</code> will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing <code>from pkg import string</code> in your code</p>\n</blockquote>\n'}, {'answer_id': 7541369, 'author': 'mossplix', 'author_id': 487623, 'author_profile': 'https://Stackoverflow.com/users/487623', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="noreferrer">http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports</a>. You could do </p>\n\n<pre><code>from .mod1 import stuff\n</code></pre>\n'}, {'answer_id': 8195271, 'author': 'lesnik', 'author_id': 788775, 'author_profile': 'https://Stackoverflow.com/users/788775', 'pm_score': 6, 'selected': False, 'text': '<p>"Guido views running scripts within a package as an anti-pattern" (rejected\n<a href="http://www.python.org/dev/peps/pep-3122/">PEP-3122</a>)</p>\n\n<p>I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.</p>\n'}, {'answer_id': 9541554, 'author': 'Garrett Berg', 'author_id': 674076, 'author_profile': 'https://Stackoverflow.com/users/674076', 'pm_score': 4, 'selected': False, 'text': '<p>This is unfortunately a sys.path hack, but it works quite well.</p>\n\n<p>I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.</p>\n\n<p>what I wanted to do was the following (the module I was working from was module3):</p>\n\n<pre><code>mymodule\\\n __init__.py\n mymodule1\\\n __init__.py\n mymodule1_1\n mymodule2\\\n __init__.py\n mymodule2_1\n\n\nimport mymodule.mymodule1.mymodule1_1 \n</code></pre>\n\n<p>Note that I have already installed mymodule, but in my installation I do not have "mymodule1"</p>\n\n<p>and I would get an ImportError because it was trying to import from my installed modules.</p>\n\n<p>I tried to do a sys.path.append, and that didn\'t work. What did work was a <strong>sys.path.insert</strong></p>\n\n<pre><code>if __name__ == \'__main__\':\n sys.path.insert(0, \'../..\')\n</code></pre>\n\n<p>So kind of a hack, but got it all to work!\nSo keep in mind, if you want your decision to <strong>override other paths</strong> then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn\'t work if you already have a module defined (I find it very strange behavior)</p>\n'}, {'answer_id': 9748770, 'author': 'Andrew_1510', 'author_id': 451718, 'author_profile': 'https://Stackoverflow.com/users/451718', 'pm_score': 1, 'selected': False, 'text': '<p>I found it\'s more easy to set "PYTHONPATH" enviroment variable to the top folder:</p>\n\n<pre><code>bash$ export PYTHONPATH=/PATH/TO/APP\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>import sub1.func1\n#...more import\n</code></pre>\n\n<p>of course, PYTHONPATH is "global", but it didn\'t raise trouble for me yet.</p>\n'}, {'answer_id': 12365065, 'author': 'Gabriel', 'author_id': 1621769, 'author_profile': 'https://Stackoverflow.com/users/1621769', 'pm_score': 1, 'selected': False, 'text': '<p>On top of what John B said, it seems like setting the <code>__package__</code> variable should help, instead of changing <code>__main__</code> which could screw up other things. But as far as I could test, it doesn\'t completely work as it should.</p>\n\n<p>I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in <code>sys.path</code>, as far as I could understand.</p>\n\n<p>I should also mention that I did not find how to format the string that should go into those variables. Is it <code>"package_head.subfolder.module_name"</code> or what? </p>\n'}, {'answer_id': 14189875, 'author': 'milkypostman', 'author_id': 154508, 'author_profile': 'https://Stackoverflow.com/users/154508', 'pm_score': 4, 'selected': False, 'text': '<p>Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a <code>scripts</code> directory.</p>\n\n<pre><code>import os.path\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))\n</code></pre>\n'}, {'answer_id': 15458607, 'author': 'Pankaj', 'author_id': 382630, 'author_profile': 'https://Stackoverflow.com/users/382630', 'pm_score': 7, 'selected': False, 'text': "<p>Here is the solution which works for me:</p>\n\n<p>I do the relative imports as <code>from ..sub2 import mod2</code>\nand then, if I want to run <code>mod1.py</code> then I go to the parent directory of <code>app</code> and run the module using the python -m switch as <code>python -m app.sub1.mod1</code>.</p>\n\n<p>The real reason why this problem occurs with relative imports, is that relative imports works by taking the <code>__name__</code> property of the module. If the module is being directly run, then <code>__name__</code> is set to <code>__main__</code> and it doesn't contain any information about package structure. And, thats why python complains about the <code>relative import in non-package</code> error. </p>\n\n<p>So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.</p>\n\n<p>I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)</p>\n\n<p>Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.</p>\n"}, {'answer_id': 20449492, 'author': 'suhailvs', 'author_id': 2351696, 'author_profile': 'https://Stackoverflow.com/users/2351696', 'pm_score': 5, 'selected': False, 'text': "<p>explanation of <code>nosklo's</code> answer with examples</p>\n\n<p><em>note: all <code>__init__.py</code> files are empty.</em></p>\n\n<pre><code>main.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n fun_a.py\n package_b/ ->\n __init__.py\n fun_b.py\n</code></pre>\n\n<h3>app/package_a/fun_a.py</h3>\n\n<pre><code>def print_a():\n print 'This is a function in dir package_a'\n</code></pre>\n\n<h3>app/package_b/fun_b.py</h3>\n\n<pre><code>from app.package_a.fun_a import print_a\ndef print_b():\n print 'This is a function in dir package_b'\n print 'going to call a function in dir package_a'\n print '-'*30\n print_a()\n</code></pre>\n\n<h3>main.py</h3>\n\n<pre><code>from app.package_b import fun_b\nfun_b.print_b()\n</code></pre>\n\n<p>if you run <code>$ python main.py</code> it returns:</p>\n\n<pre><code>This is a function in dir package_b\ngoing to call a function in dir package_a\n------------------------------\nThis is a function in dir package_a\n</code></pre>\n\n<ul>\n<li>main.py does: <code>from app.package_b import fun_b</code> </li>\n<li>fun_b.py does <code>from app.package_a.fun_a import print_a</code></li>\n</ul>\n\n<p>so file in folder <code>package_b</code> used file in folder <code>package_a</code>, which is what you want. Right??</p>\n"}, {'answer_id': 30736316, 'author': 'LondonRob', 'author_id': 2071807, 'author_profile': 'https://Stackoverflow.com/users/2071807', 'pm_score': 3, 'selected': False, 'text': '<p>As @EvgeniSergeev says in the comments to the OP, you can import code from a <code>.py</code> file at an arbitrary location with:</p>\n\n<pre><code>import imp\n\nfoo = imp.load_source(\'module.name\', \'/path/to/file.py\')\nfoo.MyClass()\n</code></pre>\n\n<p>This is taken from <a href="https://stackoverflow.com/a/67692/2071807">this SO answer</a>.</p>\n'}, {'answer_id': 35338828, 'author': 'Роман Арсеньев', 'author_id': 5774201, 'author_profile': 'https://Stackoverflow.com/users/5774201', 'pm_score': 6, 'selected': False, 'text': '<p>This is solved 100%:</p>\n\n<ul>\n<li>app/\n\n<ul>\n<li>main.py</li>\n</ul></li>\n<li>settings/\n\n<ul>\n<li>local_setings.py</li>\n</ul></li>\n</ul>\n\n<p>Import settings/local_setting.py in app/main.py:</p>\n\n<p>main.py:</p>\n\n<pre><code>import sys\nsys.path.insert(0, "../settings")\n\n\ntry:\n from local_settings import *\nexcept ImportError:\n print(\'No Import\')\n</code></pre>\n'}, {'answer_id': 60846688, 'author': 'Giorgos Myrianthous', 'author_id': 7131757, 'author_profile': 'https://Stackoverflow.com/users/7131757', 'pm_score': 1, 'selected': False, 'text': '<p>You have to append the module’s path to <code>PYTHONPATH</code>: </p>\n\n<pre><code>export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"\n</code></pre>\n'}, {'answer_id': 70163621, 'author': 'Rohit Kumar J', 'author_id': 14376181, 'author_profile': 'https://Stackoverflow.com/users/14376181', 'pm_score': 0, 'selected': False, 'text': '<p>This method queries and auto populates the path:</p>\n<pre class="lang-py prettyprint-override"><code>import os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(1, parentdir)\n# print("currentdir = ", currentdir)\n# print("parentdir=", parentdir)\n</code></pre>\n'}, {'answer_id': 71315540, 'author': 'F.M.F.', 'author_id': 4858818, 'author_profile': 'https://Stackoverflow.com/users/4858818', 'pm_score': 0, 'selected': False, 'text': '<p>A hacky way to do it is to append the current directory to the PATH at runtime as follows:</p>\n<pre><code>import pathlib \nimport sys\nsys.path.append(pathlib.Path(__file__).parent.resolve())\nimport file_to_import # the actual intended import\n</code></pre>\n<p>In contrast to another solution for this question this uses <code>pathlib</code> instead of <code>os.path</code>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3497/'] |
72,858 | <p>I have a VPS host running 3 sites using Ubuntu Hardy. I've spent much time setting it up. That includes all the installation + configuration and stuff. What ways are there to do backup + restore for VPS? </p>
| [{'answer_id': 72897, 'author': 'ceejayoz', 'author_id': 1902010, 'author_profile': 'https://Stackoverflow.com/users/1902010', 'pm_score': 0, 'selected': False, 'text': "<p>It'll depend a lot on what your host offers. MediaTemple and Slicehost both offer snapshot backups for a nominal fee. Contact your host and ask if they offer such a solution.</p>\n\n<p>If your host doesn't offer anything, you could always backup the critical stuff regularly to something like Amazon's S3 storage service.</p>\n"}, {'answer_id': 72990, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': 2, 'selected': False, 'text': "<p>Backups alone aren't enough. You should be keeping a detailed system log of all configuration changes you make to the system so that you can reproduce your configuration elsewhere. Ideally, perform the changes on a local VM, then write a script to perform those changes automatically, then run those scripts on the live server. By avoiding manual configuration, all your configuration is repeatable, so to deploy to a new server, you just have to run all of your scripts in sequence.</p>\n"}, {'answer_id': 4690962, 'author': 'Victor M', 'author_id': 575648, 'author_profile': 'https://Stackoverflow.com/users/575648', 'pm_score': 2, 'selected': False, 'text': '<p>You can try to implement a simple script to backup your data using rsynch - you\'ll need a second Linux machine with Internet access and some tinkering to make sure your backups are reliable in case you need to restore the - think /etc/ settings, website files and any databases you might have. Pay special attention to file permissions.\nSome hosting companies offer managed backup with their plans - you could look into that as well, but make sure your backups run and are stored remotely - you don\'t want the same disaster to strike all copies of your precious data.\nLast, if you can do with a small amount of disk space for your backups, you can try a free account from <a href="http://ww.vps-backup.com" rel="nofollow">VPS Backup</a> - it\'s free up to 5GB of compressed data, works on most flavors of Linux and is specially suited to backup MySQL databases as well. Since you don\'t have to pay for it, it might be a good workaround until you figure longtime solution.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11927/'] |
72,872 | <p>How can I redirect the response to an IFrame?</p>
| [{'answer_id': 72885, 'author': 'Bob Dizzle', 'author_id': 9581, 'author_profile': 'https://Stackoverflow.com/users/9581', 'pm_score': 0, 'selected': False, 'text': '<p>. . . not totally sure what your trying to do, but you normally control the source of an iframe through javascript</p>\n'}, {'answer_id': 72890, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 3, 'selected': True, 'text': "<p>Do you mean from the server-side? - You can't!</p>\n\n<p><strong>You'll have to do it on the client side.</strong></p>\n\n<p>Say, use a javascript that sends an <em>AJAX request</em> and then embed your response information in the <em>AJAX response</em>. And have the javascript read the response and changes the page in the intended frame accordingly</p>\n"}, {'answer_id': 912473, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You can do this through a post-back.</p>\n\n<p>Add a tag to your iframe like this:</p>\n\n<p>< iframe runat="server" id="myIframe" /></p>\n\n<p>in your server-side code (button click, link click, whatever posts back):</p>\n\n<p>myIframe.attributes.add ("src", "webpage.aspx")</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12452/'] |
72,879 | <p>Are there any programs or IDEs that support refactoring for Ruby or RoR?</p>
| [{'answer_id': 72946, 'author': 'mmaibaum', 'author_id': 12213, 'author_profile': 'https://Stackoverflow.com/users/12213', 'pm_score': 2, 'selected': False, 'text': "<p>I believe net-beans and eclipse both support some refactoring within their 'ruby-mode' - also the emacs code browser (ECB) and the various ruby support tools (e.g. rinari) for emacs have some support. </p>\n"}, {'answer_id': 73341, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.jetbrains.com" rel="nofollow noreferrer">IntelliJ IDEA</a> with Ruby plugin supports some refactorings.</p>\n\n<p><a href="http://www.skavish.com/rubyrefactorings.png" rel="nofollow noreferrer">alt text http://www.skavish.com/rubyrefactorings.png</a></p>\n'}, {'answer_id': 86567, 'author': 'RFelix', 'author_id': 10582, 'author_profile': 'https://Stackoverflow.com/users/10582', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s also <a href="http://www.codegear.com/products/3rdrail" rel="nofollow noreferrer">3rdRail</a> from CodeGear (from Delphi fame). The only catch is that it\'s not free.</p>\n'}, {'answer_id': 99925, 'author': 'Melvin Ram', 'author_id': 18553, 'author_profile': 'https://Stackoverflow.com/users/18553', 'pm_score': 1, 'selected': False, 'text': "<p>Aptana has some simple refactoring tools. I often extract into partials and they have a simple shortcut for pulling things out, creating a file and inserting the right call to the partial. Not the most amazing ever but it's useful</p>\n"}, {'answer_id': 129661, 'author': 'srboisvert', 'author_id': 6805, 'author_profile': 'https://Stackoverflow.com/users/6805', 'pm_score': 0, 'selected': False, 'text': "<p>I've used the refactoring in netbeans. I didn't find it that much more useful than find and replace.</p>\n"}, {'answer_id': 148240, 'author': 'domgblackwell', 'author_id': 16954, 'author_profile': 'https://Stackoverflow.com/users/16954', 'pm_score': 3, 'selected': False, 'text': '<p>The best refactoring tool is good test coverage. If your tests cover your code and they all past you can just make whatever changes you want and the tests will find any dependencies you have broken. This is the main reason why IDE-based refactoring tools are less prevalent in Ruby than elsewhere.</p>\n'}, {'answer_id': 5906207, 'author': 'thekindofme', 'author_id': 223569, 'author_profile': 'https://Stackoverflow.com/users/223569', 'pm_score': 1, 'selected': False, 'text': "<p>I'd be bold and say that Rubymine has the best rails/ruby refactoring in all RoR IDEs. Give it a try and see for your self.</p>\n"}, {'answer_id': 20450805, 'author': 'Severin', 'author_id': 1213273, 'author_profile': 'https://Stackoverflow.com/users/1213273', 'pm_score': 0, 'selected': False, 'text': '<p>You could always give RubyMine a try. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12019/'] |
72,895 | <p>I have been researching asynchronous messaging, and I like the way it elegantly deals with some problems within certain domains and how it makes domain concepts more explicit. But is it a viable pattern for general domain-driven development (at least in the service/application/controller layer), or is the design overhead such that it should be restricted to SOA-based scenarios, like remote services and distributed processing? </p>
| [{'answer_id': 73944, 'author': 'James Strachan', 'author_id': 2068211, 'author_profile': 'https://Stackoverflow.com/users/2068211', 'pm_score': 4, 'selected': True, 'text': '<p>Great question :). The main problem with asynchronous messaging is that when folks use procedural or object oriented languages, working in an asynchronous or event based manner is often quite tricky and complex and hard for the programmer to read & understand. Business logic is often way simpler if its built in a kinda synchronous manner - invoking methods and getting results immediately etc :).</p>\n\n<p>My rule of thumb is generally to try use simpler synchronous programming models at the micro level for business logic; then use asynchrony and SEDA at the macro level. </p>\n\n<p>For example submitting a purchase order might just write a message to a message queue; but the processing of the purchase order might require 10 different steps all being asynchronous and parallel in a high performance distributed system with many concurrent processes & threads processing individual steps in parallel. So the macro level wiring is based on a SEDA kind of approach - but at the micro level the code for the individual 10 steps could be written mostly in a synchronous programming style.</p>\n'}, {'answer_id': 74065, 'author': 'BradS', 'author_id': 10537, 'author_profile': 'https://Stackoverflow.com/users/10537', 'pm_score': 2, 'selected': False, 'text': '<p>Like so many architecture and design questions, the answer is "it depends".</p>\n\n<p>In my experience, the strength of asynchronous messaging has been in the loose coupling it brings to a design. The coupling can be in:</p>\n\n<ul>\n<li>Time - Requests can be handled asynchronously, helping overall scalability.</li>\n<li>Space - As you point out, allowing for distributed processing in a more robust way than many synchronous designs.</li>\n<li>Technology - Messages and queues are one way to bridge technology differences.</li>\n</ul>\n\n<p>Remember that messages and queues are an abstraction that can have a variety of implementations. You don\'t necessarily need to use a JMS-compliant, transactional, high-performance messaging framework. Implemented correctly, a table in a relational database can act as a queue with the rows as messages. I\'ve seen both approaches used to great effect.</p>\n'}, {'answer_id': 75211, 'author': 'James Strachan', 'author_id': 2068211, 'author_profile': 'https://Stackoverflow.com/users/2068211', 'pm_score': 1, 'selected': False, 'text': '<p>I agree with @BradS too BTW</p>\n\n<p>BTW <a href="http://activemq.apache.org/camel/hiding-middleware.html" rel="nofollow noreferrer">here\'s a way of hiding the middleware from your business logic</a> while still getting the benefits of loose coupling & SEDA - while being able to easily switch between a variety of different middleware technology - from in memory SEDA to JMS to AMQP to JavaSpaces to database, files or FTP etc</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12356/'] |
72,899 | <p>How do I sort a list of dictionaries by a specific key's value? Given:</p>
<pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
</code></pre>
<p>When sorted by <code>name</code>, it should become:</p>
<pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
</code></pre>
| [{'answer_id': 72950, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 5, 'selected': False, 'text': '<p>You have to implement your own comparison function that will compare the dictionaries by values of name keys. See <a href="http://wiki.python.org/moin/HowTo/Sorting" rel="noreferrer">Sorting Mini-HOW TO from PythonInfo Wiki</a></p>\n'}, {'answer_id': 73019, 'author': 'Bartosz Radaczyński', 'author_id': 985, 'author_profile': 'https://Stackoverflow.com/users/985', 'pm_score': 5, 'selected': False, 'text': "<p>I guess you've meant:</p>\n\n<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n</code></pre>\n\n<p>This would be sorted like this:</p>\n\n<pre><code>sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))\n</code></pre>\n"}, {'answer_id': 73044, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 7, 'selected': False, 'text': "<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n\nmy_list.sort(lambda x,y : cmp(x['name'], y['name']))\n</code></pre>\n<p><code>my_list</code> will now be what you want.</p>\n<p>Or better:</p>\n<p>Since Python 2.4, there's a <code>key</code> argument is both more efficient and neater:</p>\n<pre><code>my_list = sorted(my_list, key=lambda k: k['name'])\n</code></pre>\n<p>...the lambda is, IMO, easier to understand than <code>operator.itemgetter</code>, but your mileage may vary.</p>\n"}, {'answer_id': 73050, 'author': 'Mario F', 'author_id': 3785, 'author_profile': 'https://Stackoverflow.com/users/3785', 'pm_score': 13, 'selected': True, 'text': '<p>The <a href="https://docs.python.org/library/functions.html#sorted" rel="noreferrer"><code>sorted()</code></a> function takes a <code>key=</code> parameter</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=lambda d: d[\'name\']) \n</code></pre>\n<p>Alternatively, you can use <a href="https://docs.python.org/library/operator.html#operator.itemgetter" rel="noreferrer"><code>operator.itemgetter</code></a> instead of defining the function yourself</p>\n<pre><code>from operator import itemgetter\nnewlist = sorted(list_to_be_sorted, key=itemgetter(\'name\')) \n</code></pre>\n<p>For completeness, add <code>reverse=True</code> to sort in descending order</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=itemgetter(\'name\'), reverse=True)\n</code></pre>\n'}, {'answer_id': 73098, 'author': 'efotinis', 'author_id': 12320, 'author_profile': 'https://Stackoverflow.com/users/12320', 'pm_score': 5, 'selected': False, 'text': "<pre><code>import operator\na_list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.</p>\n"}, {'answer_id': 73186, 'author': 'Owen', 'author_id': 12592, 'author_profile': 'https://Stackoverflow.com/users/12592', 'pm_score': 5, 'selected': False, 'text': "<p>You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.</p>\n\n<p>You could do it this way:</p>\n\n<pre><code>def mykey(adict): return adict['name']\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=mykey)\n</code></pre>\n\n<p>But the standard library contains a generic routine for getting items of arbitrary objects: <code>itemgetter</code>. So try this instead:</p>\n\n<pre><code>from operator import itemgetter\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=itemgetter('name'))\n</code></pre>\n"}, {'answer_id': 73465, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': False, 'text': "<pre><code>import operator\n</code></pre>\n\n<p>To sort the list of dictionaries by key='name':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>To sort the list of dictionaries by key='age':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('age'))\n</code></pre>\n"}, {'answer_id': 2858683, 'author': 'Dologan', 'author_id': 222135, 'author_profile': 'https://Stackoverflow.com/users/222135', 'pm_score': 6, 'selected': False, 'text': "<p>If you want to sort the list by multiple keys, you can do the following:</p>\n<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]\nsortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))\n</code></pre>\n<p>It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).</p>\n"}, {'answer_id': 16772049, 'author': 'kiriloff', 'author_id': 1141493, 'author_profile': 'https://Stackoverflow.com/users/1141493', 'pm_score': 5, 'selected': False, 'text': '<p>Using the <a href="https://en.wikipedia.org/wiki/Schwartzian_transform" rel="noreferrer">Schwartzian transform</a> from Perl,</p>\n<pre><code>py = [{\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}]\n</code></pre>\n<p>do</p>\n<pre><code>sort_on = "name"\ndecorated = [(dict_[sort_on], dict_) for dict_ in py]\ndecorated.sort()\nresult = [dict_ for (key, dict_) in decorated]\n</code></pre>\n<p>gives</p>\n<pre><code>>>> result\n[{\'age\': 10, \'name\': \'Bart\'}, {\'age\': 39, \'name\': \'Homer\'}]\n</code></pre>\n<p>More on the Perl Schwartzian transform:</p>\n<blockquote>\n<p>In computer science, the Schwartzian transform is a Perl programming\nidiom used to improve the efficiency of sorting a list of items. This\nidiom is appropriate for comparison-based sorting when the ordering is\nactually based on the ordering of a certain property (the key) of the\nelements, where computing that property is an intensive operation that\nshould be performed a minimal number of times. The Schwartzian\nTransform is notable in that it does not use named temporary arrays.</p>\n</blockquote>\n'}, {'answer_id': 23102554, 'author': 'Shank_Transformer', 'author_id': 2819862, 'author_profile': 'https://Stackoverflow.com/users/2819862', 'pm_score': 4, 'selected': False, 'text': '<p>Let\'s say I have a dictionary <code>D</code> with the elements below. To sort, just use the key argument in <code>sorted</code> to pass a custom function as below:</p>\n<pre><code>D = {\'eggs\': 3, \'ham\': 1, \'spam\': 2}\ndef get_count(tuple):\n return tuple[1]\n\nsorted(D.items(), key = get_count, reverse=True)\n# Or\nsorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call\n</code></pre>\n<p>Check <a href="https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions" rel="nofollow noreferrer">this</a> out.</p>\n'}, {'answer_id': 28094888, 'author': 'vvladymyrov', 'author_id': 1296661, 'author_profile': 'https://Stackoverflow.com/users/1296661', 'pm_score': 4, 'selected': False, 'text': '<p>Here is the alternative general solution - it sorts elements of a dict by keys and values.</p>\n<p>The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.</p>\n<pre><code>def sort_key_func(item):\n """ Helper function used to sort list of dicts\n\n :param item: dict\n :return: sorted list of tuples (k, v)\n """\n pairs = []\n for k, v in item.items():\n pairs.append((k, v))\n return sorted(pairs)\nsorted(A, key=sort_key_func)\n</code></pre>\n'}, {'answer_id': 39281050, 'author': 'abby sobh', 'author_id': 3135363, 'author_profile': 'https://Stackoverflow.com/users/3135363', 'pm_score': 4, 'selected': False, 'text': '<p>Using the <a href="https://en.wikipedia.org/wiki/Pandas_%28software%29" rel="noreferrer">Pandas</a> package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:</p>\n<pre><code>import pandas as pd\n\nlistOfDicts = [{\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}]\ndf = pd.DataFrame(listOfDicts)\ndf = df.sort_values(\'name\')\nsorted_listOfDicts = df.T.to_dict().values()\n</code></pre>\n<p>Here are some benchmark values for a tiny list and a large (100k+) list of dicts:</p>\n<pre><code>setup_large = "listOfDicts = [];\\\n[listOfDicts.extend(({\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10})) for _ in range(50000)];\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);"\n\nsetup_small = "listOfDicts = [];\\\nlistOfDicts.extend(({\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}));\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);"\n\nmethod1 = "newlist = sorted(listOfDicts, key=lambda k: k[\'name\'])"\nmethod2 = "newlist = sorted(listOfDicts, key=itemgetter(\'name\')) "\nmethod3 = "df = df.sort_values(\'name\');\\\nsorted_listOfDicts = df.T.to_dict().values()"\n\nimport timeit\nt = timeit.Timer(method1, setup_small)\nprint(\'Small Method LC: \' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_small)\nprint(\'Small Method LC2: \' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_small)\nprint(\'Small Method Pandas: \' + str(t.timeit(100)))\n\nt = timeit.Timer(method1, setup_large)\nprint(\'Large Method LC: \' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_large)\nprint(\'Large Method LC2: \' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_large)\nprint(\'Large Method Pandas: \' + str(t.timeit(1)))\n\n#Small Method LC: 0.000163078308105\n#Small Method LC2: 0.000134944915771\n#Small Method Pandas: 0.0712950229645\n#Large Method LC: 0.0321750640869\n#Large Method LC2: 0.0206089019775\n#Large Method Pandas: 5.81405615807\n</code></pre>\n'}, {'answer_id': 42855105, 'author': 'forzagreen', 'author_id': 3495031, 'author_profile': 'https://Stackoverflow.com/users/3495031', 'pm_score': 6, 'selected': False, 'text': "<pre><code>a = [{'name':'Homer', 'age':39}, ...]\n\n# This changes the list a\na.sort(key=lambda k : k['name'])\n\n# This returns a new list (a is not modified)\nsorted(a, key=lambda k : k['name']) \n</code></pre>\n"}, {'answer_id': 45094029, 'author': 'uingtea', 'author_id': 4082344, 'author_profile': 'https://Stackoverflow.com/users/4082344', 'pm_score': 4, 'selected': False, 'text': "<p>Sometimes we need to use <code>lower()</code>. For example,</p>\n<pre><code>lists = [{'name':'Homer', 'age':39},\n {'name':'Bart', 'age':10},\n {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'])\nprint(lists)\n# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'].lower())\nprint(lists)\n# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]\n</code></pre>\n"}, {'answer_id': 47892332, 'author': 'srikavineehari', 'author_id': 8709791, 'author_profile': 'https://Stackoverflow.com/users/8709791', 'pm_score': 4, 'selected': False, 'text': '<p>If you do not need the original <code>list</code> of <code>dictionaries</code>, you could modify it in-place with <code>sort()</code> method using a custom key function.</p>\n\n<p>Key function:</p>\n\n<pre><code>def get_name(d):\n """ Return the value of a key in a dictionary. """\n\n return d["name"]\n</code></pre>\n\n<p>The <code>list</code> to be sorted:</p>\n\n<pre><code>data_one = [{\'name\': \'Homer\', \'age\': 39}, {\'name\': \'Bart\', \'age\': 10}]\n</code></pre>\n\n<p>Sorting it in-place:</p>\n\n<pre><code>data_one.sort(key=get_name)\n</code></pre>\n\n<p>If you need the original <code>list</code>, call the <code>sorted()</code> function passing it the <code>list</code> and the key function, then assign the returned sorted <code>list</code> to a new variable:</p>\n\n<pre><code>data_two = [{\'name\': \'Homer\', \'age\': 39}, {\'name\': \'Bart\', \'age\': 10}]\nnew_data = sorted(data_two, key=get_name)\n</code></pre>\n\n<p>Printing <code>data_one</code> and <code>new_data</code>.</p>\n\n<pre><code>>>> print(data_one)\n[{\'name\': \'Bart\', \'age\': 10}, {\'name\': \'Homer\', \'age\': 39}]\n>>> print(new_data)\n[{\'name\': \'Bart\', \'age\': 10}, {\'name\': \'Homer\', \'age\': 39}]\n</code></pre>\n'}, {'answer_id': 58179903, 'author': 'Bejür', 'author_id': 7933218, 'author_profile': 'https://Stackoverflow.com/users/7933218', 'pm_score': 4, 'selected': False, 'text': "<p>I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.</p>\n<h3>First option</h3>\n<pre><code>sorted_list = sorted(list_to_sort, key= lambda x: x['name'])\n# Returns list of values\n</code></pre>\n<h3>Second option</h3>\n<pre><code>list_to_sort.sort(key=operator.itemgetter('name'))\n# Edits the list, and does not return a new list\n</code></pre>\n<h3>Fast comparison of execution times</h3>\n<pre><code># First option\npython3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" "sorted_l = sorted(list_to_sort, key=lambda e: e['name'])"\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.736 µsec per loop</p>\n</blockquote>\n<pre><code># Second option\npython3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" -s "import operator" "list_to_sort.sort(key=operator.itemgetter('name'))"\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.438 µsec per loop</p>\n</blockquote>\n"}, {'answer_id': 59802559, 'author': 'swac', 'author_id': 10452855, 'author_profile': 'https://Stackoverflow.com/users/10452855', 'pm_score': 3, 'selected': False, 'text': '<p>If performance is a concern, I would use <code>operator.itemgetter</code> instead of <code>lambda</code> as built-in functions perform faster than hand-crafted functions. The <code>itemgetter</code> function seems to perform approximately 20% faster than <code>lambda</code> based on my testing.</p>\n<p>From <a href="https://wiki.python.org/moin/PythonSpeed" rel="noreferrer">https://wiki.python.org/moin/PythonSpeed</a>:</p>\n<blockquote>\n<p>Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).</p>\n</blockquote>\n<p>Here is a comparison of sorting speed using <code>lambda</code> vs <code>itemgetter</code>.</p>\n<pre><code>import random\nimport operator\n\n# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.\nl = [{\'name\': \'\'.join(random.choices(string.ascii_lowercase, k=8)), \'age\': random.randint(0, 100)} for i in range(100)]\n\n# Test the performance with a lambda function sorting on name\n%timeit sorted(l, key=lambda x: x[\'name\'])\n13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Test the performance with itemgetter sorting on name\n%timeit sorted(l, key=operator.itemgetter(\'name\'))\n10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Check that each technique produces the same sort order\nsorted(l, key=lambda x: x[\'name\']) == sorted(l, key=operator.itemgetter(\'name\'))\nTrue\n</code></pre>\n<p>Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.</p>\n'}, {'answer_id': 69072597, 'author': 'Tms91', 'author_id': 7658051, 'author_profile': 'https://Stackoverflow.com/users/7658051', 'pm_score': 1, 'selected': False, 'text': '<p>As indicated by @Claudiu to @monojohnny in comment section of <a href="https://stackoverflow.com/a/73465/7658051">this answer</a>,<br> given:</p>\n<pre><code>list_to_be_sorted = [\n {\'name\':\'Homer\', \'age\':39}, \n {\'name\':\'Milhouse\', \'age\':10}, \n {\'name\':\'Bart\', \'age\':10} \n ]\n</code></pre>\n<p>to sort the list of dictionaries by key <code>\'age\'</code>, <code>\'name\'</code>\n<br>(like in SQL statement <code>ORDER BY age, name</code>), you can use:</p>\n<pre><code>newlist = sorted( list_to_be_sorted, key=lambda k: (k[\'age\'], k[\'name\']) )\n</code></pre>\n<p>or, likewise</p>\n<pre><code>import operator\nnewlist = sorted( list_to_be_sorted, key=operator.itemgetter(\'age\',\'name\') )\n</code></pre>\n<p><code>print(newlist)</code></p>\n<blockquote>\n<p>[{\'name\': \'Bart\', \'age\': 10},<br> {\'name\': \'Milhouse\', \'age\': 10},<br>\n{\'name\': \'Homer\', \'age\': 39}]</p>\n</blockquote>\n'}, {'answer_id': 72939809, 'author': 'alex', 'author_id': 4444742, 'author_profile': 'https://Stackoverflow.com/users/4444742', 'pm_score': 0, 'selected': False, 'text': "<p>sorting by multiple columns, while in descending order on some of them:\nthe cmps array is global to the cmp function, containing field names and inv == -1 for desc 1 for asc</p>\n<pre><code>def cmpfun(a, b):\n for (name, inv) in cmps:\n res = cmp(a[name], b[name])\n if res != 0:\n return res * inv\n return 0\n\ndata = [\n dict(name='alice', age=10), \n dict(name='baruch', age=9), \n dict(name='alice', age=11),\n]\n\nall_cmps = [\n [('name', 1), ('age', -1)], \n [('name', 1), ('age', 1)], \n [('name', -1), ('age', 1)],]\n\nprint 'data:', data\nfor cmps in all_cmps: print 'sort:', cmps; print sorted(data, cmpfun)\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12398/'] |
72,913 | <p>If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?</p>
| [{'answer_id': 72963, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 1, 'selected': False, 'text': '<p>A Lambda expression can contain complex statements, so you can do the following:</p>\n\n<pre><code>Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };\n</code></pre>\n'}, {'answer_id': 73007, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': True, 'text': '<pre><code>e => e.MoveNext() ? e.Current : null\n</code></pre>\n\n<p>This will advance the enumerator and return the current value, and return null when the enumeration is complete.</p>\n'}, {'answer_id': 73041, 'author': 'fryguybob', 'author_id': 4592, 'author_profile': 'https://Stackoverflow.com/users/4592', 'pm_score': 0, 'selected': False, 'text': '<p>Is this what you are looking for?</p>\n\n<pre><code>List<string> strings = new List<string>()\n{\n "Hello", "I", "am", "a", "list", "of", "strings."\n};\nIEnumerator<string> e = strings.GetEnumerator();\nFunc<string> f = () => e.MoveNext() ? e.Current : null;\nfor (; ; )\n{\n string str = f();\n if (str == null)\n break;\n\n Console.Write(str + " ");\n}\n</code></pre>\n\n<p>The point of an <code>IEnumerator</code> is that you already get syntactic sugar to deal with it:</p>\n\n<pre><code>foreach (string str in strings)\n Console.Write(str + " ");\n</code></pre>\n\n<p>Even handling the enumerator directly looks cleaner in this case:</p>\n\n<pre><code>while (e.MoveNext())\n Console.Write(e.Current + " ");\n</code></pre>\n'}, {'answer_id': 73058, 'author': 'Nathan Baulch', 'author_id': 8799, 'author_profile': 'https://Stackoverflow.com/users/8799', 'pm_score': 0, 'selected': False, 'text': '<p>Extending on Abe\'s solution, you can also use closures to hold a reference to the enumerator:</p>\n\n<pre><code>var iter = ((IEnumerable<char>)"hello").GetEnumerator();\n\n//with closure\n{\n Func<object> f =\n () =>\n {\n iter.MoveNext();\n return iter.Current;\n };\n Console.WriteLine(f());\n Console.WriteLine(f());\n}\n\n//without closure\n{\n Func<IEnumerator, object> f =\n ie =>\n {\n ie.MoveNext();\n return ie.Current;\n };\n Console.WriteLine(f(iter));\n Console.WriteLine(f(iter));\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/'] |
72,921 | <p>I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.</p>
<p>I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. <a href="https://stackoverflow.com/users/4465/levik">Internet Duct Tape's Greasemonkey tools, like Comment Ninja</a>, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.</p>
<p>I just want to be able to select a bunch of text on the comments page and click a bookmarklet (<a href="https://stackoverflow.com/users/8119/jacob">http://bookmarklets.com</a>) in Firefox that pops up a window listing all the IP addresses found in the selection.</p>
<p><strong>Update:</strong></p>
<p>I kind of combined a the answers from <a href="https://stackoverflow.com/users/4465/levik">levik</a> and <a href="https://stackoverflow.com/users/8119/jacob">Jacob</a> to come up with this:</p>
<pre><code>javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
</code></pre>
<p>The difference is that instead of an <em>alert</em> message, as in levik's answer, I open a new window similar to Jacob's answer. The <em>alert</em> doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a <em><br></em> for the join instead of levik's <em>\n</em>. </p>
<p>Thanks for all the help, guys.</p>
| [{'answer_id': 72981, 'author': 'Dr. Bob', 'author_id': 12182, 'author_profile': 'https://Stackoverflow.com/users/12182', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://javascript.about.com/library/blip.htm" rel="nofollow noreferrer">Here</a> is a good article on obtaining the IP address of your visitors. You could display this in addition to their comment if you wanted or include it as a label or field in your page so you can reference it later.</p>\n'}, {'answer_id': 73031, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 1, 'selected': False, 'text': '<p>Use a regular expression to detect the IP address. A couple examples:</p>\n\n<pre><code>/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/\n/^([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+$/\n</code></pre>\n'}, {'answer_id': 73723, 'author': 'levik', 'author_id': 4465, 'author_profile': 'https://Stackoverflow.com/users/4465', 'pm_score': 3, 'selected': True, 'text': '<p>In Firefox, you could do something like this:</p>\n\n<pre><code>javascript:alert(\n document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g)\n .join("\\n"))\n</code></pre>\n\n<p>How this works:</p>\n\n<ul>\n<li>Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text")</li>\n<li>Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.</li>\n<li>Joins this array into one string separated by return characters</li>\n<li>Alerts that string</li>\n</ul>\n\n<p>The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you\'d need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).</p>\n'}, {'answer_id': 74377, 'author': 'Jacob', 'author_id': 8119, 'author_profile': 'https://Stackoverflow.com/users/8119', 'pm_score': 1, 'selected': False, 'text': "<h2>As a bookmarklet</h2>\n<pre><code>javascript:document.write(document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g))\n</code></pre>\n<p>Just create a new bookmark and paste that javascript in</p>\n<h2>How to do it in Ubiquity</h2>\n<pre><code>CmdUtils.CreateCommand({\n name: "findip",\n preview: function( pblock ) {\n var msg = 'IP Addresses Found<br/><br/> ';\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n msg += ips.join("<br/>\\n");\n }else{\n msg += 'None';\n }\n pblock.innerHTML = msg;\n },\n\n execute: function() {\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n CmdUtils.setSelection(ips.join("<br/>\\n"));\n }\n }\n})\n</code></pre>\n"}, {'answer_id': 74387, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at the <a href="https://www.squarefree.com/bookmarklets/pagedata.html#rot13_selection" rel="nofollow noreferrer" title="rot13 bookmarklet">rot13 bookmarklet</a> for an example of selecting text and performing an action (in this case substitution) when the bookmarklet is clicked.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12419/'] |
72,931 | <p>C++ just sucks too much of my time by making me micro-manage my own memory, making me type far too much (hello <code>std::vector<Thingy>::const_iterator it = lotsOfThingys.begin()</code>), and boring me with long compile times. What's the single best alternative for serious real-time graphics programming? Garbage collection is a must (as is the ability to avoid its use when necessary), and speed must be competitive with C++. A reasonable story for accessing C libs is also a must.</p>
<p>(Full disclosure: I have my own answer to this, but I'm interested to see what others have found to be good alternatives to C++ for real-time graphics work.)</p>
<p><strong>Edit:</strong> Thanks everyone for the thoughtful replies. Given that there's really no "right" answer to this question I won't be selecting any particular answer. Besides I'd just pick the language I happen to like as a C++ alternative, which wouldn't really be fair.</p>
| [{'answer_id': 72959, 'author': 'Drealmer', 'author_id': 12291, 'author_profile': 'https://Stackoverflow.com/users/12291', 'pm_score': 4, 'selected': False, 'text': '<p>C# is a nice language that fits your requirements, and it is definitely suited for graphics, thanks to the efforts of Microsoft to provide it with great tools and libraries like Visual Studio and XNA.</p>\n'}, {'answer_id': 72986, 'author': 'scable', 'author_id': 8942, 'author_profile': 'https://Stackoverflow.com/users/8942', 'pm_score': 4, 'selected': False, 'text': '<p>What about <a href="http://www.digitalmars.com/d/2.0/comparison.html" rel="noreferrer">D Programming Language</a>?</p>\n\n<p>Some links requested in the comment:</p>\n\n<p><a href="http://www.digitalmars.com/d/2.0/windows.html" rel="noreferrer">Win32 Api</a></p>\n\n<p><a href="http://www.dsource.org/projects/derelict/" rel="noreferrer">Derelict (Multimedia lib)</a></p>\n'}, {'answer_id': 73244, 'author': 'yrp', 'author_id': 7228, 'author_profile': 'https://Stackoverflow.com/users/7228', 'pm_score': 2, 'selected': False, 'text': '<p>There are no true alternatives for big AAA titles, especially on the consoles. For smaller titles C# should do.</p>\n'}, {'answer_id': 73247, 'author': 'Pieter', 'author_id': 5822, 'author_profile': 'https://Stackoverflow.com/users/5822', 'pm_score': 4, 'selected': False, 'text': "<p>Real-time + garbage collection don't match very well I'm afraid.</p>\n\n<p>It's a bit hard to make any real-time response guarantees if a garbage collector can kick in at any time and spend an undefined amount of processing...</p>\n"}, {'answer_id': 73430, 'author': 'James Hopkin', 'author_id': 11828, 'author_profile': 'https://Stackoverflow.com/users/11828', 'pm_score': 4, 'selected': False, 'text': '<p>Perhaps a hybrid approach. Python and C++ make a good combination (see, for example, PyGame).</p>\n'}, {'answer_id': 73642, 'author': 'Adi', 'author_id': 9090, 'author_profile': 'https://Stackoverflow.com/users/9090', 'pm_score': 2, 'selected': False, 'text': "<p>C# is a good answer here - it has a fair garbage collection (although you'd have to profile it quite a bit - to change the way you handle things now that the entire memory handling is out of your hands), it is simple to use, have a lot of examples and is well documented.\nIn the 3D department it gives full support for shaders and effects and so - that would be my choice.</p>\n\n<p>Still, C# is not as efficient as C++ and is slower due to overhead, so if it is speed and the flexibility to use any trick in the book you like (with pointers and assembly if you like to get your hands dirty) - stick to C++ and the price would be writing way more code as you mentioned, but having full control over everything including memory management.</p>\n"}, {'answer_id': 73704, 'author': 'Johan Moreau', 'author_id': 12033, 'author_profile': 'https://Stackoverflow.com/users/12033', 'pm_score': 2, 'selected': False, 'text': "<p>Like James (hopkin), for me, the hybrid approach is the best solution. Python and C++ is a good choice, but other style like C#/C++ works. All depends of your graphical context. For game, XNA is a good platform (limited to win32), in this case C#/C++ is the best solution. For scientific visualization, Python/C++ is accepted (like vtk's bindings in python). For mobile game JAVA/C++ can works...</p>\n"}, {'answer_id': 73935, 'author': 'DevilDog', 'author_id': 323425, 'author_profile': 'https://Stackoverflow.com/users/323425', 'pm_score': 3, 'selected': False, 'text': '<p>Sometimes, looking outside the beaten path you can find a real gem. You might want to consider <a href="http://www.purebasic.com" rel="nofollow noreferrer">PureBasic</a> (Don\'t let the name mislead you). Here\'s some details:</p>\n\n<p>PureBasic Features </p>\n\n<ul>\n<li>Machine Code (Assembly) executables (FASM)\n\n<ul>\n<li>In-line Assembly support </li>\n<li>No run-times needed (no DLLs needed,etc.) 1 executable file </li>\n<li>Tiny executables (as small or smaller/as fast or faster than C++ w/out the runtime) </li>\n<li>You can write DLLs </li>\n<li>Multi-thread support </li>\n<li>Full OS API support </li>\n</ul></li>\n<li>Multi-platform support \n\n<ul>\n<li>Windows 95-2003</li>\n<li>Linux</li>\n<li>Mac-OS X</li>\n<li>Amiga </li>\n</ul></li>\n<li>2D & 3D game development \n\n<ul>\n<li>DirectX </li>\n<li>OGRE </li>\n</ul></li>\n<li>Generous Licensing \n\n<ul>\n<li>Inexpensive (79 Euros or about $112) </li>\n<li>Life-time license (all future updates & versions included) </li>\n<li>One price for all platforms </li>\n</ul></li>\n<li>External Library support \n\n<ul>\n<li>3rd party DLLs </li>\n<li>User Libraries </li>\n</ul></li>\n<li>On-line Support \n\n<ul>\n<li>Responsive development team led by it\'s creator</li>\n<li><a href="http://www.purebasic.fr/english/index.php" rel="nofollow noreferrer">On-line forum</a>\n\n<ul>\n<li>One place for answers (don’t have to go all over the net) </li>\n<li>Huge amount of sample code (try code out while in IE with IEtool) </li>\n<li>Fast replies to questions </li>\n</ul></li>\n</ul></li>\n<li>Bonus learning (alternative to learning C++) \n\n<ul>\n<li>API </li>\n<li>Structures </li>\n<li>Interfaces </li>\n<li>Pointers</li>\n</ul></li>\n</ul>\n\n<p>Visit the online forum to get a better idea of PureBasic (<a href="http://www.purebasic.fr/english/index.php" rel="nofollow noreferrer">http://www.purebasic.fr/english/index.php</a>) or the main site: <a href="http://www.purebasic.com" rel="nofollow noreferrer">www.purebasic.com</a></p>\n'}, {'answer_id': 74401, 'author': 'R Caloca', 'author_id': 13004, 'author_profile': 'https://Stackoverflow.com/users/13004', 'pm_score': 0, 'selected': False, 'text': "<p>If your target is a PC, I think you can try C#, or embed <strong>Lua</strong> in your C++ app and run scripts for 'high-level' stuff. However if your target is a console, you <strong>must</strong> manage your own memory!</p>\n"}, {'answer_id': 74566, 'author': 'Nathan', 'author_id': 3623, 'author_profile': 'https://Stackoverflow.com/users/3623', 'pm_score': 4, 'selected': False, 'text': '<p>Some variation of Lisp that compiles to machine code could be almost as fast as C++ for this kind of programming. The <a href="http://www.naughtydog.com/" rel="noreferrer">Naughty Dog</a> team created a version of Lisp called <a href="http://en.wikipedia.org/wiki/Game_Oriented_Assembly_Lisp" rel="noreferrer">Game Oriented Assembly Lisp</a>, which they used to create several AAA titles, including the Jak and Daxter series. The two major impediments to a Lisp approach in the game industry would be the entrenched nature of C/C++ development (both tools and human assets are heavily invested in C/C++), as well as the difficulty of finding talented engineers who are stars in both the game programming domain and the Lisp language.</p>\n\n<p>Many programming teams in the industry are shifting to a hybrid approach wherein the real-time code, especially graphics and physics code, is written in C or C++, but game logic is done in a higher-level scripting language, which is accessible to and editable by programmers and non-programmers alike. <a href="http://www.lua.org/" rel="noreferrer">Lua</a> and <a href="http://www.python.org/" rel="noreferrer">Python</a> are both popular for higher-level scripting.</p>\n'}, {'answer_id': 74745, 'author': 'Nemanja Trifunovic', 'author_id': 8899, 'author_profile': 'https://Stackoverflow.com/users/8899', 'pm_score': 0, 'selected': False, 'text': '<p>Objective-C looks like a good match for your requirements (the latest version with optional GC), although it is too dynamic and Smalltalk-like for my taste.</p>\n'}, {'answer_id': 74750, 'author': 'Game_Overture', 'author_id': 13115, 'author_profile': 'https://Stackoverflow.com/users/13115', 'pm_score': 0, 'selected': False, 'text': '<p>XNA is your best bet I think. Being supported by the .NET framework you can build for a Windows or Xbox 360 platform by simply changing a setting in Game Studio. Best yet, all the tools are free!</p>\n\n<p>If you decide to go with XNA you can easily get started using their quickstart guide\n<a href="http://creators.xna.com/en-US/quickstart_main" rel="nofollow noreferrer">XNA Quickstart guide</a></p>\n\n<p>It has been a rewarding and fun experiance for me so far, and a nice break from the memory management of C++.</p>\n'}, {'answer_id': 75555, 'author': 'Dima', 'author_id': 13313, 'author_profile': 'https://Stackoverflow.com/users/13313', 'pm_score': 4, 'selected': False, 'text': '<p>I disagree with your premise. When used carefully and properly, C++ is a great language, especially for a domain like real-time graphics, where speed is of the essence.</p>\n\n<p>Memory management becomes easy if you design your system well, and use stl containers and smart pointers.</p>\n\n<p><code>std::vector::const_iterator it = lotsOfThingys.begin())</code> will become much shorter if you use</p>\n\n<p><code>\nusing namespace std;<br>\ntypedef vector::const_iterator ThingyConstIter;\n</code></p>\n\n<p>And you can shorten compile times significantly by breaking up your systems into reasonably self-contained modules, by using precompiled headers, or by using the PIMPL idiom.</p>\n'}, {'answer_id': 75756, 'author': 'Markowitch', 'author_id': 11964, 'author_profile': 'https://Stackoverflow.com/users/11964', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>Garbage collection is a must (as is\n the ability to avoid its use when\n necessary)</p>\n</blockquote>\n\n<p>You can't disable a garbage collector temporarily. You would need a deterministic garbage collector then. But such a beast does come with a performance hit also. I think BEA JRockit is such a beast and then you should stick to Java.</p>\n\n<p>Just to comment on your example; typedef is your friend...</p>\n\n<pre><code>typedef std::vector<Thingy> Thingys;\nThingys::const_iterator it = lotsOfThingys.begin()\n</code></pre>\n"}, {'answer_id': 75804, 'author': 'komma8.komma1', 'author_id': 13355, 'author_profile': 'https://Stackoverflow.com/users/13355', 'pm_score': 2, 'selected': False, 'text': "<p>I would say the D programming language is a good option. You can link to C object files and interface with C++ code through C libraries. D has garbage collection, inline assembly, and game developers have created bindings to SDL and OpenGL libraries, and are also actively working on new game development apis. I love D. Too bad my job doesn't demand it's use. :(</p>\n"}, {'answer_id': 75838, 'author': 'Martin Cote', 'author_id': 9936, 'author_profile': 'https://Stackoverflow.com/users/9936', 'pm_score': 4, 'selected': False, 'text': "<p>I wouldn't discard C++. In fact, I would consider adding Boost to your C++ library, which makes the language much more usable. Your example would become:</p>\n\n<pre><code>BOOST_FOREACH( Thingy& t, lostOfThingys ) {\n // do something with 't'\n}\n</code></pre>\n\n<p>Boost has tons of tools that help make C++ a better language.</p>\n"}, {'answer_id': 76040, 'author': 'mittens', 'author_id': 10188, 'author_profile': 'https://Stackoverflow.com/users/10188', 'pm_score': 3, 'selected': False, 'text': '<p>I completely agree with the mention of C# for graphics programming. It has the slight disadvantage of being a managed language and allowing the garbage collector free reign over your application is framerate suicide after a while but with some relatively intelligent pool allocations made early in the program\'s life any real issues can be avoided.</p>\n\n<p>Several people have already mentioned XNA, which is incredibly friendly and well-documented and I would like to echo that recommendation as well. I\'m personally using it for my hobby game projects and it has treated me very well.</p>\n\n<p>XNA isn\'t the only alternative, though. There is also SlimDX which is under constant development as a means of providing a lean wrapper of DirectX in a similar fashion as Managed DirectX (which was, I believe, discontinued by Microsoft in favor of XNA). Both are worthy of research: <a href="http://code.google.com/p/slimdx/" rel="nofollow noreferrer">http://code.google.com/p/slimdx/</a></p>\n'}, {'answer_id': 76156, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 2, 'selected': False, 'text': '<p>If you are targeting Windows, C++/CLI (Microsoft\'s .NET \'managed\' dialect of C++) is an interesting possibility, particularly if you want to leverage your C++ experience. You can mix native code (e.g. calls to C-style libraries) with .NET managed code quite seamlessly, and take advantage of .NET GC and libraries.</p>\n\n<p>As far as concerns about GC impacting \'real time\' performance, I think those tend to be overblown. The multi-generational .NET GC is very good at never taking much time to do a collection, unless you are in some kind of critical low-memory situation. I write .NET code that interacts with electronic derivatives exchanges, where time delays == lots of $$$, and we have never had a GC-related issue. A few milliseconds is a long, long time for the GC, but not for a human interacting with a piece of software, even a \'real time\' game. If you really need true "real time" performance (for medical devices, process control, etc.) then you can\'t use Windows anyway - it\'s just not a real-time OS.</p>\n'}, {'answer_id': 81496, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 4, 'selected': False, 'text': "<p>Let's not forget to mention the new 'auto' use:</p>\n\n<pre><code>auto it = lotsOfThingys.begin(); // Let the compiler figure it out.\nauto it2 = lotsOfFoos.begin();\nif (it==it2) // It's still strongly typed; a Thingy iter is not a Foo iter.\n</code></pre>\n"}, {'answer_id': 125586, 'author': 'PhiLho', 'author_id': 15459, 'author_profile': 'https://Stackoverflow.com/users/15459', 'pm_score': 2, 'selected': False, 'text': '<p>Lot of game engines can fit your need, I suppose. For example, using SDL or Cairo, if portability is needed. Lot of scripting languages (coming in general with easy syntax and garbage collection) have binding to these canvas.<br>\nFlash might be another alternative.</p>\n\n<p>I will just point out <a href="http://processing.org/" rel="nofollow noreferrer" title="Processing">Processing</a>, which is <em>an open source programming language and environment for people who want to program images, animation, and interactions.</em></p>\n\n<p>Actually, it is a thin wrapper around Java, making it look like a scripting language: it has a (primitive) IDE when you can type a few lines of code and hit Run without even having to save the file. Actually it wraps the code around a class and adds a main() call, compiles it and run it in a window.</p>\n\n<p>Lot of people use it for real-time exhibitions (VJ and similar).\nIt has the power and limitations of Java, but adds out of the box a number of nice wrappers (libraries) to simplify access to Java2D, OpenGL, SVG, etc.</p>\n\n<p>Somehow, it has become a model of simple graphics language: there are several applications trying to mimic Processing in other languages, like Ruby, Scala or Python. One of the most impressive is a JavaScript implementation, using the <code>canvas</code> component implemented in Firefox, Safari, Opera, etc.</p>\n'}, {'answer_id': 776104, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Don\'t overlook independent languages in your quest. Emergence BASIC from Ionic Wind Software has a built in DirectX 9 engine, supports OOP and can easily interface with C libraries.</p>\n\n<p><a href="http://www.ionicwind.com" rel="nofollow noreferrer">http://www.ionicwind.com</a></p>\n\n<p>James.</p>\n'}, {'answer_id': 857269, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>As a developer/researcher/professor of 3D VR applications for some 20 years I would suggest there is no alternative (except possibly C). The only way to reduce latency and enable real-time interaction is an optimized compiled language (eg C or C++) with access to a fast relaible 3D graphics library such as OpenGL. While I agree it is flustrating to have to code everything, this is also essential for performanc and optimization. </p>\n'}, {'answer_id': 1519427, 'author': 'sdclibbery', 'author_id': 184281, 'author_profile': 'https://Stackoverflow.com/users/184281', 'pm_score': 1, 'selected': False, 'text': '<p>I have very successfully used C++ for the engine, with the application written in Lua on top. JavaScript is also very practical, now the latest generation of JIT based JS engines are around (tracemonkey, V8 etc).</p>\n\n<p>I think C++ will be with us for a while yet; even Tim Sweeney hasn\'t actually <a href="http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf" rel="nofollow noreferrer">switched to Haskell</a> (pdf) yet, AFAIK :-)</p>\n'}, {'answer_id': 1519509, 'author': 'Tobias Langner', 'author_id': 79996, 'author_profile': 'https://Stackoverflow.com/users/79996', 'pm_score': 0, 'selected': False, 'text': '<p>The best enviroment for your project is the one you get your task done in the fastest way possible. This - especially for 3D-graphics - includes libraries.</p>\n\n<p>Depending on the task, you may get away with some minor directx hacking. Then you could use .NET and <a href="http://slimdx.org/" rel="nofollow noreferrer">slimdx</a>. Managed languages tend to be faster to programm and easier to debug.</p>\n\n<p>Perhaps you need a really good 3D-engine? Try <a href="http://www.ogre3d.org" rel="nofollow noreferrer">Ogre3D</a> or <a href="http://irrlicht.sourceforge.net/" rel="nofollow noreferrer">Irrlicht</a>. You need commercial grade quality (one might argue that Ogre3D offers that) - go for Cryengine or Unreal. With Ogre3D and Irrlicht you might uses .NET as well, though the ports are not always up to date and plugins are not as easyly included as in the C++ versions. For Cryengine/Unrealengine you won\'t have a real choice I guess.</p>\n\n<p>You need it more portable? <a href="http://www.opengl.org/" rel="nofollow noreferrer">OpenGL</a> for the rescue - though you might need some wrapper (e.g. <a href="http://www.libsdl.org" rel="nofollow noreferrer">SDL</a>).</p>\n\n<p>You need a GUI as well? <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a>, <a href="http://qt.nokia.com/products" rel="nofollow noreferrer">QT</a> might be a possiblity.</p>\n\n<p>You already have a toolchain? Your libraries need to be able to handle the file formats.</p>\n\n<p>You want to write a library? C / C++ might be a solution, since most of the world can use C / C++ libraries. Perhaps with the use of COM?</p>\n\n<p>There are still a lot of projects/libraries I did not mention (XNA, Boost, ...) and if you want to create some program that does not only display 3D-graphics, you might have other needs as well (Input, Sound, Network, AI, Database, GUI, ...)</p>\n\n<p>To sum it up: A programming language is a tool to reach a goal. It has to be seen in the context of the task at hand. The task has its own needs and these needs may chose the language for you (e.g. you need a certain library to get a feature that takes long to programm and you can only access the library with language X).</p>\n\n<p>If you need the one-does-nearly-all: try C++/CLI (perhaps in combination with C# for easier syntax).</p>\n'}, {'answer_id': 1951889, 'author': 'oyd11', 'author_id': 237493, 'author_profile': 'https://Stackoverflow.com/users/237493', 'pm_score': 0, 'selected': False, 'text': "<p>Good question.\nAs for the 'making me type far too much', C++0x seems to address most of it\nas mentioned:</p>\n\n<p>auto it = lotsOfThingys.begin()) // ... deduce type, just like in *ML\nVS2010beta implements this already.</p>\n\n<p>As for the memory management - for efficiency - you will have to keep good track of memory allocations, with or without garbage collection (ie, make memory-pools, re-use allocated object sometimes) anyhow, so that eventually whether your environment is garbage collected or not, matters less. You'll have to explicitly call the gc() as well, to keep the memory from fragmenting.\nHaving consistent ways to manage memory is important anywhere.\nRAII - is a killer feature of C++ \nAnother thing - is that memory is just one resource, you still have to keep track of other resources with a GC, so RIAA.</p>\n\n<p>Anyhow, C# - is a nice alternative in many respects, I find it a very nice language, especially the ability to write functional-style code in it (the cute lambda -> syntax, map/select 'LINQ' syntax etc), thus the possibility to write parallel code; while it's still a 'standard curly-brackets', when you (or your colleagues) need it.</p>\n"}, {'answer_id': 1993746, 'author': 'crelbor', 'author_id': 150712, 'author_profile': 'https://Stackoverflow.com/users/150712', 'pm_score': 2, 'selected': False, 'text': '<p>I vote c++0x. Partial support is already available in gcc-4.3+ using the -std=c++0x flag.</p>\n'}, {'answer_id': 3071648, 'author': 'philnext', 'author_id': 359671, 'author_profile': 'https://Stackoverflow.com/users/359671', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look to Delphi/Pascal Object and some exemples :\n<a href="http://www.delphigamer.com" rel="nofollow noreferrer">http://www.delphigamer.com</a> or <a href="http://glscene.cjb.net/" rel="nofollow noreferrer">http://glscene.cjb.net/</a></p>\n'}, {'answer_id': 4265913, 'author': 'Rik', 'author_id': 518630, 'author_profile': 'https://Stackoverflow.com/users/518630', 'pm_score': 1, 'selected': False, 'text': "<p>Java and LWJGL (OpenGL wrapper) has worked well for me. If you're looking for more of a scene graph type library like Orge have a look at jMonkeyEngine which we used to create a google earth type application (see www.skapeworld.com). If you're sensible with object creation the garbage collection is a non issue.</p>\n"}, {'answer_id': 5339700, 'author': 'BenjaminB', 'author_id': 282815, 'author_profile': 'https://Stackoverflow.com/users/282815', 'pm_score': 0, 'selected': False, 'text': "<p>You can look at <strong>Ada</strong>. There is no garbage collector but this language is oftenly used for real-time system needing high reliability. That means less debuging times for your 3D applications.</p>\n\n<p>And, you can also look at <strong>Haskell</strong>, if you don't know the functional paradigm this language will look weird to you, but it's worth a bit of your time. Tim Sweeney (EPIC Inc) is considering this language as a C++ alternative.</p>\n"}, {'answer_id': 5343237, 'author': 'Martin Beckett', 'author_id': 10897, 'author_profile': 'https://Stackoverflow.com/users/10897', 'pm_score': 2, 'selected': False, 'text': "<p>Would 'C' be too obvious an answer?</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9631/'] |
72,936 | <pre>
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
ls: cannot access commit-msg: No such file or directory
ls: cannot access pre-rebase: No such file or directory
ls: cannot access post-receive: No such file or directory
ls: cannot access pre-applypatch: No such file or directory
ls: cannot access pre-commit: No such file or directory
total 8
drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 .
drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 ..
-????????? ? ? ? ? ? commit-msg
-????????? ? ? ? ? ? post-commit
-????????? ? ? ? ? ? post-receive
-????????? ? ? ? ? ? post-update
-????????? ? ? ? ? ? pre-applypatch
-????????? ? ? ? ? ? pre-commit
-????????? ? ? ? ? ? pre-rebase
-????????? ? ? ? ? ? update
</pre>
| [{'answer_id': 72988, 'author': 'raldi', 'author_id': 7598, 'author_profile': 'https://Stackoverflow.com/users/7598', 'pm_score': 4, 'selected': True, 'text': "<p>First off, here's your question, nicely formatted (surround it in < pre > tags to get this):</p>\n\n<pre>kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al\nls: cannot access post-commit: No such file or directory\nls: cannot access update: No such file or directory\nls: cannot access post-update: No such file or directory\n[snip]</pre>\n\n<p>Anyway, you need to boot up in single-user mode and run fsck. If you can't reboot right now, just move the directory to /tmp and forget about it.</p>\n"}, {'answer_id': 73013, 'author': 'David Precious', 'author_id': 4040, 'author_profile': 'https://Stackoverflow.com/users/4040', 'pm_score': 1, 'selected': False, 'text': "<p>(a) Looks like you have some kind of filesystem problems; I'd recommend you run fsck and see if it finds anything</p>\n\n<p>(b) Really not a programming-related question, so off-topic here.</p>\n"}, {'answer_id': 8263727, 'author': 'James EJ', 'author_id': 600525, 'author_profile': 'https://Stackoverflow.com/users/600525', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same problem caused by Aptana Studio working with rails more than once.\n The long term solution was to avoid using aptana to create files.</p>\n'}, {'answer_id': 23014728, 'author': 'iOSAndroidWindowsMobileAppsDev', 'author_id': 1611779, 'author_profile': 'https://Stackoverflow.com/users/1611779', 'pm_score': 0, 'selected': False, 'text': '<p>I ran into this problem and tried everything. Surprisingly the solution is very simple. Dude, this is what you do:\nUsing GUI and not the terminal\n1. Move all other files in that folder to a different one with a different name\n2. Move the containing directory which should have only the problematic file to trash\n3 Empty trash</p>\n\n<p>and yes, it is that simple</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12417/'] |
72,943 | <p>Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab?</p>
<p>Here's what I'm doing today:
<code></p>
<pre>
var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args);
try {
// Not all window types support the focus() property.
winRef.focus();
}
catch (exception) {
}
</pre>
<p></code></p>
<p>The window opens, but the new tab doesn't receive focus.</p>
| [{'answer_id': 72971, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 1, 'selected': False, 'text': '<p>As a user, I never want applications (or tabs) to take focus unless I specifically requested it. I have gone to great lengths to prevent tabs in my browser (Firefox) from taking focus for this reason. </p>\n'}, {'answer_id': 72997, 'author': 'Guido', 'author_id': 12388, 'author_profile': 'https://Stackoverflow.com/users/12388', 'pm_score': 3, 'selected': True, 'text': '<p>Jay,</p>\n\n<p>You are seeing designed behavior. To limit opportunities for malicious behavior, scripts running in tabbed windows cannot affect other tabs.</p>\n\n<p>For more information, please see Tabbed Browsing for Developers at <a href="http://msdn.microsoft.com/en-us/library/ms537636.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms537636.aspx</a> :</p>\n\n<p>"The ability to open multiple documents within the same browser window has certain practical and security implications [...] Active tabs (tabs with focus) cannot be affected by scripts that run in inactive or background tabs."</p>\n\n<p>BR.</p>\n'}, {'answer_id': 73005, 'author': 'Erratic', 'author_id': 2246765, 'author_profile': 'https://Stackoverflow.com/users/2246765', 'pm_score': 1, 'selected': False, 'text': "<p>I'm reasonably certain you can't shift focus to another tab.</p>\n\n<p>My understanding is this is done to somewhat limit pop ups and other malicious content from stealing the users focus. </p>\n"}, {'answer_id': 78119, 'author': 'Brendan Kidwell', 'author_id': 13958, 'author_profile': 'https://Stackoverflow.com/users/13958', 'pm_score': 1, 'selected': False, 'text': '<p>If the other "tab" is part of your application (and not content from another site) perhaps you should include it in a popup div on top of your main content instead of in a separate window; that way you can always control focusing it, deactivating the content under it (for modal dialogs), hiding it, etc.</p>\n'}, {'answer_id': 547019, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>As a user, shouldn't I be able to control how this operates?</p>\n\n<p>What if there is an application that would be enhanced by this feature that I want to run - shouldn't I be able to grant a domain that privilege?</p>\n\n<p>Just a thought.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/733/'] |
72,945 | <p>Using Django's built in models, how would one create a triple-join between three models.</p>
<p>For example:</p>
<ul>
<li>Users, Roles, and Events are the models.</li>
<li>Users have many Roles, and Roles many Users. (ManyToMany)</li>
<li>Events have many Users, and Users many Events. (ManyToMany)</li>
<li>But for any given Event, any User may have only one Role.</li>
</ul>
<p>How can this be represented in the model?</p>
| [{'answer_id': 73153, 'author': 'Eli Courtwright', 'author_id': 1694, 'author_profile': 'https://Stackoverflow.com/users/1694', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d recommend just creating an entirely separate model for this.</p>\n\n<pre><code>class Assignment(Model):\n user = ForeignKey(User)\n role = ForeignKey(Role)\n event = ForeignKey(Event)\n</code></pre>\n\n<p>This lets you do all the usual model stuff, such as</p>\n\n<pre><code>user.assignment_set.filter(role__name="Chaperon")\nrole.assignment_set.filter(event__name="Silly Walkathon")\n</code></pre>\n\n<p>The only thing left is to enforce your one-role-per-user-per-event restriction. You can do this in the Assignment class by either overriding the save method (<a href="http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods</a>) or using signals (<a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/topics/signals/</a>)</p>\n'}, {'answer_id': 76221, 'author': 'Aaron Maenpaa', 'author_id': 2603, 'author_profile': 'https://Stackoverflow.com/users/2603', 'pm_score': 0, 'selected': False, 'text': "<p>I'd model Role as an association class between Users and Roles, thus,</p>\n\n<pre><code>class User(models.Model):\n ...\n\nclass Event(models.Model):\n ...\n\nclass Role(models.Model):\n user = models.ForeignKey(User)\n event = models.ForeignKey(Event)\n</code></pre>\n\n<p>And enforce the one role per user per event in either a manager or SQL constraints.</p>\n"}, {'answer_id': 77898, 'author': 'zuber', 'author_id': 9812, 'author_profile': 'https://Stackoverflow.com/users/9812', 'pm_score': 5, 'selected': True, 'text': '<p><strong>zacherates</strong> writes:</p>\n\n<blockquote>\n <p>I\'d model Role as an association class between Users and Roles (...)</p>\n</blockquote>\n\n<p>I\'d also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="noreferrer">ManyToMany relation with extra fields</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>class User(models.Model):\n name = models.CharField(max_length=128)\n\nclass Event(models.Model):\n name = models.CharField(max_length=128)\n members = models.ManyToManyField(User, through=\'Role\')\n\n def __unicode__(self):\n return self.name\n\nclass Role(models.Model):\n person = models.ForeignKey(User)\n group = models.ForeignKey(Event)\n date_joined = models.DateField()\n invite_reason = models.CharField(max_length=64)\n</code></pre>\n'}, {'answer_id': 16290256, 'author': 'Brent Washburne', 'author_id': 584846, 'author_profile': 'https://Stackoverflow.com/users/584846', 'pm_score': 0, 'selected': False, 'text': '<p>While trying to find a faster three-table join for my own Django models, I came across this question. By default, Django 1.1 uses INNER JOINs which can be slow on InnoDB. For a query like:</p>\n\n<pre><code>def event_users(event_name):\n return User.objects.filter(roles__events__name=event_name)\n</code></pre>\n\n<p>this might create the following SQL:</p>\n\n<pre><code>SELECT `user`.`id`, `user`.`name` FROM `user` INNER JOIN `roles` ON (`user`.`id` = `roles`.`user_id`) INNER JOIN `event` ON (`roles`.`event_id` = `event`.`id`) WHERE `event`.`name` = "event_name"\n</code></pre>\n\n<p>The INNER JOINs can be very slow compared with LEFT JOINs. An even faster query can be found under gimg1\'s answer: <a href="https://stackoverflow.com/questions/10257433/mysql-query-to-join-three-tables#10257569">Mysql query to join three tables</a></p>\n\n<pre><code>SELECT `user`.`id`, `user`.`name` FROM `user`, `roles`, `event` WHERE `user`.`id` = `roles`.`user_id` AND `roles`.`event_id` = `event`.`id` AND `event`.`name` = "event_name"\n</code></pre>\n\n<p>However, you will need to use a custom SQL query: <a href="https://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/dev/topics/db/sql/</a></p>\n\n<p>In this case, it would look something like:</p>\n\n<pre><code>from django.db import connection\ndef event_users(event_name):\n cursor = connection.cursor()\n cursor.execute(\'select U.name from user U, roles R, event E\' \\\n \' where U.id=R.user_id and R.event_id=E.id and E.name="%s"\' % event_name)\n return [row[0] for row in cursor.fetchall()]\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8507/'] |
72,958 | <p>I am trying to program a small server+client in Javascript on Firefox, using XPCOM.</p>
<p>To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.</p>
<p>Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)</p>
<p>J.</p>
| [{'answer_id': 73939, 'author': 'Chouser', 'author_id': 7624, 'author_profile': 'https://Stackoverflow.com/users/7624', 'pm_score': 0, 'selected': False, 'text': '<p>If you control the protocol (that is, both the client and server) I would highly recommend using Javascript/JSON for your server-to-client messages. The client can open a stream either via dynamically adding a <script> tag to the DOM. The server can then send a stream of Javascript commands like:</p>\n\n<pre><code>receiveMsg({type:"text", content:"this is my message"});\n</code></pre>\n\n<p>Then the client just needs to define a receiveMsg function. This allows you to rely on fast browser code to parse the message and determine where the end of each message is, at which point it will call your handler for you.</p>\n\n<p>Even if you\'re working with an existing HTTP protocol and can\'t use JSON, is there some reason you can\'t use XMLHttpRequest? I would expect it to be more stable than some poorly documented Firefox-specific XPCOM interface.</p>\n\n<p>--Chouser</p>\n'}, {'answer_id': 75825, 'author': 'Zach', 'author_id': 9128, 'author_profile': 'https://Stackoverflow.com/users/9128', 'pm_score': 1, 'selected': False, 'text': '<p>I had the same problem with unreliability... I ended up using XMLHTTPRequest, which when used from the XPCOM component can do cross site requests. The second part of the <a href="http://developer.mozilla.org/en/XMLHttpRequest" rel="nofollow noreferrer">docs</a> detail how to instantiate the XPCOM version.</p>\n\n<p>If you\'re looking to serve HTTP request I\'d take a look at the <a href="https://addons.mozilla.org/en-US/firefox/addon/3002" rel="nofollow noreferrer">POW</a> source code and the use of <a href="http://www.xulplanet.com/tutorials/mozsdk/serverpush.php" rel="nofollow noreferrer">server sockets</a>, which implements a basic HTTP server in JavaScript. Also check out <a href="http://mxr.mozilla.org/mozilla/source/netwerk/test/httpserver/httpd.js" rel="nofollow noreferrer">httpd.js</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
72,961 | <p>So our SQL Server 2000 is giving me the error, "The log file for database is full. Back up the transaction log for the database to free up some log space."</p>
<p>How do I go about fixing this without deleting the log like some other sites have mentioned?</p>
<p>Additional Info: Enable AutoGrowth is enabled growing by 10% and is restricted to 40MB.</p>
| [{'answer_id': 72984, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': -1, 'selected': False, 'text': '<p>Rename it it. eg:<br>\nold-log-16-09-08.log</p>\n\n<p>Then the SQL server can use a new empty one.</p>\n'}, {'answer_id': 73023, 'author': 'Marc Gear', 'author_id': 6563, 'author_profile': 'https://Stackoverflow.com/users/6563', 'pm_score': 0, 'selected': False, 'text': "<p>Well you could take a copy of the transaction log, then truncate the log file, which is what the error message suggests.</p>\n\n<p>If disk space is full and you can't copy the log to another machine over the network, then connect a drive via USB and copy it off that way.</p>\n"}, {'answer_id': 73027, 'author': 'cori', 'author_id': 8151, 'author_profile': 'https://Stackoverflow.com/users/8151', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think renaming or moving the log file will work while the database is online.</p>\n\n<p>Easiest thing to do, IMO, is to open the properties for the database and switch it to Simple Recovery Model. then shrink the database and then go back and set the DB to Full Recoery Model (or whatever model you need). </p>\n\n<p>Changing the logging mode forces SQL Server to set a checkpoint in the database, after which shrinking the database will free up the excess space.</p>\n"}, {'answer_id': 73036, 'author': 'Miroslav Zadravec', 'author_id': 8239, 'author_profile': 'https://Stackoverflow.com/users/8239', 'pm_score': 0, 'selected': False, 'text': '<p>You have the answer in your question: Backup the log, then it will be shrunk.\nMake a maintenance plan to regularly backup the database and don\'t forget to select "Backup the transaction log". That way you\'ll keep it small.</p>\n'}, {'answer_id': 73074, 'author': 'TrevorD', 'author_id': 12492, 'author_profile': 'https://Stackoverflow.com/users/12492', 'pm_score': 4, 'selected': False, 'text': "<p>To just empty it:</p>\n\n<pre><code>backup log <dbname> with truncate_only \n</code></pre>\n\n<p>To save it somewhere:</p>\n\n<pre><code>backup log <dbname> to disk='c:\\somefile.bak'\n</code></pre>\n\n<p>If you dont really need transactional history, try setting the database recovery mode to simple.</p>\n"}, {'answer_id': 73136, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>If it's a <strong>non</strong> production environment use </p>\n\n<pre><code>dump tran <db_name> with no_log;\n</code></pre>\n\n<p>Once this has completed shrink the log file to free up disk space. Finally switch database recovery mode to simple.</p>\n"}, {'answer_id': 73269, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 1, 'selected': False, 'text': "<p>My friend who faced this error in the past recommends:</p>\n\n<p>Try</p>\n\n<ul>\n<li>Backing up the DB. The maintenance plan includes truncation of these files.</li>\n<li>Also try changing the 'recovery mode' for the DB to <em>Simple</em> (instead of <em>Full</em> for instance)</li>\n</ul>\n\n<p>Cause:\nThe transaction log swells up due to events being logged (Maybe you have a number of transactions failing and being rolled back.. or a sudden peaking in transactions on the server )</p>\n"}, {'answer_id': 73421, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 0, 'selected': False, 'text': "<p>As soon as you take a full backup of the database, and the database is not using the Simple recovery model, SQL Server keeps a complete record of all transactions ever performed on the database. It does this so that in the event of a catastrophic failure where you lose the data file, you can restore to the point of failure by backing up the log and, once you have restored an old data backup, restore the log to replay the lost transactions.</p>\n\n<p>To prevent this building up, you must back up the transaction log. Or, you can break the chain at the current point using the TRUNCATE_ONLY or NO_LOG options of BACKUP LOG.</p>\n\n<p>If you don't need this feature, set the recovery model to Simple.</p>\n"}, {'answer_id': 74030, 'author': 'kristof', 'author_id': 3241, 'author_profile': 'https://Stackoverflow.com/users/3241', 'pm_score': 1, 'selected': False, 'text': '<p>You may want to check related SO question:</p>\n\n<ul>\n<li><a href="https://stackoverflow.com/questions/56628/how-do-you-clear-the-transaction-log-in-a-sql-server-2005-database#63070">How do you clear the transaction log in a SQL Server 2005 database?</a></li>\n</ul>\n'}, {'answer_id': 74480, 'author': 'Michael K. Campbell', 'author_id': 11191, 'author_profile': 'https://Stackoverflow.com/users/11191', 'pm_score': 3, 'selected': True, 'text': '<p>Scott, as you guessed: truncating the log is a bad move if you care about your data.</p>\n\n<p>The following, free, videos will help you see exactly what\'s going on and will show you how to fix the problem without truncating the logs. (These videos also explain why that\'s such a dangerous hack and why you are right to look for another solution.)</p>\n\n<ul>\n<li><a href="http://www.sqlservervideos.com/sqlserver-backups/backups-demystified" rel="nofollow noreferrer">SQL Server Backups Demystified</a></li>\n<li><a href="http://www.sqlservervideos.com/sqlserver-backups/logging-essentials" rel="nofollow noreferrer">SQL Server Logging Essentials</a></li>\n<li><a href="http://www.sqlservervideos.com/sqlserver-backups/backup-options" rel="nofollow noreferrer">Understanding Backup Options</a></li>\n</ul>\n\n<p>Together these videos will help you understand exactly what\'s going on and will show you whether you want to switch to SIMPLE recovery, or look into actually changing your backup routines. There are also some additional \'how-to\' videos that will show you exactly how to set up your backups to ensure availability while managing log file sizing and growth. </p>\n'}, {'answer_id': 76908, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>ether backup your database logs regularly if you need to recover up to the minute or do other fun stuff like log shipping in the future, or set the database to simple mode and shrink the data file. </p>\n\n<p>DO NOT copy, rename, or delete the .ldf file this will break your database and after you recover from this you may have data in an inconsistent state making it invalid.</p>\n'}, {'answer_id': 10979331, 'author': 'shadab shah', 'author_id': 1429149, 'author_profile': 'https://Stackoverflow.com/users/1429149', 'pm_score': 0, 'selected': False, 'text': "<p>My dear friend it is vey important for a DBA to check his log file quite frequently. Because if you don't give much attention towards it some day it is going to give this error.</p>\n\n<p>For this purpose you have to periodically take back up so that the logs file would not faced such error.</p>\n\n<p>Other then this the above given suggestion are quite right.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2863/'] |
72,983 | <p>I was wondering; which logging libraries for Delphi do you prefer?</p>
<ul>
<li><a href="http://www.raize.com/devtools/codesite/" rel="noreferrer">CodeSite</a></li>
<li><a href="http://www.gurock.com/products/smartinspect/" rel="noreferrer">SmartInspect</a></li>
<li><a href="http://log4delphi.sourceforge.net/" rel="noreferrer">Log4Delphi</a></li>
<li><a href="http://tracetool.sourceforge.net/" rel="noreferrer">TraceFormat</a></li>
</ul>
<p>Please try to add a reasoning why you prefer one over the other if you've used more than one.</p>
<p>I'll add suggestions to this question to keep things readable.</p>
| [{'answer_id': 73015, 'author': 'Kaerber', 'author_id': 12428, 'author_profile': 'https://Stackoverflow.com/users/12428', 'pm_score': 2, 'selected': False, 'text': "<p>Log4net/ports of Log4xxx to other languages. It's open-source, pretty wide-spread, popular, has a good community behind, and isused widel (for example, in Hibernate/nHibernate).</p>\n"}, {'answer_id': 73113, 'author': 'Erick Sasse', 'author_id': 2089, 'author_profile': 'https://Stackoverflow.com/users/2089', 'pm_score': 1, 'selected': False, 'text': "<p>I didn't use CodeSite probably because I'm completely happy with SmartInspect. Highly recommended.</p>\n"}, {'answer_id': 73234, 'author': 'mj2008', 'author_id': 5544, 'author_profile': 'https://Stackoverflow.com/users/5544', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve used Codesite and it has been fantastic. On one project, a word-processor, I could easily output a million debug lines, all structured, and Codesite helped greatly with its auto-collapsing indented output. For any task where you have to know what really is happening "underneath" a process that can\'t be interrupted by user interaction, Codesite is really good. I recommend it heartily.</p>\n'}, {'answer_id': 73865, 'author': 'Peter', 'author_id': 12833, 'author_profile': 'https://Stackoverflow.com/users/12833', 'pm_score': 0, 'selected': False, 'text': '<p>I am looking into Codesite as well. I built my own in the past but I really like the featrues in Codesite. The Raize componenets are very well written and always quality stuff.</p>\n'}, {'answer_id': 74435, 'author': 'Lars Truijens', 'author_id': 1242, 'author_profile': 'https://Stackoverflow.com/users/1242', 'pm_score': 3, 'selected': False, 'text': '<p>And don\'t forget the free open source <a href="http://tracetool.sourceforge.net/" rel="noreferrer">TraceTool</a></p>\n'}, {'answer_id': 85050, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 4, 'selected': True, 'text': '<p><strong>SmartInspect</strong> is really useful. It is the only one I have used. The logging library is good, but the console and the remote TCP/IP logging takes it over the top. I think CodeSite has some similar features.</p>\n'}, {'answer_id': 99272, 'author': 'Argalatyr', 'author_id': 18484, 'author_profile': 'https://Stackoverflow.com/users/18484', 'pm_score': 2, 'selected': False, 'text': "<p>An important value behind CodeSite is Ray Kanopka's support. He personally answers emails and newsgroup posts, and has done so for many years. His answers often contain code that illustrates excellent coding habits.</p>\n"}, {'answer_id': 708888, 'author': 'mjn', 'author_id': 80901, 'author_profile': 'https://Stackoverflow.com/users/80901', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://sourceforge.net/projects/log4d/" rel="nofollow noreferrer">Log4D</a> is another implementation which is based on Log4J and easy to extend and configure.</p>\n'}, {'answer_id': 4165270, 'author': 'Melloware', 'author_id': 502366, 'author_profile': 'https://Stackoverflow.com/users/502366', 'pm_score': 3, 'selected': False, 'text': '<p>I have just updated Log4Delphi 0.8 on the Sourceforge page and it rolls up patches and bug fixes from the last 4 years.</p>\n\n<p><a href="https://sourceforge.net/projects/log4delphi/files/">Sourceforge Log4Delphi Downloads</a></p>\n'}, {'answer_id': 5676498, 'author': 'Arnaud Bouchez', 'author_id': 458259, 'author_profile': 'https://Stackoverflow.com/users/458259', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at the features of this Open Source unit:\n<a href="http://blog.synopse.info/post/2011/04/14/Enhanced-logging-in-SynCommons" rel="nofollow">http://blog.synopse.info/post/2011/04/14/Enhanced-logging-in-SynCommons</a></p>\n\n<ul>\n<li>logging with a set of levels (not only a hierarchy of levels);</li>\n<li>fast, low execution overhead;</li>\n<li>can load .map file symbols to be used in logging;</li>\n<li>compression of .map into binary .mab (900 KB -> 70 KB);</li>\n<li>optional inclusion of the .map/.mab into the .exe;</li>\n<li>handle libraries (.ocx/.dll);</li>\n<li>exception logging (Delphi or low-level exceptions) with unit names and line numbers;</li>\n<li>optional stack trace with units and line numbers;</li>\n<li>methods or procedure recursive tracing, with Enter and auto-Leave;</li>\n<li>high resolution time stamps, for customer-side profiling of the application execution;</li>\n<li>set / enumerates / TList / TPersistent / TObjectList / dynamic array JSON serialization;</li>\n<li>per-thread, rotating or global logging;</li>\n<li>multiple log files on the same process;</li>\n<li>optional colored console display;</li>\n<li>optional redirected logging (e.g. to third party library, or to a remote server);</li>\n<li>log viewer GUI application, with per event or per thread filters, and method execution profiler;</li>\n<li>Open Source, works from Delphi 5 up to XE6 (Win32 and Win64).</li>\n</ul>\n\n<p>Your feedback is welcome!</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12170/'] |
72,994 | <p>I want to simulate a 'Web 2.0' Lightbox style UI technique in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. </p>
<p>The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? </p>
<p>I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful.
If it is not possible, what would be another way to do it?</p>
<p>See: <a href="http://www.useit.com/alertbox/application-design.html" rel="noreferrer">http://www.useit.com/alertbox/application-design.html</a> (under the Lightbox section for a screenshot to illustrate what I mean.)</p>
| [{'answer_id': 73062, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>The forms themselves have the property <code>Opacity</code> that would be perfect, but I don't think most of the individual controls do. You'll have to owner-draw it.</p>\n"}, {'answer_id': 73065, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 1, 'selected': False, 'text': '<p>The big dimming rectangle is good.</p>\n\n<p>Another way to do it would be:</p>\n\n<p>Roll your own base Form class says a <code>MyLightboxAwareForm</code> class that would listen to a <code>LightboxEvent</code> from a <code>LightboxManager</code>. Then have all your forms inherit from <code>MyLightboxAwareForm</code>.</p>\n\n<p>On calling the <code>Show</code> method on any <code>Lightbox</code>, the <code>LightboxManager</code> would broadcast a <code>LightboxShown</code> event to all <code>MyLightboxAwareForm</code> instances and making them dim themselves.</p>\n\n<p>This has the advantage that normal Win32 forms functionality will continue to work such as taskbar-flashing of the form when you click on one of its modal dialogs or the management of mouseover/mousedown events would still work normally etc.</p>\n\n<p>And if you want the rectangle dimming style, you could just put the logic in MyLightboxAwareForm</p>\n'}, {'answer_id': 73146, 'author': 'Miroslav Zadravec', 'author_id': 8239, 'author_profile': 'https://Stackoverflow.com/users/8239', 'pm_score': 0, 'selected': False, 'text': '<p>Every form has "Opacity" property. Set it to 50% (or 0.5 from code) so will be half transparent. Remove borders and show it maximized before the form you want to have focus. You can change BackColor of the form or even set background image for different effects.</p>\n'}, {'answer_id': 73191, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 4, 'selected': False, 'text': '<p>Can you do this in .NET/C#? </p>\n\n<p>Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...</p>\n\n<pre><code>public class DarkenArea : Form\n{\n public DarkenArea()\n {\n FormBorderStyle = FormBorderStyle.None;\n SizeGripStyle = SizeGripStyle.Hide;\n StartPosition = FormStartPosition.Manual;\n MaximizeBox = false;\n MinimizeBox = false;\n ShowInTaskbar = false;\n BackColor = Color.Magenta;\n TransparencyKey = Color.Magenta;\n Opacity = 0.5f;\n }\n}\n</code></pre>\n\n<p>Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...</p>\n\n<pre><code>public void ShowWithoutActivate()\n{\n // Show the window without activating it (i.e. do not take focus)\n PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);\n}\n</code></pre>\n\n<p>You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...</p>\n\n<pre><code>protected override void OnPaint(PaintEventArgs e)\n{\n base.OnPaint(e);\n // Do your painting here be exclude the area you want to be brighter\n}\n</code></pre>\n\n<p>Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...</p>\n\n<pre><code>protected override void WndProc(ref Message m)\n{\n if (m.Msg == (int)WM_NCHITTEST)\n m.Result = (IntPtr)HTTRANSPARENT;\n else\n base.WndProc(ref m);\n}\n</code></pre>\n\n<p>That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.</p>\n'}, {'answer_id': 169855, 'author': 'ZeroBugBounce', 'author_id': 11314, 'author_profile': 'https://Stackoverflow.com/users/11314', 'pm_score': 3, 'selected': False, 'text': '<p>This is a really cool idea - I will probably use it, so thanks. Anyway, my solution is really simple... open a new 50% opaque form over your current one and then custom draw a background image for that form with a rectangle matching the bounds of the control you want to highlight filled in the color of the transparency key.</p>\n\n<p>In my rough sample, I called this form the \'LBform\' and the meat of it is this:</p>\n\n<pre><code>public Rectangle ControlBounds { get; set; }\nprivate void LBform_Load(object sender, EventArgs e)\n{\n Bitmap background = new Bitmap(this.Width, this.Height);\n Graphics g = Graphics.FromImage(background);\n g.FillRectangle(Brushes.Fuchsia, this.ControlBounds);\n\n g.Flush();\n\n this.BackgroundImage = background;\n this.Invalidate();\n}\n</code></pre>\n\n<p>Color.Fuchia is the TransparencyKey for this semi-opaque form, so you will be able to see through the rectangle drawn and interact with anything within it\'s bounds on the main form.</p>\n\n<p>In the experimental project I whipped up to try this, I used a UserControl dynamically added to the form, but you could just as easily use a control already on the form. In the main form (the one you are obscuring) I put the relevant code into a button click:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n // setup user control:\n UserControl1 uc1 = new UserControl1();\n uc1.Left = (this.Width - uc1.Width) / 2;\n uc1.Top = (this.Height - uc1.Height) / 2;\n this.Controls.Add(uc1);\n uc1.BringToFront();\n\n // load the lightbox form:\n LBform lbform = new LBform();\n lbform.SetBounds(this.Left + 8, this.Top + 30, this.ClientRectangle.Width, this.ClientRectangle.Height);\n lbform.ControlBounds = uc1.Bounds;\n\n lbform.Owner = this;\n lbform.Show();\n}\n</code></pre>\n\n<p>Really basic stuff that you can do your own way if you like, but it\'s just adding the usercontrol, then setting the lightbox form over the main form and setting the bounds property to render the full transparency in the right place. Things like form dragging and closing the lightbox form and UserControl aren\'t handled in my quick sample. Oh and don\'t forget to dispose the Graphics instance - I left that out too (it\'s late, I\'m really tired).</p>\n\n<p><a href="http://cid-12d219ccfc930f76.skydrive.live.com/self.aspx/Code/LightBox000.zip" rel="noreferrer">Here\'s my very did-it-in-20-minutes demo</a></p>\n'}, {'answer_id': 5757080, 'author': 'Gad', 'author_id': 25152, 'author_profile': 'https://Stackoverflow.com/users/25152', 'pm_score': 1, 'selected': False, 'text': "<p>Another solution that doesn't involve using a new Form :</p>\n\n<ul>\n<li>make a picture of your container (form / panel / whatever), </li>\n<li>change its opacity,</li>\n<li>display it in a new panel's background.</li>\n<li>Fill your container with that panel.</li>\n</ul>\n\n<p>And now the code... </p>\n\n<p>Let's say I have a UserControl called Frame to which I'll want to apply my lightbox effect:</p>\n\n<pre><code>public partial class Frame : UserControl\n{\n private Panel shadow = new Panel();\n private static float LIGHTBOX_OPACITY = 0.3f;\n\n public Frame()\n {\n InitializeComponent(); \n shadow.Dock = DockStyle.Fill;\n }\n\n public void ShowLightbox()\n {\n Bitmap bmp = new Bitmap(this.Width, this.Height);\n this.pnlContainer.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));\n shadow.BackgroundImage = SetImgOpacity(bmp, LIGHTBOX_OPACITY );\n this.Controls.Add(shadow);\n shadow.BringToFront();\n }\n\n // http://www.geekpedia.com/code110_Set-Image-Opacity-Using-Csharp.html\n private Image SetImgOpacity(Image imgPic, float imgOpac)\n {\n Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);\n Graphics gfxPic = Graphics.FromImage(bmpPic);\n ColorMatrix cmxPic = new ColorMatrix();\n cmxPic.Matrix33 = imgOpac;\n ImageAttributes iaPic = new ImageAttributes();\n iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);\n gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);\n gfxPic.Dispose();\n return bmpPic;\n }\n}\n</code></pre>\n\n<p>The advantages to using this technique are :</p>\n\n<ul>\n<li>You won't have to handle all of the mouse events</li>\n<li>You won't have to manage multiple forms to communicate with the lightbox elements</li>\n<li>No overriding of WndProc</li>\n<li>You'll be cool because you'll be the only one not to use forms to achieve this effect.</li>\n</ul>\n\n<p>Drawbacks are mainly that this technique is much slower because you have to process an entire image to correct each pixel point using the ColorMatrix.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6199/'] |
72,996 | <p>I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work. </p>
<p>I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel. </p>
<p>Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much. </p>
<p>Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.</p>
<p>Format of XML for example purposes:
File1.xml</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xinclude href="example/File2.xml" />
</pack>
</packs>
</code></pre>
<p>File2.xml</p>
<pre><code><xfragment>
<file src="..." />
</xfragment>
</code></pre>
<p>File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)</p>
<p>What I am looking to have produced:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<file src="..." />
</pack>
</packs>
</code></pre>
<p>Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer. </p>
<p>Tim Reynolds</p>
| [{'answer_id': 73306, 'author': 'Paul de Vrieze', 'author_id': 4100, 'author_profile': 'https://Stackoverflow.com/users/4100', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure if java supports automatic xinclude. But you will have to use namespaces to make it work. So don\'t use <code><xinclude ....></code>, but use: </p>\n\n<pre><code><xi:xinclude xmlns:xi="http://www.w3.org/2001/XInclude" href="example/File2.xml" />\n</code></pre>\n\n<p>Normally the included file should still contain the xml header as well. There is no requirement for it to e.g. have the same encoding.</p>\n'}, {'answer_id': 74275, 'author': 'Brian Agnew', 'author_id': 12960, 'author_profile': 'https://Stackoverflow.com/users/12960', 'pm_score': 1, 'selected': False, 'text': '<p>If you can\'t get xinclude to work and you\'re using Ant, I\'d recommend <a href="http://www.oopsconsultancy.com/software/xmltask" rel="nofollow noreferrer">XMLTask</a>, which is a plugin task for Ant. It\'ll do lots of clever stuff, including the one thing you\'re interested in - constructing a XML file out of fragments.</p>\n\n<p>e.g.</p>\n\n<pre><code><xmltask source="templatefile.xml" dest="finalfile.xml">\n <insert path="/packs/pack[1]" position="under" file="pack1.xml"/>\n</xmltask>\n</code></pre>\n\n<p>(warning- the above is done from memory so please consult the documentation!).</p>\n\n<p>Note that in the above, the file <em>pack1.xm</em>l doesn\'t have to have a root node.</p>\n'}, {'answer_id': 534077, 'author': 'mattwright', 'author_id': 33106, 'author_profile': 'https://Stackoverflow.com/users/33106', 'pm_score': 0, 'selected': False, 'text': '<p>Apache Xerces, for example, should support Xinclude, but you will need to enable it.</p>\n\n<p><a href="http://xerces.apache.org/xerces2-j/faq-xinclude.html" rel="nofollow noreferrer">http://xerces.apache.org/xerces2-j/faq-xinclude.html</a></p>\n\n<pre><code>import javax.xml.parsers.SAXParserFactory;\n\nSAXParserFactory spf = SAXParserFactory.newInstance();\nspf.setNamespaceAware(true);\nspf.setXIncludeAware(true);\n</code></pre>\n\n<p>Their documentation also says you can enable it as a <a href="http://xerces.apache.org/xerces2-j/features.html#xinclude" rel="nofollow noreferrer">feature</a></p>\n'}, {'answer_id': 1302238, 'author': 'denny', 'author_id': 159557, 'author_profile': 'https://Stackoverflow.com/users/159557', 'pm_score': 0, 'selected': False, 'text': '<p>This works now:</p>\n\n<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>\n<installation version="1.0">\n<packs> \n <pack name="Transaction Service" id="Transaction Service" required="no" >\n <xi:include href="example/File2.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />\n </pack>\n</packs>\n</code></pre>\n\n<p>example/File2.xml</p>\n\n<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>\n<xfragment>\n <file src="..." />\n</xfragment>\n</code></pre>\n'}, {'answer_id': 27536996, 'author': 'matfud', 'author_id': 4372321, 'author_profile': 'https://Stackoverflow.com/users/4372321', 'pm_score': 0, 'selected': False, 'text': '<p>Just for anyone who wants to know. IzPack used nanoXML to parse all config files. It does not have namespaces. And does not handle xml includes.</p>\n\n<p>To resolve an issue I had I added the "xinclude" etc (fragment/fallback) element to the parser stuff so that it that mostly followed the standards for x:include (notice the name difference?) One is correct and has a namespace. The other is a nasty hack that pretends to follow the standard without using namespaces.</p>\n\n<p>Anyway this is long ago and now IzPack uses a sane XML parser and understands if you do it correctly xi:include or whatever prefix you wish to use there are no problems. It is standard in decent xml parsers.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/72996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
73,000 | <p>I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds <strong>all</strong> IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they <em>see</em> dialog on top of IE but it looks like it has hanged since it is not refreshe). </p>
<p>So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. </p>
<p>Here's the code:</p>
<pre><code> PassDialog dialog = new PassDialog(parent);
/* do some non gui related initialization */
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
</code></pre>
<p>Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: </p>
<pre><code>parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
</code></pre>
| [{'answer_id': 73214, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 0, 'selected': False, 'text': '<p>You might try launching a modal from JavaScript using the JavaScript integration (see <a href="http://www.raditha.com/java/mayscript.php" rel="nofollow noreferrer">http://www.raditha.com/java/mayscript.php</a> for an example). </p>\n\n<p>The JavaScript you would need would be something like:</p>\n\n<pre><code>function getPassword() {\n return prompt("Enter Password");\n}\n</code></pre>\n\n<p>And the Java would be:</p>\n\n<pre><code>password = jso.call("getPassword", new String[0]);\n</code></pre>\n\n<p>Unfortunately that means giving up all hope of having a nice looking modal. Good luck!</p>\n'}, {'answer_id': 73525, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 1, 'selected': False, 'text': '<p>Make a background Thread that calls toFront on the Dialog every 2 seconds.\nCode that we use (I hope I got everything):</p>\n\n<pre><code>class TestClass {\nprotected void toFrontTimer(JFrame frame) {\n try {\n bringToFrontTimer = new java.util.Timer();\n bringToFrontTask = new BringToFrontTask(frame);\n bringToFrontTimer.schedule( bringToFrontTask, 300, 300);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n}\n\nclass BringToFrontTask extends TimerTask {\n private Frame frame;\n public BringToFrontTask(Frame frame) {\n this.frame = frame;\n }\n public void run()\n {\n if(count < 2) {\n frame.toFront();\n } else {\n cancel();\n }\n count ++;\n }\n private int count = 0;\n}\n\npublic void cleanup() {\n if(bringToFrontTask != null) {\n bringToFrontTask.cancel();\n bringToFrontTask = null;\n }\n if(bringToFrontTimer != null) {\n bringToFrontTimer = null;\n }\n}\n\njava.util.Timer bringToFrontTimer = null;\njava.util.TimerTask bringToFrontTask = null;\n}\n</code></pre>\n'}, {'answer_id': 73615, 'author': 'Joel Anair', 'author_id': 7441, 'author_profile': 'https://Stackoverflow.com/users/7441', 'pm_score': 1, 'selected': False, 'text': "<p>This is a shot in the dark as I'm not familiar with applets, but you could take a look at IE's built-in window.showModalDialog method. It's fairly easy to use. Maybe a combination of this and Noah's suggestion?</p>\n"}, {'answer_id': 93914, 'author': 'shemnon', 'author_id': 8020, 'author_profile': 'https://Stackoverflow.com/users/8020', 'pm_score': 2, 'selected': True, 'text': '<p>What argument are you using for the parent?</p>\n\n<p>You may have better luck if you use the parent of the Applet.</p>\n\n<pre><code>javax.swing.SwingUtilities.getWindowAncestor(theApplet)\n</code></pre>\n\n<p>Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7918/'] |
73,008 | <p>We have several wizard style form applications on our website where we capture information from the user on each page and then submit to a backend process using a web service.</p>
<p>Unfortunately we can't submit the information in chunks during each form submission so we have to store it the users session until the end of the process and submit it all at the same time.</p>
<p>Is the amount of server memory/sql server disk space the only constraint on how much I can store in users sessions or is there something else I need to consider?</p>
<p>Edit: The site is built on ASP.NET web forms.</p>
| [{'answer_id': 73055, 'author': 'mmattax', 'author_id': 1638, 'author_profile': 'https://Stackoverflow.com/users/1638', 'pm_score': 0, 'selected': False, 'text': '<p>If you use a traditional HTTP model (i.e. don\'t use runat="server") you can post the data to another asp page and place the posted data into hidden form elements, you can do this for however many pages you need thus avoiding placing anything in a session variable. </p>\n'}, {'answer_id': 73158, 'author': 'Toby Mills', 'author_id': 12377, 'author_profile': 'https://Stackoverflow.com/users/12377', 'pm_score': 3, 'selected': True, 'text': '<p>Assuming the information is not sensitive then you could store the information in a cookie which would reduce the amount of information required to be stored server side. This would also allow you to access the information via JavaScript. </p>\n\n<p>Alternatively you could use the viewstate to store the information although this can lead to large amounts of data being sent between the server and the client and not my preferred solution.</p>\n\n<p>The amount of session information you should store varies wildly depending on the application, number of expected users, server specification etc. To give a more accurate answer would require more information :)</p>\n\n<p>Finally, assuming that the information collected throughout the process is not required from page to page then you could store all the information in a database table and only store the records unique id in the session. As each page is submitted the db record is updated and then on the final page all the information is retrieved and submitted. This is not an idea solution if you need to retrieve previous information on each subsequent page due to the number of db reads required.</p>\n'}, {'answer_id': 73381, 'author': 'mmattax', 'author_id': 1638, 'author_profile': 'https://Stackoverflow.com/users/1638', 'pm_score': 2, 'selected': False, 'text': '<p>You could also have 1 asp page with the entire html form, and hide parts of it until the user fill and "submits" the visible part...</p>\n\n<p>then simply hide the part that is filled out and show the next part of the form...</p>\n\n<p>This would be extremely easy in the .NET framework, use panels for each "wizard step" and add loggic when to display and hide each panel.</p>\n\n<p>you will then have all the data on one page. </p>\n'}, {'answer_id': 73633, 'author': 'amitm', 'author_id': 9149, 'author_profile': 'https://Stackoverflow.com/users/9149', 'pm_score': 0, 'selected': False, 'text': '<p>Since it is problematic from performance point of view to store large amounts of data in user Session object, ASP.Net provides some other workarounds on top of what is mentioned in the posts above. <a href="http://msdn.microsoft.com/en-us/library/014bec1k.aspx" rel="nofollow noreferrer">ASP.NET Profile Provider</a> allows you to persist session related information in a database. You can also use <a href="http://msdn.microsoft.com/en-us/library/ms972429.aspx" rel="nofollow noreferrer">Session State Server</a> which uses a separate server to store all Session information. Both of these situations take into account if you need to use clusters or load balancers, the servers can still recognize the session information across different servers. If you store information in the Http Session object, you run into the problem that one user must always go to the same server for that session. </p>\n'}, {'answer_id': 1051434, 'author': 'Axl', 'author_id': 16605, 'author_profile': 'https://Stackoverflow.com/users/16605', 'pm_score': 0, 'selected': False, 'text': '<p>Session, viewstate, database. These are all slow but will get the job done.</p>\n\n<p>Hidden form fields is the answer I like best.</p>\n\n<p>There are other ways to persist state. Cookies, popup window, frameset or iframes.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1762/'] |
73,022 | <p>What is the difference between <strong>CodeFile</strong>="file.ascx.cs" and <strong>CodeBehind</strong>="file.ascx.cs" in the declaration of a ASP.NET user control?</p>
<p>Is one newer or recommended? Or do they have specific usage?</p>
| [{'answer_id': 901329, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Codebehind file need to compile before run but in src we dont need to compile and then run.. just save the file.</p>\n'}, {'answer_id': 954873, 'author': 'Shafqat Ahmed', 'author_id': 115176, 'author_profile': 'https://Stackoverflow.com/users/115176', 'pm_score': 8, 'selected': True, 'text': "<p><strong>CodeBehind</strong>: Needs to be compiled (ASP.NET 1.1 model). The compiled binary is placed in the bin folder of the website. You need to do a compile in Visual Studio before you deploy. It's a good model when you don't want the source code to be viewable as plain text. For example when delivering to a customer to whom you don't have an obligation to provide code.</p>\n\n<p><strong>CodeFile</strong>: You provide the source file with the solution for deployment. ASP.NET 2.0 runtime compiles the code when needed. The compiled files are at Microsoft.NET[.NET version]\\Temporary ASP.NET Files. </p>\n"}, {'answer_id': 17006133, 'author': 'DavidHyogo', 'author_id': 341180, 'author_profile': 'https://Stackoverflow.com/users/341180', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m working with an Application Project in Visual Studio Express 2012 For Web and using .NET 4.0. In the code behind files for my login and change password pages I found a situation where I needed both CodeBehind and CodeFile in the declaration.</p>\n\n<p>If I don\'t add a code file reference like</p>\n\n<pre><code>CodeFile=login.aspx.cs\n</code></pre>\n\n<p>The web page doesn\'t parse and the browser displays a parser error. It doesn\'t matter whether I compile the project or not.</p>\n\n<p>If I don\'t add a code behind reference like</p>\n\n<pre><code>CodeBehind=login.aspx.cs\n</code></pre>\n\n<p>References to Security classes like MembershipUser fail both at compile time and when attempting to use intellisense with an error like "The type or namespace MembershipUser cannot be found". I have added a reference to System.Web.ApplicationServices as required by the .Net 4.0 framework. </p>\n\n<p>I should add that these troublesome files are running in an application within the website created using the IIS Application tool. When I open the website from Visual Studio I have no difficulty with parser errors or reference errors. This confusion only occurs when I open the application as a project in Visual Studio.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3420/'] |
73,024 | <p>This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why <code>delegate(0)</code> accomplishes this, in the kind of simple terms I can understand.</p>
<pre><code>xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
</code></pre>
| [{'answer_id': 73040, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 0, 'selected': False, 'text': '<p>That is creating an anonymous function. This feature was introduced in C# 2.0</p>\n'}, {'answer_id': 73066, 'author': 'André Chalella', 'author_id': 4850, 'author_profile': 'https://Stackoverflow.com/users/4850', 'pm_score': 0, 'selected': False, 'text': "<p>It serves as an anonymous method, so you don't need to declare it somewhere else. It's very useful.</p>\n\n<p>What it does in that case is to attach that method to the list of actions that are triggered because of the <code>onLogin</code> event.</p>\n"}, {'answer_id': 73069, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s exactly the same as</p>\n\n<pre><code>xmpp.OnLogin += EventHandler(MyMethod);\n</code></pre>\n\n<p>Where MyMethod is</p>\n\n<pre><code>public void MyMethod(object o) \n{ \n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); \n}\n</code></pre>\n'}, {'answer_id': 73083, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 2, 'selected': True, 'text': '<p>The <code>delegate(object o){..}</code> tells the compiler to package up whatever is inside the brackets as an object to be executed later, in this case when <code>OnLogin</code> is fired. Without the <code>delegate()</code> statement, the compiler would think you are tying to execute an action in the middle of an assignemnt statement and give you errors.</p>\n'}, {'answer_id': 73088, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 0, 'selected': False, 'text': '<p>Agreed with Abe, this is an anonymous method. An anonymous method is just that -- a method without a name, which can be supplied as a parameter argument.</p>\n\n<p>Obviously the OnLogin object is an Event; using an += operator ensures that the method specified by the anonymous delegate above is executed whenever the OnLogin event is raised.</p>\n'}, {'answer_id': 73092, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 0, 'selected': False, 'text': '<p>Basically, the code inside the {} will run when the "OnLogin" event of the xmpp event is fired. Based on the name, I\'d guess that event fires at some point during the login process.</p>\n\n<p>The syntax:</p>\n\n<pre><code>delegate(object o) { statements; }\n</code></pre>\n\n<p>is a called an anonymous method. The code in your question would be equivilent to this:</p>\n\n<pre><code>public class MyClass\n{\n private XMPPObjectType xmpp;\n public void Main()\n {\n xmpp.OnLogin += MyMethod;\n }\n private void MyMethod(object o)\n {\n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?"));\n }\n}\n</code></pre>\n'}, {'answer_id': 73103, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 0, 'selected': False, 'text': '<p>You are subscribing to the OnLogin event in xmpp.</p>\n\n<p>This means that when xmpp fires this event, the code inside the anonymous delegate will fire. Its an elegant way to have callbacks.</p>\n\n<p>In Xmpp, something like this is going on:</p>\n\n<pre><code> // Check to see if we should fire the login event\n // ALso check to see if anything is subscribed to OnLogin \n // (It will be null otherwise)\n if (loggedIn && OnLogin != null)\n {\n // Anyone subscribed will now receive the event.\n OnLogin(this);\n }\n</code></pre>\n'}, {'answer_id': 73137, 'author': 'Remi Despres-Smyth', 'author_id': 8169, 'author_profile': 'https://Stackoverflow.com/users/8169', 'pm_score': 2, 'selected': False, 'text': '<p>As Abe noted, this code is creating an anonymous function. This:</p>\n\n<pre><code>\nxmpp.OnLogin += delegate(object o) \n { \n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); \n };\n</code></pre>\n\n<p>would have been accomplished as follows in older versions of .Net (I\'ve excluded class declarations and such, and just kept the essential elements):</p>\n\n<pre><code>\ndelegate void OnLoginEventHandler(object o);\n\npublic void MyLoginEventHandler(object o)\n{\n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); \n}\n\n[...]\n\nxmpp.OnLogin += new OnLoginEventHandler(MyLoginEventHandler);\n</code></pre>\n\n<p>What you\'re doing in either case is associating a method of yours to run when the xmpp OnLogin event is fired.</p>\n'}, {'answer_id': 73254, 'author': 'Romain Verdier', 'author_id': 4687, 'author_profile': 'https://Stackoverflow.com/users/4687', 'pm_score': 2, 'selected': False, 'text': '<p><code>OnLogin</code> on xmpp is probably an event declared like this :</p>\n\n<pre><code>public event LoginEventHandler OnLogin;\n</code></pre>\n\n<p>where <code>LoginEventHandler</code> is as delegate type probably declared as :</p>\n\n<pre><code>public delegate void LoginEventHandler(Object o);\n</code></pre>\n\n<p>That means that in order to subscribe to the event, you need to provide a method (or an <a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx" rel="nofollow noreferrer">anonymous method</a> / <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambda expression</a>) which match the <code>LoginEventHandler</code> delegate signature.</p>\n\n<p>In your example, you pass an anonymous method using the <code>delegate</code> keyword:</p>\n\n<pre><code>xmpp.OnLogin += delegate(object o)\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n "Hello, how are you?")); \n };\n</code></pre>\n\n<p>The anonymous method matches the delegate signature expected by the <code>OnLogin</code> event (void return type + one object argument). You could also remove the <code>object o</code> parameter leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms173174(VS.80).aspx" rel="nofollow noreferrer">contravariance</a>, since it is not used inside the anonymous method body.</p>\n\n<pre><code>xmpp.OnLogin += delegate\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n "Hello, how are you?")); \n };\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7574/'] |
73,029 | <p>I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.</p>
<p>That's why I need to serve servlets and html (login.html) under the same context
to make authentication work. I don't want to secure the hole application since
different context should need different roles. The jetty javadoc states that a
ContextHandlerCollection can handle different handlers for one context but I don't
get it to work. My sample ignoring the authentication stuff will not work, why?</p>
<pre><code>ContextHandlerCollection contexts = new ContextHandlerCollection();
// serve html
Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS);
ctxADocs.setResourceBase("d:\\tmp\\ctxA");
ServletHolder ctxADocHolder= new ServletHolder();
ctxADocHolder.setInitParameter("dirAllowed", "false");
ctxADocHolder.setServlet(new DefaultServlet());
ctxADocs.addServlet(ctxADocHolder, "/");
// serve a sample servlet
Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS);
ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda");
ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/");
contexts.setHandlers(new Handler[]{ctxA, ctxADocs});
// end of snippet
</code></pre>
<p>Any helpful thought is welcome!</p>
<p>Thanks.</p>
<p>Okami</p>
| [{'answer_id': 91072, 'author': 'Eduard Wirch', 'author_id': 17428, 'author_profile': 'https://Stackoverflow.com/users/17428', 'pm_score': 1, 'selected': False, 'text': '<p>Use the web application descriptor:</p>\n\n<p>Paste this in to your web.xml:</p>\n\n<pre><code><login-config>\n <auth-method>BASIC</auth-method>\n</login-config>\n<security-role>\n <role-name>MySiteRole</role-name>\n</security-role>\n\n<security-constraint>\n <display-name>ProtectEverything</display-name>\n <web-resource-collection>\n <web-resource-name>ProtectEverything</web-resource-name>\n <url-pattern>*.*</url-pattern>\n <url-pattern>/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>MySiteRole</role-name>\n </auth-constraint>\n</security-constraint>\n\n<security-constraint>\n <web-resource-collection>\n <web-resource-name>ExcludeLoginPage</web-resource-name>\n <url-pattern>/login.html</url-pattern>\n </web-resource-collection>\n <user-data-constraint>\n <transport-guarantee>NONE</transport-guarantee>\n </user-data-constraint>\n</security-constraint>\n</code></pre>\n\n<p>Without authentication this will hide everything but the login.html.</p>\n'}, {'answer_id': 114336, 'author': 'Okami', 'author_id': 11450, 'author_profile': 'https://Stackoverflow.com/users/11450', 'pm_score': 2, 'selected': False, 'text': "<p>Finally I got it right, solution is to use latest jetty 6.1.12 rc2.\nI didn't check out what they changed - I'm just happy that it works now.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11450/'] |
73,032 | <p>I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.</p>
<p>I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:</p>
<pre><code>ordered_list = [[1, 2], [1, 1], [2, 1]]
</code></pre>
<p>Any suggestions?</p>
<p>Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:</p>
<pre><code>ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
</code></pre>
| [{'answer_id': 73090, 'author': 'Brian Phillips', 'author_id': 7230, 'author_profile': 'https://Stackoverflow.com/users/7230', 'pm_score': 6, 'selected': True, 'text': '<p>How about:</p>\n\n<pre>\n<code>\nordered_list = [[1, "b"], [1, "a"], [2, "a"]]\nordered_list.sort! do |a,b|\n [a[0],b[1]] <=> [b[0], a[1]]\nend\n</code>\n</pre>\n'}, {'answer_id': 73496, 'author': 'glenn mcdonald', 'author_id': 7919, 'author_profile': 'https://Stackoverflow.com/users/7919', 'pm_score': 2, 'selected': False, 'text': '<p>I had this same basic problem, and solved it by adding this:</p>\n\n<pre><code>class Inverter\n attr_reader :o\n\n def initialize(o)\n @o = o\n end\n\n def <=>(other)\n if @o.is && other.o.is\n -(@o <=> other.o)\n else\n @o <=> other.o\n end\n end\nend\n</code></pre>\n\n<p>This is a wrapper that simply inverts the <=> function, which then allows you to do things like this:</p>\n\n<pre><code>your_objects.sort_by {|y| [y.prop1,Inverter.new(y.prop2)]}\n</code></pre>\n'}, {'answer_id': 76148, 'author': 'mislav', 'author_id': 11687, 'author_profile': 'https://Stackoverflow.com/users/11687', 'pm_score': 2, 'selected': False, 'text': '<p><code>Enumerable#multisort</code> is a generic solution that can be applied to arrays of <strong>any size</strong>, not just those with 2 items. Arguments are booleans that indicate whether a specific field should be sorted ascending or descending (usage below):</p>\n\n<pre><code>items = [\n [3, "Britney"],\n [1, "Corin"],\n [2, "Cody"],\n [5, "Adam"],\n [1, "Sally"],\n [2, "Zack"],\n [5, "Betty"]\n]\n\nmodule Enumerable\n def multisort(*args)\n sort do |a, b|\n i, res = -1, 0\n res = a[i] <=> b[i] until !res.zero? or (i+=1) == a.size\n args[i] == false ? -res : res\n end\n end\nend\n\nitems.multisort(true, false)\n# => [[1, "Sally"], [1, "Corin"], [2, "Zack"], [2, "Cody"], [3, "Britney"], [5, "Betty"], [5, "Adam"]]\nitems.multisort(false, true)\n# => [[5, "Adam"], [5, "Betty"], [3, "Britney"], [2, "Cody"], [2, "Zack"], [1, "Corin"], [1, "Sally"]]\n</code></pre>\n'}, {'answer_id': 3275140, 'author': 'Alex Fortuna', 'author_id': 243424, 'author_profile': 'https://Stackoverflow.com/users/243424', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve been using Glenn\'s recipe for quite a while now. Tired of copying code from project to project over and over again, I\'ve decided to make it a gem:</p>\n\n<p><a href="http://github.com/dadooda/invert" rel="nofollow noreferrer">http://github.com/dadooda/invert</a></p>\n'}, {'answer_id': 11320778, 'author': 'TwoByteHero', 'author_id': 1311787, 'author_profile': 'https://Stackoverflow.com/users/1311787', 'pm_score': 3, 'selected': False, 'text': "<p>I was having a nightmare of a time trying to figure out how to reverse sort a specific attribute but normally sort the other two. Just a note about the sorting for those that come along after this and are confused by the |a,b| block syntax. You cannot use the <code>{|a,b| a.blah <=> b.blah}</code> block style with <code>sort_by!</code> or <code>sort_by</code>. It must be used with <code>sort!</code> or <code>sort</code>. Also, as indicated previously by the other posters swap <code>a</code> and <code>b</code> across the comparison operator <code><=></code> to reverse the sort order. Like this:</p>\n\n<p>To sort by blah and craw normally, but sort by bleu in reverse order do this:</p>\n\n<pre><code>something.sort!{|a,b| [a.blah, b.bleu, a.craw] <=> [b.blah, a.bleu, b.craw]}\n</code></pre>\n\n<p>It is also possible to use the <code>-</code> sign with <code>sort_by</code> or <code>sort_by!</code> to do a reverse sort on numerals (as far as I am aware it only works on numbers so don't try it with strings as it just errors and kills the page). </p>\n\n<p>Assume <code>a.craw</code> is an integer. For example:</p>\n\n<pre><code>something.sort_by!{|a| [a.blah, -a.craw, a.bleu]}\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3230/'] |
73,037 | <p>This is a 3 part question regarding embedded RegEx into SQL statements. </p>
<ol>
<li><p>How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?</p></li>
<li><p>What is the performance impact if used within a
mission critical business
transaction?</p></li>
<li><p>Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?</p></li>
</ol>
<hr>
<p>Dear Larry :</p>
<p>Thank you for using ABC's alert service.</p>
<p>ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.</p>
<p>ENTITY NAME: Oracle Systems, LLC</p>
<p>PREVIOUS STATUS: --</p>
<p>CURRENT STATUS: DELINQUENT</p>
<p>As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.</p>
<p>Kind regards,</p>
<p>Service Team 1
ABC</p>
<p>--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--</p>
<p>Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based.</p>
| [{'answer_id': 73084, 'author': 'Matt Rogish', 'author_id': 2590, 'author_profile': 'https://Stackoverflow.com/users/2590', 'pm_score': 0, 'selected': False, 'text': '<p>Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightforward (and portable, since it\'s supported in older versions).</p>\n\n<p><a href="http://www.techonthenet.com/oracle/functions/instr.php" rel="nofollow noreferrer">http://www.techonthenet.com/oracle/functions/instr.php</a> and <a href="http://www.adp-gmbh.ch/ora/sql/substr.html" rel="nofollow noreferrer">http://www.adp-gmbh.ch/ora/sql/substr.html</a></p>\n\n<p><a href="http://www.databasejournal.com/features/mssql/article.php/3071531" rel="nofollow noreferrer">http://www.databasejournal.com/features/mssql/article.php/3071531</a> and <a href="http://msdn.microsoft.com/en-us/library/ms187748.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187748.aspx</a></p>\n'}, {'answer_id': 73336, 'author': 'Gary Russo', 'author_id': 3048, 'author_profile': 'https://Stackoverflow.com/users/3048', 'pm_score': 0, 'selected': False, 'text': "<p>INSTR and CHARINDEX are great alternative approaches but I'd like to explore the benefits of embedding Regex.</p>\n"}, {'answer_id': 74827, 'author': 'WIDBA', 'author_id': 10868, 'author_profile': 'https://Stackoverflow.com/users/10868', 'pm_score': 0, 'selected': False, 'text': '<p>In MS SQL you can use LIKE which has some "pattern matching" in it. I would guess Oracle has something similar. Its not Regex, but has some of the matching capabilities. (Note: its not particularly fast).. Fulltext searching could also be an option (again MS SQL) (probably a much faster way in the context of a good sized database)</p>\n'}, {'answer_id': 78318, 'author': 'Sergey Stadnik', 'author_id': 10557, 'author_profile': 'https://Stackoverflow.com/users/10557', 'pm_score': 2, 'selected': True, 'text': '<p>Why would you need regular expressions here?\nINSTR and SUBSTR will do the job perfectly.</p>\n\n<p>But if you convinced you need Regex\'es you can use:</p>\n\n<p><a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions129.htm#i1239887" rel="nofollow noreferrer">REGEXP_INSTR</a><br>\n<a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions130.htm#i1305521" rel="nofollow noreferrer">REGEXP_REPLACE</a><br>\n<a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions131.htm#i1239858" rel="nofollow noreferrer">REGEXP_SUBSTR</a> </p>\n\n<p>(only available in Oracle 10g and up)</p>\n\n<pre><code>SELECT emp_id, text\n FROM employee_comment\n WHERE REGEXP_LIKE(text,\'...-....\');\n</code></pre>\n'}, {'answer_id': 152118, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 1, 'selected': False, 'text': '<p>If I recall correctly, it is possible to write a UDF in c#/vb for SQL Server. \nHere\'s a link, though possibly not the best: <a href="http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm" rel="nofollow noreferrer">http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3048/'] |
73,039 | <p>In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.</p>
<p>I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").</p>
<p>Some references I've read:<br>
- <a href="http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread" rel="nofollow noreferrer">MSDN</a><br>
- <a href="http://aspalliance.com/329" rel="nofollow noreferrer">Fire and Forget</a></p>
<p>So my question is - what is the best method?</p>
<p>UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.</p>
| [{'answer_id': 73082, 'author': 'kemiller2002', 'author_id': 1942, 'author_profile': 'https://Stackoverflow.com/users/1942', 'pm_score': 1, 'selected': False, 'text': "<p>I ran into this exact problem at my last job. The best way I found was to fire off an asychronous process, and notify the user when it's done (email or something else). Making them wait that long is going to be problematic because of timeouts and wasted productivity for them. Having them wait for a progress bar can give them false sense of security that they can cancel the process when they close the browser which may not be the case depending on how you set up the system. </p>\n"}, {'answer_id': 73148, 'author': 'ahin4114', 'author_id': 11579, 'author_profile': 'https://Stackoverflow.com/users/11579', 'pm_score': 0, 'selected': False, 'text': "<ol>\n<li>How are you querying the remote data?</li>\n<li>How often does it change?</li>\n<li>Are the results something that could be cached for a period of time?</li>\n<li>How long a period of time are we actually talking about here?</li>\n</ol>\n\n<p>The 'best method' is likely to depend in some way on the answers to these questions...</p>\n"}, {'answer_id': 73170, 'author': 'wile.e.coyote', 'author_id': 12542, 'author_profile': 'https://Stackoverflow.com/users/12542', 'pm_score': 2, 'selected': False, 'text': '<p>We had a similar issue and solved it by starting the work via an asychronous web service call (which meant that the user did not have to wait for the work to finish). The web service then started a SQL Job which performed the work and periodically updated a table with the status of the work. We provided a UI which allowed the user to query the table.</p>\n'}, {'answer_id': 73171, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can create another thread and store a reference to the thread in the session or application state, depending on wether the thread can run only once per website, or once per user session.<br />\nYou can then redirect the user to a page where he can monitor the threads progress. You can set the page to refresh automatically, or display a refresh button to the user.<br />\nUpon completion of the thread, you can send an email to the user.</p>\n'}, {'answer_id': 73177, 'author': 'DevelopingChris', 'author_id': 1220, 'author_profile': 'https://Stackoverflow.com/users/1220', 'pm_score': 0, 'selected': False, 'text': '<p>My solution to this, has been an out of band service that does these and caches them in db.</p>\n\n<p>When the person asks for something the first time, they get a bit of a wait, and then it shows up but if they refresh, its immediate, and then, because its int he db, its now part of the hourly update for the next 24 hours from the last request.</p>\n'}, {'answer_id': 73428, 'author': 'Dave Ward', 'author_id': 60, 'author_profile': 'https://Stackoverflow.com/users/60', 'pm_score': 4, 'selected': True, 'text': '<p>To avoid excessive architecture astronomy, I often <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">use a hidden iframe to call the long running process and stream back progress information</a>. Coupled with something like <a href="http://www.bram.us/demo/projects/jsprogressbarhandler/" rel="nofollow noreferrer">jsProgressBarHandler</a>, you can pretty easily create great out-of-band progress indication for longer tasks where a generic progress animation doesn\'t cut it.</p>\n\n<p>In your specific situation, you may want to use one LongRunningProcess.aspx call per task, to avoid those page timeouts. </p>\n\n<p>For example, call LongRunningProcess.aspx?taskID=1 to kick it off and then at the end of that task, emit a </p>\n\n<pre><code>document.location = "LongRunningProcess.aspx?taskID=2". \n</code></pre>\n\n<p>Ad nauseum.</p>\n'}, {'answer_id': 73485, 'author': 'tbone', 'author_id': 8678, 'author_profile': 'https://Stackoverflow.com/users/8678', 'pm_score': 0, 'selected': False, 'text': '<p>Add the job, with its relevant parameters, to a job queue table. Then, write a windows service that will pick up these jobs and process them, save the results to an appropriate location, and email the requester with a link to the results. It is also a nice touch to give some sort of a UI so the user can check the status of their job(s).</p>\n\n<p>This way is much better than launching a seperate thread or increasing the timeout, especially if your application is larger and needs to scale, as you can simply add multiple servers to process jobs if necessary.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12442/'] |
73,045 | <p>I'm not talking about how to indent here. I'm looking for suggestions about the best way of organizing the chunks of code in a source file.</p>
<p>Do you arrange methods alphabetically? In the order you wrote them? Thematically? In some kind of 'didactic' order?</p>
<p>What organizing principles do you follow? Why?</p>
| [{'answer_id': 73081, 'author': 'Marc Gear', 'author_id': 6563, 'author_profile': 'https://Stackoverflow.com/users/6563', 'pm_score': 3, 'selected': False, 'text': "<p>i normally order by the following</p>\n\n<ol>\n<li>constructors</li>\n<li>destructors</li>\n<li>getters</li>\n<li>setters</li>\n<li>any 'magic' methods </li>\n<li>methods for changing the persisted state of reciever (save() etc)</li>\n<li>behaviors</li>\n<li>public helper methods</li>\n<li>private/protected helper methods</li>\n<li>anything else (although if there is anything else its normally a sign that some refactoring is necessary)</li>\n</ol>\n"}, {'answer_id': 73089, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': 0, 'selected': False, 'text': '<p>I group them based on what there doing, and then in the order I wrote them (alphabetically would probs be better though)</p>\n\n<p>eg in texture.cpp I have:</p>\n\n<pre><code>//====(DE)CONSTRUCTOR====\n...\n//====LOAD FUNCTIONS====\n...\n//====SAVE FUNCTIONS====\n...\n//====RESOURCE MANGEMENT FUNCTIONS====\n//(preventing multiple copies being loaded etc)\n...\n//====UTILL FUNCTIONS====\n//getting texture details, etc\n...\n//====OVERLOADED OPERTORS====\n....\n</code></pre>\n'}, {'answer_id': 73099, 'author': 'betelgeuce', 'author_id': 366182, 'author_profile': 'https://Stackoverflow.com/users/366182', 'pm_score': 0, 'selected': False, 'text': '<p>Pretty much use this approach for anything I am coding in. Good structure and well commented code makes good reading</p>\n\n<ul>\n<li>Global Variables </li>\n<li>Functions</li>\n<li>Main Body/Method</li>\n</ul>\n'}, {'answer_id': 73112, 'author': 'Allan Wind', 'author_id': 9706, 'author_profile': 'https://Stackoverflow.com/users/9706', 'pm_score': 0, 'selected': False, 'text': '<p>public, protected and then private and within each section alphabetically although I often list constructor first and deconstructor last.</p>\n\n<p>/Allan</p>\n'}, {'answer_id': 73115, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 0, 'selected': False, 'text': "<p>I tend to group things thematically for lack of a better word.</p>\n\n<p>For example, if I had a public method that used two private methods in the course of doing its work then I would group all three together in the implementation file since odds are good that if you're going to be looking at one of them then you'll need to look at one of the others.</p>\n\n<p>I also always group get/set methods for a particular class member.</p>\n\n<p>It's really personal preference, especially with modern IDEs since there are a lot of features that allow you to automatically jump to locations in the code.</p>\n"}, {'answer_id': 73118, 'author': 'David Smart', 'author_id': 9623, 'author_profile': 'https://Stackoverflow.com/users/9623', 'pm_score': 1, 'selected': False, 'text': '<p>I tend to group methods that relate to each other. Use of a good IDE removes much of this concern. Alphabetizing methods seems like a waste of effort to me.</p>\n'}, {'answer_id': 73121, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 0, 'selected': False, 'text': "<p>I like to keep things simple, so I don't stuff a bunch of methods in a class. Within a class, I usually have the most commonly used (or modified-by-me ;-)) methods listed first. As far as specific code organization goes, each set of methods belongs to a class, so it organizes by itself.</p>\n\n<p>I make use of my editor's search feature, and code folding to navigate through large source files. Similarly, I make use of search features to find things in other contexts too. A grand organization scheme never suited me, so I rely on the power of search in all things, not just code.</p>\n"}, {'answer_id': 73133, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Interesting point. I hadn't really thought about this.</p>\n\n<p>I tend to put frequently-accessed functions at the top (utility functions, and such), as they're most likely need tweaking.</p>\n\n<p>I don't think organization is particularly important, as I can find any function quickly. I don't scroll through my file to find a function; I search for it.</p>\n\n<p>In C++, I do expect that the functions in the .cpp file are in the same order in which they're declared in the .h file. Which is usually constructors, followed by destructors, followed by primary/central functionality functions, followed by utility functions.</p>\n"}, {'answer_id': 73195, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 2, 'selected': False, 'text': "<p>I tend to use following pattern:</p>\n\n<ul>\n<li>public static final variables</li>\n<li>static functions, static blocks </li>\n<li>variables </li>\n<li>constructors </li>\n<li>functions that do something related to logic</li>\n<li>getters and setters (are uninteresing mostly so there is no need to read them)</li>\n</ul>\n\n<p>I'm have no pattern of including local classes, and mostly I put them on top of first method that uses them. </p>\n\n<p>I don't like separating methods depending on access level. If some public method uses some private method they will be close to one another. </p>\n"}, {'answer_id': 74316, 'author': 'Kristian', 'author_id': 12911, 'author_profile': 'https://Stackoverflow.com/users/12911', 'pm_score': 0, 'selected': False, 'text': "<p>I mostly write C code and I tend to order by dependency. If possible I try to match my source code file with me header files, but generally it's if void a() uses int b(char *foo), than int b(char *foo) comes first.</p>\n\n<p>Saves me from adding entries to the header file for local functions.</p>\n\n<p>For the rest it's mainly alphabetic actually, makes searching easier.</p>\n"}, {'answer_id': 74515, 'author': 'user8806', 'author_id': 8806, 'author_profile': 'https://Stackoverflow.com/users/8806', 'pm_score': 0, 'selected': False, 'text': '<p>I have all the private fields, then the public, then the constructors, then the main, then the methods that main calls, in the order they are called.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423836/'] |
73,051 | <p>I need to run a stored procedure from a C# application.</p>
<p>I use the following code to do so:</p>
<pre><code>Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
</code></pre>
<p>From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).</p>
<p>How can I customize these return codes?</p>
<p>H.</p>
| [{'answer_id': 73108, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': True, 'text': '<p>If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at <code>SqlConnection</code> and <code>SqlCommand</code> in the <code>System.Data.SqlClient</code> namespace.</p>\n\n<p>Once you are calling the stored procedure via <code>SqlCommand</code> you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.</p>\n'}, {'answer_id': 73193, 'author': 'Ron Savage', 'author_id': 12476, 'author_profile': 'https://Stackoverflow.com/users/12476', 'pm_score': 2, 'selected': False, 'text': '<p>I have a small VB.Net app that executes system commands like that. To capture error or success conditions I define regular expressions to match the error text output from the command and I capture the output like this:</p>\n\n<pre><code> myprocess.Start()\n procReader = myprocess.StandardOutput()\n\n While (Not procReader.EndOfStream)\n procLine = procReader.ReadLine()\n\n If (MatchesRegEx(errRegEx, procLine)) Then\n writeDebug("Error reg ex: [" + errorRegEx + "] has matched: [" + procLine + "] setting hasError to true.")\n\n Me.hasError = True\n End If\n\n writeLog(procLine)\n End While\n\n procReader.Close()\n\n myprocess.WaitForExit(CInt(waitTime))\n</code></pre>\n\n<p>That way I can capture specific errors and also log all the output from the command in case I run across an unexpected error.</p>\n'}, {'answer_id': 77400, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': "<p>Even with windows authentication you can still use <code>SqlCommand</code> and <code>SqlConnection</code> to execute, and you don't have to re-invent the wheel for exception handling.</p>\n\n<p>A simple connection configuration and a single <code>SqlCommand</code> can execute it without issue.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12525/'] |
73,063 | <p>In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.</p>
<p>Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?</p>
| [{'answer_id': 73120, 'author': 'Tom Ritter', 'author_id': 8435, 'author_profile': 'https://Stackoverflow.com/users/8435', 'pm_score': 2, 'selected': False, 'text': "<p>If you can search for the word exactly, you can use a pair of keyboard shortcuts to do it quickly.</p>\n\n<p>Tools -> Options -> Enviroment -> Keyboard</p>\n\n<ul>\n<li>Edit.GoToFindResults1NextLocation</li>\n<li>EditorContextMenus.CodeWindow.Breakpoint.InsertBreakpoint</li>\n</ul>\n\n<p>Assign them to Control+Alt+F11 and F10 and you can go through all the results very quickly. I haven't found a shortcut for going to the next reference however.</p>\n"}, {'answer_id': 249501, 'author': 'Jeff Hillman', 'author_id': 3950, 'author_profile': 'https://Stackoverflow.com/users/3950', 'pm_score': 5, 'selected': True, 'text': '<p><strong><em>This answer does not work for Visual Studio 2015 or later. A more recent answer can be found <a href="https://stackoverflow.com/questions/38061627/how-do-i-add-debug-breakpoints-to-lines-displayed-in-a-find-results-window-in?rq=1">here</a>.</em></strong></p>\n\n<p>You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...</p>\n\n<p>Paste the following in the source editor:</p>\n\n<pre><code>Imports System\nImports System.IO\nImports System.Text.RegularExpressions\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module CustomMacros\n Sub BreakpointFindResults()\n Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1)\n\n Dim selection As TextSelection\n selection = findResultsWindow.Selection\n selection.SelectAll()\n\n Dim findResultsReader As New StringReader(selection.Text)\n Dim findResult As String = findResultsReader.ReadLine()\n\n Dim findResultRegex As New Regex("(?<Path>.*?)\\((?<LineNumber>\\d+)\\):")\n\n While Not findResult Is Nothing\n Dim findResultMatch As Match = findResultRegex.Match(findResult)\n\n If findResultMatch.Success Then\n Dim path As String = findResultMatch.Groups.Item("Path").Value\n Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item("LineNumber").Value)\n\n Try\n DTE.Debugger.Breakpoints.Add("", path, lineNumber)\n Catch ex As Exception\n \' breakpoints can\'t be added everywhere\n End Try\n End If\n\n findResult = findResultsReader.ReadLine()\n End While\n End Sub\nEnd Module\n</code></pre>\n\n<p>This example uses the results in the "Find Results 1" window; you might want to create an individual shortcut for each result window.</p>\n\n<p>You can create a keyboard shortcut by going to Tools|Options... and selecting <strong>Keyboard</strong> under the <strong>Environment</strong> section in the navigation on the left. Select your macro and assign any shortcut you like. </p>\n\n<p>You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the <strong>Macros</strong> section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.</p>\n'}, {'answer_id': 797454, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I needed something similar to disable all breakpoints and place a breakpoint on every "Catch ex as Exception". However, I expanded this a little so it will place a breakpoint at every occurance of the string you have selected. All you need to do with this is highlight the string you want to have a breakpoint on and run the macro. </p>\n\n<pre><code> Sub BreakPointAtString()\n\n Try\n DTE.ExecuteCommand("Debug.DisableAllBreakpoints")\n Catch ex As Exception\n\n End Try\n\n Dim tsSelection As String = DTE.ActiveDocument.Selection.text\n DTE.ActiveDocument.Selection.selectall()\n Dim AllText As String = DTE.ActiveDocument.Selection.Text\n\n Dim findResultsReader As New StringReader(AllText)\n Dim findResult As String = findResultsReader.ReadLine()\n Dim lineNum As Integer = 1\n\n Do Until findResultsReader.Peek = -1\n lineNum += 1\n findResult = findResultsReader.ReadLine()\n If Trim(findResult) = Trim(tsSelection) Then\n DTE.ActiveDocument.Selection.GotoLine(lineNum)\n DTE.ExecuteCommand("Debug.ToggleBreakpoint")\n End If\n Loop\n\nEnd Sub\n</code></pre>\n\n<p>Hope it works for you :)</p>\n'}, {'answer_id': 1631799, 'author': 'Dmytro', 'author_id': 194487, 'author_profile': 'https://Stackoverflow.com/users/194487', 'pm_score': 1, 'selected': False, 'text': '<p>Paul, thanks a lot, but I have the following error (message box), may be I need to restart my PC:</p>\n\n<pre><code>Error\n---------------------------\nError HRESULT E_FAIL has been returned from a call to a COM component.\n---------------------------\nOK \n---------------------------\n</code></pre>\n\n<p>I would propose the following solution that\'s very simple but it works for me</p>\n\n<pre><code>Sub BreakPointsFromSearch()\n Dim n As Integer = InputBox("Enter the number of search results")\n\n For i = 1 To n\n DTE.ExecuteCommand("Edit.GoToNextLocation")\n DTE.ExecuteCommand("Debug.ToggleBreakpoint") \n Next\nEnd Sub\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12113/'] |
73,072 | <p>Does anybody have links to site or pre built report running on the SQL Analysis Service provided by TFS2008?</p>
<p>Creating a meaningful Excel report or a new report sometime is a very boring and difficult taks, maybe finding a way to share reports could be a good idea?</p>
| [{'answer_id': 73304, 'author': 'Larry Smithmier', 'author_id': 4911, 'author_profile': 'https://Stackoverflow.com/users/4911', 'pm_score': 0, 'selected': False, 'text': '<p>If you are using SCRUM, this has Sprint reports and Product Burndown reports:</p>\n\n<p><a href="http://www.scrumforteamsystem.com/en/default.aspx" rel="nofollow noreferrer">http://www.scrumforteamsystem.com/en/default.aspx</a></p>\n'}, {'answer_id': 78897, 'author': 'granth', 'author_id': 11210, 'author_profile': 'https://Stackoverflow.com/users/11210', 'pm_score': 3, 'selected': True, 'text': '<p>Try this download: <a href="http://www.microsoft.com/downloads/details.aspx?familyid=a74486b2-f7db-4a85-97bd-46bf478bda60&displaylang=en" rel="nofollow noreferrer">Creating and Customizing TFS Reports</a>, it includes a few samples and some guidance. <a href="http://msdn.microsoft.com/en-us/library/cc487893.aspx" rel="nofollow noreferrer">More here</a>.</p>\n\n<p>Also try the <a href="http://blogs.msdn.com/buckh/archive/2006/09/09/tfs-reporting.aspx" rel="nofollow noreferrer">TFS Reporting Samples.zip</a> linked from this site. </p>\n\n<p>This site links to a large number of TFS reporting resources:\n<a href="http://blogs.msdn.com/teams_wit_tools/archive/2007/03/26/tfs-report-developer-resources.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/teams_wit_tools/archive/2007/03/26/tfs-report-developer-resources.aspx</a> </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11673/'] |
73,078 | <p>I'm convinced from <a href="http://www.masukomi.org/talks/unit_testing_talk_2/index.xul?data=slide_data.txt#page2" rel="nofollow noreferrer">this presentation</a> and other commentary here on the site that I need to learn to Unit Test. I also realize that there have been many questions about what unit testing is here. Each time I go to consider how it should be done in the application I am currently working on, I walk away confused. It is a xulrunner application application, and a lot of the logic is event-based - when a user clicks here, this action takes place.</p>
<p>Often the examples I see for testing are testing classes - they instantiate an object, give it mock data, then check the properties of the object afterward. That makes sense to me - but what about the non-object-oriented pieces?</p>
<p><a href="https://stackoverflow.com/questions/2364/what-is-your-experience-with-unit-testing-in-practice#2390">This guy mentioned</a> that GUI-based unit testing is difficult in most any testing framework, maybe that's the problem. The presentation linked above mentions that each test should only touch one class, one method at a time. That seems to rule out what I'm trying to do.</p>
<p>So the question - how does one unit testing procedural or event-based code? Provide a link to good documentation, or explain it yourself.</p>
<p>On a side note, I also have a challenge of not having found a testing framework that is set up to test xulrunner apps - it seems that the tools just aren't developed yet. I imagine this is more peripheral than my understanding the concepts, writing testable code, applying unit testing.</p>
| [{'answer_id': 73126, 'author': 'Joel Martinez', 'author_id': 5416, 'author_profile': 'https://Stackoverflow.com/users/5416', 'pm_score': 1, 'selected': False, 'text': '<p>The problem is that "event based programming" links far too much logic to the events. The way such a system should be designed is that there should be a subsystem that raises events (and you can write tests to ensure that these events are raised in the proper order). And there should be another subsystem that deals only with managing, say, the state of a form. And you can write a unit test that will verify that given the correct inputs (ie. events being raised), will set the form state to the correct values.</p>\n\n<p>Beyond that, the actual event handler that is raised from component 1, and calls the behavior on component 2 is just integration testing which can be done manually by a QA person.</p>\n'}, {'answer_id': 73156, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 2, 'selected': False, 'text': '<p>At first I would test events like this:</p>\n\n<pre><code>private bool fired;\n\nprivate void HandlesEvent(object sender, EventArgs e)\n{\n fired = true;\n } \n\npublic void Test()\n{\n class.FireEvent += HandlesEvent;\n class.PErformEventFiringAction(null, null);\n\n Assert.IsTrue(fired);\n}\n</code></pre>\n\n<p>And Then I discovered <a href="http://www.ayende.com/wiki/Rhino+Mocks+Events.ashx" rel="nofollow noreferrer">RhinoMocks</a>.\nRhinoMocks is a framework that creates mock objects and it also handles event testing. It may come in handy for your procedural testing as well.</p>\n'}, {'answer_id': 73169, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>An approach I've found helpful for procedural code is to use TextTest. It's not so much about unit testing, but it helps you do automated regression testing. The idea is that you have your application write a log then use texttest to compare the log before and after your changes. </p>\n"}, {'answer_id': 73239, 'author': 'David Arno', 'author_id': 7122, 'author_profile': 'https://Stackoverflow.com/users/7122', 'pm_score': 4, 'selected': True, 'text': '<p>The idea of unit testing is to test small sections of code with each test. In an event based system, one form of unit testing you could do, would be to test how your event handlers respond to various events. So your unit test might set an aspect of your program into a specific state, then call the event listener method directly, and finally test the subsequent state of of your program. </p>\n\n<p>If you plan on unit testing an event-based system, you will make your life a lot easier for yourself if you use the dependency injection pattern and ideally would go the whole way and use inversion of control (see <a href="http://martinfowler.com/articles/injection.html" rel="nofollow noreferrer">http://martinfowler.com/articles/injection.html</a> and <a href="http://msdn.microsoft.com/en-us/library/aa973811.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa973811.aspx</a> for details of these patterns)</p>\n\n<p>(thanks to pc1oad1etter for pointing out I\'d messed up the links)</p>\n'}, {'answer_id': 85890, 'author': 'Joe Schneider', 'author_id': 1541, 'author_profile': 'https://Stackoverflow.com/users/1541', 'pm_score': 0, 'selected': False, 'text': '<p>See the oft-linked <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="nofollow noreferrer" rel="nofollow noreferrer">Working Effectively with Legacy Code</a>. See the sections titled "My Application Is All API Calls" and "My Project is Not Object-Oriented. How Do I Make Safe Changes?". </p>\n\n<p>In C/C++ world (my experience) the best solution in practice is to use the linker "seam" and link against test doubles for all the functions called by the function under test. That way you don\'t change any of the legacy code, but you can still test it in isolation.</p>\n'}, {'answer_id': 107273, 'author': 'pc1oad1etter', 'author_id': 525, 'author_profile': 'https://Stackoverflow.com/users/525', 'pm_score': 2, 'selected': False, 'text': '<p>Answering my own question here, but I came across an article that take explains the problem, and does a walk-through of a simple example -- <a href="http://www.onjava.com/pub/a/onjava/2004/11/17/agileuser_1.html" rel="nofollow noreferrer">Agile User Interface Development</a>. The code and images are great, and here is a snippet that shows the idea:</p>\n\n<blockquote>\n <p>Agile gurus such as Kent Beck and\n David Astels suggest building the GUI\n by keeping the view objects very thin,\n and testing the layers "below the\n surface." This "smart object/thin\n view" model is analogous to the\n familiar document-view and\n client-server paradigms, but applies\n to the development of individual GUI\n elements. Separation of the content\n and presentation improves the design\n of the code, making it more modular\n and testable. Each component of the\n user interface is implemented as a\n smart object, containing the\n application behavior that should be\n tested, but no GUI presentation code.\n Each smart object has a corresponding\n thin view class containing only\n generic GUI behavior. With this design\n model, GUI building becomes amenable\n to TDD.</p>\n</blockquote>\n'}, {'answer_id': 386348, 'author': 'Kjetil Klaussen', 'author_id': 15599, 'author_profile': 'https://Stackoverflow.com/users/15599', 'pm_score': 1, 'selected': False, 'text': '<p>Your question doesn\'t state your programming language of choice, but mine is C# so I\'ll exemplify using that. This is however just a refinement over Gilligans answer by using anonymous delegates to inline your test code. I\'m all in favor of making tests as readable as possible, and to me that means all test code within the test method;</p>\n\n<pre><code>// Arrange\nvar car = new Car();\nstring changedPropertyName = "";\ncar.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n if (sender == car) \n changedPropertyName = e.PropertyName;\n };\n\n// Act\ncar.Model = "Volvo";\n\n// Assert \nAssert.AreEqual("Model", changedPropertyName, \n "The notification of a property change was not fired correctly.");\n</code></pre>\n\n<p>The class I\'m testing here implements the <code>INotifyPropertyChanged</code> interface and therefore a <code>NotifyPropertyChanged</code> event should be raised whenever a property\'s value has changed.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525/'] |
73,086 | <p>I've been trying to come up with a way to create a 3 column web design where the center column has a constant width and is always centered. The columns to the left and right are variable. This is trivial in tables, but not correct semantically. </p>
<p>I haven't been able to get this working properly in all current browsers. Any tips on this?</p>
| [{'answer_id': 73094, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': 3, 'selected': True, 'text': '<p>Use <a href="http://matthewjamestaylor.com/blog/perfect-3-column.htm" rel="nofollow noreferrer">this technique</a>, and simply specify a fixed width for the centre column.</p>\n'}, {'answer_id': 73140, 'author': 'Adam Hopkinson', 'author_id': 12280, 'author_profile': 'https://Stackoverflow.com/users/12280', 'pm_score': 0, 'selected': False, 'text': "<p>I think you'd need to start off with initial (fixed) widths for both sidebar columns and then, when the page loads, use javascript to get the window width and calculate the new width of the sidebars.</p>\n\n<p>sidebar width = (window width - center column width) / 2</p>\n\n<p>You could then reapply the javascript if the window is resized.</p>\n"}, {'answer_id': 73145, 'author': 'David Cumps', 'author_id': 4329, 'author_profile': 'https://Stackoverflow.com/users/4329', 'pm_score': 1, 'selected': False, 'text': '<p>Check this out: <a href="http://www.glish.com/css/2.asp" rel="nofollow noreferrer">http://www.glish.com/css/2.asp</a></p>\n<p>And replace the width: xx% for #maincenter by a fixed value. Seems to work when I change it with Firebug, worth a shot?</p>\n<pre class="lang-css prettyprint-override"><code>#maincenter {\n width: 200px;\n float: left;\n background: #fff;\n padding-bottom: 10px;\n}\n</code></pre>\n'}, {'answer_id': 73905, 'author': 'Dave Rutledge', 'author_id': 2486915, 'author_profile': 'https://Stackoverflow.com/users/2486915', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://alistapart.com/articles/holygrail" rel="nofollow noreferrer">This article at A List Apart</a> has a solution resulting in a 3-column layout that will :</p>\n\n<ul>\n<li><p>have a fluid center with fixed width sidebars,</p></li>\n<li><p>allow the center column to appear first in the source,</p></li>\n<li><p>allow any column to be the tallest,</p></li>\n<li><p>require only a single extra div of markup, and</p></li>\n<li><p>require very simple CSS, with minimal patches.</p></li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12529/'] |
73,087 | <p>Is there a standard X / Gnome program that will display the X,Y width and depth in pixels of a window that I select? Something similar to the way an xterm shows you the width and depth of the window (in lines) as you resize it.</p>
<p>I'm running on Red Hat Enterprise Linux 4.4.</p>
<p>Thanks!</p>
| [{'answer_id': 73155, 'author': 'Frank Wiles', 'author_id': 12568, 'author_profile': 'https://Stackoverflow.com/users/12568', 'pm_score': 6, 'selected': True, 'text': "<p>Yes, you're looking for the program 'xwininfo'. Run it in another terminal and then click on the window you want info about and it will give it to you. </p>\n\n<p>Hope this helps! </p>\n"}, {'answer_id': 73221, 'author': 'Linulin', 'author_id': 12481, 'author_profile': 'https://Stackoverflow.com/users/12481', 'pm_score': 3, 'selected': False, 'text': '<pre><code>$ xwininfo \n\nxwininfo: Please select the window about which you\n would like information by clicking the\n mouse in that window.\n\nxwininfo: Window id: 0x1200007 "xeyes"\n\n Absolute upper-left X: 1130\n Absolute upper-left Y: 0\n Relative upper-left X: 0\n Relative upper-left Y: 0\n Width: 150\n Height: 100\n Depth: 24\n Visual Class: TrueColor\n Border width: 0\n Class: InputOutput\n Colormap: 0x20 (installed)\n Bit Gravity State: NorthWestGravity\n Window Gravity State: NorthWestGravity\n Backing Store State: NotUseful\n Save Under State: no\n Map State: IsViewable\n Override Redirect State: no\n Corners: +1130+0 -0+0 -0-924 +1130-924\n -geometry 150x100-0+0\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9648/'] |
73,095 | <p>I'd like to implement a simple class (in Java) that would allow me to register and deregister strings, and on the basis of the current set of strings auto-complete a given string. So, the interface would be:</p>
<ul>
<li>void add(String)</li>
<li>void remove(String)</li>
<li>String complete(String)</li>
</ul>
<p>What's the best way to do this in terms of algorithms and data-structures?</p>
| [{'answer_id': 73161, 'author': 'Jon Homan', 'author_id': 7589, 'author_profile': 'https://Stackoverflow.com/users/7589', 'pm_score': -1, 'selected': False, 'text': '<p>Regular expressions.</p>\n'}, {'answer_id': 73345, 'author': 'johnmcase', 'author_id': 12480, 'author_profile': 'https://Stackoverflow.com/users/12480', 'pm_score': 0, 'selected': False, 'text': '<p>It would have to be some kind of a List that you can maintain in sorted order. You would also have to write your own search algorithm that would give you the index of the first element in the list that matches your search pattern. Then iterate from that index until the first element that doesn\'t match and you have your list of possible completions.</p>\n\n<p>I\'d look at <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/list/TreeList.html" rel="nofollow noreferrer">TreeList</a> from commons-collections. It has fast insert and remove times from the middle of the List which you\'ll want in order to maintain sorted order. It would probably be fairly easy to write your search function off of the tree that backs that list.</p>\n'}, {'answer_id': 73358, 'author': 'Aidos', 'author_id': 12040, 'author_profile': 'https://Stackoverflow.com/users/12040', 'pm_score': 2, 'selected': False, 'text': "<p>The datastructure you are after is called a Ternary Search Tree.</p>\n\n<p>There's a great JavaWorld example at www.javaworld.com/javaworld/jw-02-2001/jw-0216-ternary.html</p>\n"}, {'answer_id': 73616, 'author': 'pgras', 'author_id': 12719, 'author_profile': 'https://Stackoverflow.com/users/12719', 'pm_score': 3, 'selected': True, 'text': "<p>you should consider to use a PATRICIA trie for the data structure. Search for 'patricia trie' on google and you'll find a lot of information...</p>\n"}, {'answer_id': 1944664, 'author': 'Shilad Sen', 'author_id': 141245, 'author_profile': 'https://Stackoverflow.com/users/141245', 'pm_score': 0, 'selected': False, 'text': '<p>For those who stumble upon this question...</p>\n\n<p>I just posted a <a href="http://code.google.com/p/autocomplete-server/" rel="nofollow noreferrer">server-side autocomplete implementation</a> on Google Code. The project includes a java library that can be integrated into existing applications and a standalone HTTP AJAX autocomplete server. </p>\n\n<p>My hope is that enables people to incorporate efficient autocomplete into their applications. Kick the tires!</p>\n'}, {'answer_id': 2493872, 'author': 'Wellington RIbeiro', 'author_id': 299179, 'author_profile': 'https://Stackoverflow.com/users/299179', 'pm_score': 0, 'selected': False, 'text': '<p>I have created a JQuery plugin called Simple AutoComplete, that allows you to add many autocomplete as you want on the same page, and to add filters with extra param, and execute a callback function to bring other params, like the id of the item.</p>\n\n<p>See it at <a href="http://www.idealmind.com.br/projetos/simple-autocomplete-jquery-plugin/" rel="nofollow noreferrer">http://www.idealmind.com.br/projetos/simple-autocomplete-jquery-plugin/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12547/'] |
73,109 | <p>I'm working with a fairly simple database, from a Java application. We're trying to insert about 200k of text at a time, using the standard JDBC mysql adapter. We intermittently get a <code>com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.</code></p>
<p>The column type is <code>longtext</code>, and database collation is <code>UTF-8</code>. The error shows up using both <code>MyISAM</code> and <code>InnoDB</code> table engines. Max packet size has been set ot 1 GB on both client and server sides, so that shouldn't be causing a problem, either.</p>
| [{'answer_id': 73197, 'author': 'Nicholas', 'author_id': 8054, 'author_profile': 'https://Stackoverflow.com/users/8054', 'pm_score': 3, 'selected': False, 'text': '<p>Well you can make it ignore the error by doing an INSERT IGNORE which will just truncate the data and insert it anyway. (from <a href="http://dev.mysql.com/doc/refman/5.0/en/insert.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/insert.html</a> )</p>\n\n<blockquote>\n <p>If you use the IGNORE keyword, errors\n that occur while executing the INSERT\n statement are treated as warnings\n instead. For example, without IGNORE,\n a row that duplicates an existing\n UNIQUE index or PRIMARY KEY value in\n the table causes a duplicate-key error\n and the statement is aborted. With\n IGNORE, the row still is not inserted,\n but no error is issued. Data\n conversions that would trigger errors\n abort the statement if IGNORE is not\n specified. With IGNORE, invalid values\n are adjusted to the closest values and\n inserted; warnings are produced but\n the statement does not abort.</p>\n</blockquote>\n'}, {'answer_id': 73232, 'author': 'Aaron', 'author_id': 11176, 'author_profile': 'https://Stackoverflow.com/users/11176', 'pm_score': 2, 'selected': False, 'text': "<p>It sounds to me like you are trying to put too many bytes into a column. I ran across a very similar error with MySQL last night due to a bug in my code. I meant to do </p>\n\n<pre><code>foo.status = 'inactive'\n</code></pre>\n\n<p>but had actually typed</p>\n\n<pre><code>foo.state = 'inactive'\n</code></pre>\n\n<p>Where foo.state is supposed to be a two character code for a US State ( varchar(2) ). I got the same error as you. You might go look for a similar situation in your code.</p>\n"}, {'answer_id': 73397, 'author': 'Avi', 'author_id': 1605, 'author_profile': 'https://Stackoverflow.com/users/1605', 'pm_score': 4, 'selected': False, 'text': '<p>Check that your UTF-8 data is all 3-byte Unicode. If you have 4-byte characters (legal in Unicode and Java, illegal in MySQL 5), it can throw this error when you try to insert them. This is an <a href="http://bugs.mysql.com/bug.php?id=25666" rel="noreferrer">issue that should be fixed</a> in MySQL 6.0.</p>\n'}, {'answer_id': 1110486, 'author': 'Szemere', 'author_id': 136373, 'author_profile': 'https://Stackoverflow.com/users/136373', 'pm_score': 1, 'selected': False, 'text': '<p>I just hit this problem and solved it by removing all the non-standard ascii characters in my text (following the UTF-8 advice above).</p>\n\n<p>I had the problem on a Debian 4, Java 5 system; but the same code worked fine with Ubuntu 9.04, Java 6. Both run MySql 5.</p>\n'}, {'answer_id': 12914251, 'author': 'grigson', 'author_id': 1051262, 'author_profile': 'https://Stackoverflow.com/users/1051262', 'pm_score': 2, 'selected': False, 'text': '<p>In mysql you can use <code>MEDIUMTEXT</code> or <code>LONGTEXT</code> field type for large text data</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
73,110 | <p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p>
<p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p>
<hr/>
<p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p>
<hr/>
<p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p>
<hr/>
<p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
| [{'answer_id': 73173, 'author': 'André Chalella', 'author_id': 4850, 'author_profile': 'https://Stackoverflow.com/users/4850', 'pm_score': 3, 'selected': False, 'text': "<p>I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and <code>WordWrap == false</code>.</p>\n\n<p>I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!</p>\n\n<p>Perhaps it would be a good idea just to let your application follow Windows' look and feel.</p>\n"}, {'answer_id': 89428, 'author': 'Hans Passant', 'author_id': 17034, 'author_profile': 'https://Stackoverflow.com/users/17034', 'pm_score': 5, 'selected': True, 'text': "<p>Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyTextBox : TextBox {\n private bool mScrollbars;\n public MyTextBox() {\n this.Multiline = true;\n this.ReadOnly = true;\n }\n private void checkForScrollbars() {\n bool scroll = false;\n int cnt = this.Lines.Length;\n if (cnt > 1) {\n int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;\n if (pos0 >= 32768) pos0 -= 65536;\n int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;\n if (pos1 >= 32768) pos1 -= 65536;\n int h = pos1 - pos0;\n scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding\n }\n if (scroll != mScrollbars) {\n mScrollbars = scroll;\n this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n\n protected override void OnTextChanged(EventArgs e) {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnClientSizeChanged(EventArgs e) {\n checkForScrollbars();\n base.OnClientSizeChanged(e);\n }\n}\n</code></pre>\n"}, {'answer_id': 612234, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>I came across this question when I wanted to solve the same problem. </p>\n\n<p>The easiest way to do it is to change to System.Windows.Forms.RichTextBox. The ScrollBars property in this case can be left to the default value of RichTextBoxScrollBars.Both, which indicates "Display both a horizontal and a vertical scroll bar when needed." It would be nice if this functionality were provided on TextBox.</p>\n'}, {'answer_id': 666731, 'author': 'yagni', 'author_id': 80525, 'author_profile': 'https://Stackoverflow.com/users/80525', 'pm_score': 3, 'selected': False, 'text': "<p>There's an extremely subtle bug in nobugz's solution that results in a heap corruption, but only if you're using AppendText() to update the TextBox.</p>\n\n<p>Setting the ScrollBars property from OnTextChanged will cause the Win32 window (handle) to be destroyed and recreated. But OnTextChanged is called from the bowels of the Win32 edit control (EditML_InsertText), which immediately thereafter expects the internal state of that Win32 edit control to be unchanged. Unfortunately, since the window is recreated, that internal state has been freed by the OS, resulting in an access violation.</p>\n\n<p>So the moral of the story is: don't use AppendText() if you're going to use nobugz's solution.</p>\n"}, {'answer_id': 4147348, 'author': 'b8adamson', 'author_id': 215954, 'author_profile': 'https://Stackoverflow.com/users/215954', 'pm_score': 2, 'selected': False, 'text': '<p>I had some success with the code below.</p>\n\n<pre><code> public partial class MyTextBox : TextBox\n {\n private bool mShowScrollBar = false;\n\n public MyTextBox()\n {\n InitializeComponent();\n\n checkForScrollbars();\n }\n\n private void checkForScrollbars()\n {\n bool showScrollBar = false;\n int padding = (this.BorderStyle == BorderStyle.Fixed3D) ? 14 : 10;\n\n using (Graphics g = this.CreateGraphics())\n {\n // Calcualte the size of the text area.\n SizeF textArea = g.MeasureString(this.Text,\n this.Font,\n this.Bounds.Width - padding);\n\n if (this.Text.EndsWith(Environment.NewLine))\n {\n // Include the height of a trailing new line in the height calculation \n textArea.Height += g.MeasureString("A", this.Font).Height;\n }\n\n // Show the vertical ScrollBar if the text area\n // is taller than the control.\n showScrollBar = (Math.Ceiling(textArea.Height) >= (this.Bounds.Height - padding));\n\n if (showScrollBar != mShowScrollBar)\n {\n mShowScrollBar = showScrollBar;\n this.ScrollBars = showScrollBar ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n }\n\n protected override void OnTextChanged(EventArgs e)\n {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnResize(EventArgs e)\n {\n checkForScrollbars();\n base.OnResize(e);\n }\n }\n</code></pre>\n'}, {'answer_id': 25197797, 'author': 'Michael Csikos', 'author_id': 1484559, 'author_profile': 'https://Stackoverflow.com/users/1484559', 'pm_score': 0, 'selected': False, 'text': "<p>What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.</p>\n\n<p>For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.</p>\n\n<p>I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.</p>\n\n<p>The following seems to work pretty well, with or without a border, and it works with WordWrap on.</p>\n\n<p>Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.</p>\n\n<pre><code>public class TextBoxAutoScroll : TextBox\n{\n public void AutoScrollVertically(bool recalculateOnResize = false)\n {\n SuspendLayout();\n\n if (recalculateOnResize)\n {\n Resize -= OnResize;\n Resize += OnResize;\n }\n\n float linesHeight = 0;\n var borderStyle = BorderStyle;\n\n BorderStyle = BorderStyle.None;\n\n int textHeight = PreferredHeight;\n\n try\n {\n using (var graphics = CreateGraphics())\n {\n foreach (var text in Lines)\n {\n var textArea = graphics.MeasureString(text, Font);\n\n if (textArea.Width < Width)\n linesHeight += textHeight;\n else\n {\n var numLines = (float)Math.Ceiling(textArea.Width / Width);\n\n linesHeight += textHeight * numLines;\n }\n }\n }\n\n if (linesHeight > Height)\n ScrollBars = ScrollBars.Vertical;\n else\n ScrollBars = ScrollBars.None;\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine(ex);\n }\n finally\n {\n BorderStyle = borderStyle;\n\n ResumeLayout();\n }\n }\n\n private void OnResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n m_timerResize.Tick -= OnDelayedResize;\n m_timerResize.Tick += OnDelayedResize;\n m_timerResize.Interval = 475;\n\n m_timerResize.Start();\n }\n\n Timer m_timerResize = new Timer();\n\n private void OnDelayedResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n Resize -= OnResize;\n\n AutoScrollVertically();\n\n Resize += OnResize;\n }\n}\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1042/'] |
73,117 | <p>I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)</p>
<pre>
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
</pre>
<p>So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is. <br /></p>
<p>I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.<br /></p>
<p>ACTUAL QUESTION:</p>
<p>Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?</p>
<p>EDIT (To clarify more):<br />
OS -- Windows (since this is a hobby project, may do this in Linux later)<br />
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)</p>
<p>Q-Unanswered: SDL : OpenGL : Direct X <br />
Q-Answered: Avoid Parallel Processing <br />
Q-Answered: Use STL to implement time-step actions.<br /></p>
<pre>
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
</pre>
<p>Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)</p>
| [{'answer_id': 73152, 'author': 'Jason Z', 'author_id': 2470, 'author_profile': 'https://Stackoverflow.com/users/2470', 'pm_score': 1, 'selected': False, 'text': "<p>I have played this game before. I don't necessarily think parallel processing is the way to go. You have shared objects in the game (levers, boxes, elevators, etc) that will need to be shared between processes, possibly with every delta, thereby reducing the effectiveness of the parallelism.</p>\n\n<p>I would personally just keep a list of actions, then for each subsequent iteration start interleaving them together. For example, if the list is in the format of <[iteration.action]> then the 3rd time thru would execute actions 1.1, 2.1, 3.1, 1.2, 2.2, 3.3, etc.</p>\n"}, {'answer_id': 73160, 'author': 'mmattax', 'author_id': 1638, 'author_profile': 'https://Stackoverflow.com/users/1638', 'pm_score': 0, 'selected': False, 'text': "<p>After briefly glossing over the description, I think you have the right idea, I would have a state object that holds the state data, and place this into a linked list...I don't think you need parallel threads...</p>\n\n<p>as far as the graphics API, I have only used opengl, and can say that it is pretty powerful and has a good C / C++ API, opengl would also be more cross platform as you can use the messa library on *Nix computers. </p>\n"}, {'answer_id': 73178, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>A very interesting game idea. I think you are right that parrellel computing would be benefical to this design, but no more then any other high resource program. </p>\n\n<p>The question is a bit ambigous. I see that you are going to write this in C++ but what OS are you coding it for? Do you intend on it being cross platform and what kind of graphics would you like, ie 3D, 2D, high end, web based.</p>\n\n<p>So basically we need a lot more information.</p>\n'}, {'answer_id': 73265, 'author': 'enigmatic', 'author_id': 443575, 'author_profile': 'https://Stackoverflow.com/users/443575', 'pm_score': 0, 'selected': False, 'text': '<p>Parallel processing isn\'t the answer. You should simply "record" the players actions then play them back for the "previous actions"</p>\n\n<p>So you create a vector (singly linked list) of vectors that holds the actions. Simply store the frame number that the action was taken (or the delta) and complete that action on the "dummy bot" that represents the player during that particular instance. You simply loop through the states and trigger them one after another.</p>\n\n<p>You get a side effect of easily "breaking" the game when a state paradox happens simply because the next action fails.</p>\n'}, {'answer_id': 73328, 'author': 'Iain', 'author_id': 11911, 'author_profile': 'https://Stackoverflow.com/users/11911', 'pm_score': 0, 'selected': False, 'text': '<p>Unless you\'re desperate to use C++ for your own education, you should definitely look at <a href="http://creators.xna.com" rel="nofollow noreferrer">XNA</a> for your game & graphics framework (it uses C#). It\'s completely free, it does a lot of things for you, and soon you\'ll be able to sell your game on Xbox Live.</p>\n\n<p>To answer your main question, nothing that you can already do in Flash would ever need to use more than one thread. Just store a list of positions in an array and loop through with a different offset for each robot.</p>\n'}, {'answer_id': 73353, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 3, 'selected': False, 'text': '<p>This sounds very similar to <a href="http://braid-game.com" rel="noreferrer">Braid</a>. You really don\'t want parallel processing for this - parallel programming is <b>hard</b>, and for something like this, performance should not be an issue.</p>\n\n<p>Since the game state vector will grow very quickly (probably on the order of several kilobytes per second, depending on the frame rate and how much data you store), you don\'t want a linked list, which has a lot of overhead in terms of space (and can introduce big performance penalties due to cache misses if it is laid out poorly). For each parallel timeline, you want a vector data structure. You can store each parallel timeline in a linked list. Each timeline knows at what time it began.</p>\n\n<p>To run the game, you iterate through all active timelines and perform one frame\'s worth of actions from each of them in lockstep. No need for parallel processing.</p>\n'}, {'answer_id': 73537, 'author': 'Andreas Magnusson', 'author_id': 5811, 'author_profile': 'https://Stackoverflow.com/users/5811', 'pm_score': 4, 'selected': True, 'text': '<p>What you should do is first to read and understand the "fixed time-step" game loop (Here\'s a good explanation: <a href="http://www.gaffer.org/game-physics/fix-your-timestep" rel="nofollow noreferrer">http://www.gaffer.org/game-physics/fix-your-timestep</a>).</p>\n\n<p>Then what you do is to keep a list of list of pairs of frame counter and action. STL example:</p>\n\n<pre class="lang-c++ prettyprint-override"><code>std::list<std::list<std::pair<unsigned long, Action> > > state;\n</code></pre>\n\n<p>Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you\'d get the best results if action simply was "key <X> pressed" or "key <X> released":</p>\n\n<pre class="lang-c++ prettyprint-override"><code>state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));\n</code></pre>\n\n<p>To play back the previous states, you\'d have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state.\nTo optimize you could keep a list of iterators to where you are in each previous state-list. Here\'s some <em>pseudo-code</em> for that:</p>\n\n<pre class="lang-c++ prettyprint-override"><code>typedef std::list<std::pair<unsigned long, Action> > StateList;\nstd::list<StateList::iterator> stateIteratorList;\n//\nforeach(it in stateIteratorList)\n{\n if(it->first == currentFrame)\n {\n performAction(it->second);\n ++it;\n }\n}\n</code></pre>\n\n<p>I hope you get the idea...</p>\n\n<p>Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can\'t really see how that would be implemented) or a non-fixed time-step game loop.</p>\n\n<p>When it comes to graphics API, I\'d go with SDL as it\'s probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6128/'] |
73,123 | <p>Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?</p>
<p>For example:</p>
<pre><code>http://mywebsite.com/132483
</code></pre>
<p>would be sent to:</p>
<pre><code>http://mywebsite.com/scriptname.php?no=132483
</code></pre>
<p>but</p>
<pre><code>http://mywebsite.com/132483a or
http://mywebsite.com/asdf
</code></pre>
<p>would be handled as a 404 error.</p>
<p>I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.</p>
| [{'answer_id': 73141, 'author': 'Frank Wiles', 'author_id': 12568, 'author_profile': 'https://Stackoverflow.com/users/12568', 'pm_score': 0, 'selected': False, 'text': "<p>Yes it's possible with mod_rewrite. There are tons of good mod_rewrite tutorials online a quick Google search should turn up your answer in no time. </p>\n\n<p>Basically what you're going to want to do is ensure that the regular expression you use is just looking for digits and no other characters and to ensure the length is 6. Then you'll redirect to scriptname.?no= with the number you captured. </p>\n\n<p>Hope this helps!</p>\n"}, {'answer_id': 73184, 'author': 'Adam Hopkinson', 'author_id': 12280, 'author_profile': 'https://Stackoverflow.com/users/12280', 'pm_score': 4, 'selected': False, 'text': '<p>In your htaccess file, put the following</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]\n</code></pre>\n\n<p>The first line turns the mod_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters long containing only characters 0-9.</p>\n\n<p>The [L] at the end makes this the last rule - if it applies, rule processing will stop.</p>\n\n<p>Oh, the ^ and $ mark the start and end of the incoming uri.</p>\n\n<p>Hope that helps!</p>\n'}, {'answer_id': 73315, 'author': 'daniels', 'author_id': 9789, 'author_profile': 'https://Stackoverflow.com/users/9789', 'pm_score': 3, 'selected': True, 'text': '<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]\n</IfModule>\n</code></pre>\n\n<p>To preserve the clean URL </p>\n\n<pre><code>http://mywebsite.com/132483\n</code></pre>\n\n<p>while serving scriptname.php use only [L]. \nUsing [R=301] will redirect you to your scriptname.php?no=xxx</p>\n\n<p>You may find this useful <a href="http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/" rel="nofollow noreferrer">http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/</a> </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12513/'] |
73,128 | <p>We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher: </p>
<pre><code>if (this.fileWatcher == null)
{
this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
</code></pre>
<p>The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):</p>
<pre><code>private void FileWatcherFileChanged(FileSystemEventArgs args)
{
if (this.TreeView != null)
{
if (this.TreeView.InvokeRequired)
{
FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
this.TreeView.Invoke(d, new object[]
{
args
});
}
else
{
switch (args.ChangeType)
{
case WatcherChangeTypes.Changed:
if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
{
this.StateImageKey = GetStateImageKey();
}
else
{
projectItemTreeNode.StateImageKey = GetStateImageKey();
}
break;
}
}
}
}
</code></pre>
<p>Is there something we're missing or is this an anomoly from .NET3.5 SP1?</p>
| [{'answer_id': 73192, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 4, 'selected': True, 'text': "<p>Just a thought... Any chance there's a deadlock issue here?</p>\n\n<p>You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed.</p>\n\n<p>Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction.</p>\n\n<p>Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided.</p>\n"}, {'answer_id': 88377, 'author': 'Jamie Penney', 'author_id': 68230, 'author_profile': 'https://Stackoverflow.com/users/68230', 'pm_score': 1, 'selected': False, 'text': "<p>We are also having this issue. Our application runs on .Net 2.0 but is compiled by VS 2008 SP1. I have .NET 3.5 SP1 installed as well. I've got no idea why this happens either, it doesn't look like a deadlock issue on our end as no other threads are running at this point (it is during application shutdown).</p>\n"}, {'answer_id': 153922, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 2, 'selected': False, 'text': "<p>Scott, we've occasionally seen issues with control.Invoke in .NET 2. Try switching to control.BeginInvoke and see if that helps. </p>\n\n<p>Doing that will allow the FileSystemWatcher thread to return immediately. I suspect your issue is somehow that the control.Invoke is blocking, thus causing the FileSystemWatcher to freeze upon dispose.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1559/'] |
73,134 | <p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p>
<pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
</code></pre>
<p>Later on however the memory is freed using a <code>delete</code> call:</p>
<pre class="lang-cpp prettyprint-override"><code>delete pStruct;
</code></pre>
<p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>
| [{'answer_id': 73157, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': 0, 'selected': False, 'text': "<p>Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.</p>\n\n<p>Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)</p>\n\n<p>Better would be to do it correctly, as this will also correctly call any constructors and deconstructors</p>\n\n<pre><code>STRUCT* pStruct = new STRUCT;\n...\ndelete pStruct;\n</code></pre>\n"}, {'answer_id': 73163, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 5, 'selected': True, 'text': "<p>Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.</p>\n\n<p>More importantly if <code>STRUCT</code> where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.</p>\n\n<p>Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:</p>\n\n<pre><code>delete [] (BYTE*) pStruct;\n</code></pre>\n"}, {'answer_id': 73189, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 0, 'selected': False, 'text': "<p>You'd could cast back to a BYTE * and the delete:</p>\n\n<pre><code>delete[] (BYTE*)pStruct;\n</code></pre>\n"}, {'answer_id': 73201, 'author': 'slicedlime', 'author_id': 11230, 'author_profile': 'https://Stackoverflow.com/users/11230', 'pm_score': 3, 'selected': False, 'text': "<p>The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it:</p>\n\n<ol>\n<li>The <code>delete</code> should be an array <code>delete []</code>.</li>\n<li>The <code>delete</code> should be called on a pointer to the same type as the type allocated.</li>\n</ol>\n\n<p>So to be entirely correct, you want to be doing something like this:</p>\n\n<pre><code>delete [] (BYTE*)(pStruct);\n</code></pre>\n"}, {'answer_id': 73219, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': -1, 'selected': False, 'text': '<p>Rob Walker <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163">reply</a> is good.</p>\n\n<p>Just small addition, if you don\'t have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.</p>\n'}, {'answer_id': 73225, 'author': 'QBziZ', 'author_id': 11572, 'author_profile': 'https://Stackoverflow.com/users/11572', 'pm_score': 0, 'selected': False, 'text': "<p>It's always best to keep acquisition/release of any resource as balanced as possible.\nAlthough leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation.</p>\n\n<pre><code>BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nSTRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ;\n\n // do stuff with pStruct\n\ndelete [] pBytes ;\n</code></pre>\n"}, {'answer_id': 73233, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You\'re sort of mixing C and C++ ways of doing things. Why allocate more than the size of a STRUCT? Why not just "new STRUCT"? If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects.</p>\n'}, {'answer_id': 73295, 'author': 'Len Holgate', 'author_id': 7925, 'author_profile': 'https://Stackoverflow.com/users/7925', 'pm_score': 3, 'selected': False, 'text': '<p>Yes it will cause a memory leak.</p>\n\n<p>See this except from C++ Gotchas: <a href="http://www.informit.com/articles/article.aspx?p=30642" rel="nofollow noreferrer"><a href="http://www.informit.com/articles/article.aspx?p=30642" rel="nofollow noreferrer">http://www.informit.com/articles/article.aspx?p=30642</a></a> for why.</p>\n\n<p>Raymond Chen has an explanation of how vector <code>new</code> and <code>delete</code> differ from the scalar versions under the covers for the Microsoft compiler... Here: \n<a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx" rel="nofollow noreferrer"><a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx</a></a> </p>\n\n<p>IMHO you should fix the delete to:</p>\n\n<pre><code>delete [] pStruct;\n</code></pre>\n\n<p>rather than switching to <code>malloc</code>/<code>free</code>, if only because it\'s a simpler change to make without making mistakes ;)</p>\n\n<p>And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be </p>\n\n<pre><code>delete [] reinterpret_cast<BYTE *>(pStruct);\n</code></pre>\n\n<p>so, I guess it\'s probably as easy to switch to <code>malloc</code>/<code>free</code> after all ;)</p>\n'}, {'answer_id': 73332, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size. So delete[] pStruct will not de-allocate all of the allocated memory.</p>\n'}, {'answer_id': 73368, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 0, 'selected': False, 'text': '<p>Use operator new and delete:</p>\n\n<pre><code>struct STRUCT\n{\n void *operator new (size_t)\n {\n return new char [sizeof(STRUCT) + nPaddingSize];\n }\n\n void operator delete (void *memory)\n {\n delete [] reinterpret_cast <char *> (memory);\n }\n};\n\nvoid main()\n{\n STRUCT *s = new STRUCT;\n delete s;\n}\n</code></pre>\n'}, {'answer_id': 73420, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 2, 'selected': False, 'text': '<p>The C++ standard clearly states:</p>\n\n<pre><code>delete-expression:\n ::opt delete cast-expression\n ::opt delete [ ] cast-expression\n</code></pre>\n\n<blockquote>\n <p>The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.</p>\n \n <p>In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined.</p>\n</blockquote>\n\n<p>The value of the operand in <code>delete pStruct</code> is a pointer to an array of <code>char</code>, independent of its static type (<code>STRUCT*</code>). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case.</p>\n\n<p>It could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression.</p>\n'}, {'answer_id': 73718, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 3, 'selected': False, 'text': "<p>I personally think you'd be better off using <code>std::vector</code> to manage your memory, so you don't need the <code>delete</code>.</p>\n\n<pre><code>std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);\nSTRUCT* pStruct = (STRUCT*)(&backing[0]);\n</code></pre>\n\n<p>Once backing leaves scope, your <code>pStruct</code> is no longer valid.</p>\n\n<p>Or, you can use:</p>\n\n<pre><code>boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);\nSTRUCT* pStruct = (STRUCT*)backing.get();\n</code></pre>\n\n<p>Or <code>boost::shared_array</code> if you need to move ownership around.</p>\n"}, {'answer_id': 74170, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 2, 'selected': False, 'text': '<p>If you <em>really</em> must do this sort of thing, you should probably call operator <code>new</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);\n</code></pre>\n\n<p>I believe calling it this way avoids calling constructors/destructors.</p>\n'}, {'answer_id': 74232, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 1, 'selected': False, 'text': '<p>I am currently unable to vote, but <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73201">slicedlime\'s answer</a> is preferable to <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163">Rob Walker\'s answer</a>, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.</p>\n\n<p>Also note that the example code does not necessarily result in a memory leak - it\'s undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away).</p>\n\n<p>The example code results in undefined behavior, plain and simple. slicedlime\'s answer is direct and to the point (with the caveat that the word \'vector\' should be changed to \'array\' since vectors are an STL thing).</p>\n\n<p>This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):</p>\n\n<p><a href="http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12" rel="nofollow noreferrer">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12</a></p>\n'}, {'answer_id': 74236, 'author': 'Richard Corden', 'author_id': 11698, 'author_profile': 'https://Stackoverflow.com/users/11698', 'pm_score': 2, 'selected': False, 'text': "<p>As highlighted in other posts:</p>\n\n<p>1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)</p>\n\n<p>2) Mixing array/non-array versions of <code>new</code> and <code>delete</code> is undefined behaviour. (C++ '03 5.3.5/4)</p>\n\n<p>Looking at the source it appears that someone did a search and replace for <code>malloc</code> and <code>free</code> and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for <code>new</code> and <code>delete</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);\n// ...\npStruct->~STRUCT (); // Call STRUCT destructor\n::operator delete (pStruct);\n</code></pre>\n\n<p>If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement <code>new</code>:</p>\n\n<pre><code>BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];\nSTRUCT * pStruct = new (pByteData) STRUCT ();\n// ...\npStruct->~STRUCT ();\ndelete[] pByteData;\n</code></pre>\n"}, {'answer_id': 74361, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': '<p>I think the is no memory leak.</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];\n</code></pre>\n\n<p>This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of <code>sizeof(STRUCT)</code> and the size of <code>nPaddingSize</code> would be known in order to fulfill any memory allocation requests against the underlying operating system.</p>\n\n<p>So the memory that is allocated is "recorded" in the operating system\'s global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well).</p>\n\n<p>You see, the C/C++ compiler is not managing memory, the underlying operating system is.</p>\n\n<p>I agree there are cleaner methods but the OP did say this was legacy code.</p>\n\n<p>In short, I don\'t see a memory leak as the accepted answer believes there to be one.</p>\n'}, {'answer_id': 74411, 'author': 'Assaf Lavie', 'author_id': 11208, 'author_profile': 'https://Stackoverflow.com/users/11208', 'pm_score': 1, 'selected': False, 'text': "<p>It's an array delete ([]) you're referring to, not a vector delete.\nA vector is std::vector, and it takes care of deletion of its elements.</p>\n"}, {'answer_id': 75945, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': -1, 'selected': False, 'text': '<p>ericmayo.myopenid.com is so wrong, that someone with enough reputation should downvote him.</p>\n\n<p>The C or C++ runtime libraries are managing the heap which is given to it in blocks by the Operating System, somewhat like you indicate, Eric. But it <em>is</em> the responsibility of the developer to indicate to the compiler which runtime calls should be made to free memory, and possibly destruct the objects that are there. Vector delete (aka delete[]) is necessary in this case, in order for the C++ runtime to leave the heap in a valid state. The fact that when the PROCESS terminates, the OS is smart enough to deallocate the underlying memory blocks is not something that developers should rely on. This would be like never calling delete at all.</p>\n'}, {'answer_id': 79620, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': "<p>@Matt Cruikshank \nYou should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up. And you're wrong about the C++ run-time libraries managing the heap. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable). I challenge you to find stdlib.h in the Linux sources from kernel.org. The new keyword in C++ actually is talking to the same memory management routines as malloc.</p>\n\n<p>The C++ run-time libraries make OS system calls and it's the OS that manages the heaps. You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly. In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc... It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source. Understand these modern operating system have virtual memory managers that complicates things a bit further.</p>\n\n<p>Ever wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer?</p>\n\n<p>Memory management on x86 processors is managed within Kernel space using three tables. PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables). This is at the hardware level I'm speaking of. One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls. The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault).</p>\n\n<p>It may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit. I use to maintain a C/C++ compiler for a living...</p>\n"}, {'answer_id': 83972, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 0, 'selected': False, 'text': '<p>@ericmayo - cripes. Well, experimenting with VS2005, I can\'t get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster.</p>\n\n<p>You\'ve got to admit though, it\'s a really lousy practice to do what the original poster said.</p>\n\n<blockquote>\n <p>If that were the case then C++ would\n not be portable as is today and a\n crashing application would never get\n cleaned up by the OS.</p>\n</blockquote>\n\n<p>This logic doesn\'t really hold, though. My assertion is that a compiler\'s runtime can manage the memory within the memory blocks that the OS returns to it. This is how most virtual machines work, so your argument against portability in this case don\'t make much sense.</p>\n'}, {'answer_id': 84335, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': '<p>@Matt Cruikshank</p>\n\n<p>"Well, experimenting with VS2005, I can\'t get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster."</p>\n\n<p>I disagree that it\'s a compiler behavior or even a compiler issue. The \'new\' keyword gets compiled and linked, as you pointed out, to run-time libraries. Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either. </p>\n\n<p>The OS manages memory. </p>\n\n<p>The run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs. This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it\'s implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either. You will, however, find OS specific definitions for malloc.</p>\n\n<p>Since we have the source to Linux, you can go look at how malloc is implemented there. You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory. Never, malloc itself, actually managing memory!</p>\n\n<p>And don\'t take it from me. Read the source code to Linux OS or you can see what K&R say about it... Here is a PDF link to the K&R on C.</p>\n\n<p><a href="http://www.oberon2005.ru/paper/kr_c.pdf" rel="nofollow noreferrer">http://www.oberon2005.ru/paper/kr_c.pdf</a></p>\n\n<p>See near end of Page 149:\n"Calls to malloc and free may occur in any order; malloc calls\nupon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef."</p>\n\n<p>"You\'ve got to admit though, it\'s a really lousy practice to do what the original poster said."</p>\n\n<p>Oh, I don\'t disagree there. My point was that the original poster\'s code was not conducive of a memory leak. That\'s all I was saying. I didn\'t chime in on the best practice side of things. Since the code is calling delete, the memory is getting free up.</p>\n\n<p>I agree, in your defense, if the original poster\'s code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called. "Later on however the memory is freed using a delete call:"</p>\n\n<p>Moreover, my reason for responding as I did was due to the OP\'s comment "variable length structures (TAPI), where the structure size will depend on variable length strings"</p>\n\n<p>That comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak. I was reading between the lines if you will ;).</p>\n'}, {'answer_id': 84503, 'author': 'KPexEA', 'author_id': 13676, 'author_profile': 'https://Stackoverflow.com/users/13676', 'pm_score': 0, 'selected': False, 'text': '<p>In addition to the excellent answers above, I would also like to add:</p>\n\n<p>If your code runs on linux or if you can compile it on linux then I would suggest running it through <a href="http://valgrind.org/" rel="nofollow noreferrer">Valgrind</a>. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).</p>\n'}, {'answer_id': 85021, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 2, 'selected': False, 'text': "<p>@eric - Thanks for the comments. You keep saying something though, that drives me nuts:</p>\n\n<blockquote>\n <p>Those run-time libraries handle the\n memory management calls to the OS in a\n OS independent consistent syntax and\n those run-time libraries are\n responsible for making malloc and new\n work consistently between OSes such as\n Linux, Windows, Solaris, AIX, etc....</p>\n</blockquote>\n\n<p>This is not true. The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS <strong>dependent</strong> way. They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish.</p>\n\n<p>Compatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls.</p>\n"}, {'answer_id': 108454, 'author': 'CB Bailey', 'author_id': 19563, 'author_profile': 'https://Stackoverflow.com/users/19563', 'pm_score': 2, 'selected': False, 'text': "<p>The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided.</p>\n\n<p>Frequently these two steps are performed by a single C++ statement.</p>\n\n<pre><code>MyObject* ObjPtr = new MyObject;\n\n//...\n\ndelete MyObject;\n</code></pre>\n\n<p>Instead of the above you can use the C++ raw memory allocation functions <code>operator new</code> and <code>operator delete</code> and explicit construction (via placement <code>new</code>) and destruction to perform the equivalent steps.</p>\n\n<pre><code>void* MemoryPtr = ::operator new( sizeof(MyObject) );\nMyObject* ObjPtr = new (MemoryPtr) MyObject;\n\n// ...\n\nObjPtr->~MyObject();\n::operator delete( MemoryPtr );\n</code></pre>\n\n<p>Notice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like <code>new char[N]</code> as a way to allocate raw memory is technically incorrect as, logically, <code>char</code> objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it.</p>\n\n<p>In this particular case, there is no gain to be had by separating out the two steps of <code>delete</code> but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of <code>MyObject</code> throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression.</p>\n\n<pre><code>class MyObject\n{\n void* operator new( std::size_t rqsize, std::size_t padding )\n {\n return ::operator new( rqsize + padding );\n }\n\n // Usual (non-placement) delete\n // We need to define this as our placement operator delete\n // function happens to have one of the allowed signatures for\n // a non-placement operator delete\n void operator delete( void* p )\n {\n ::operator delete( p );\n }\n\n // Placement operator delete\n void operator delete( void* p, std::size_t )\n {\n ::operator delete( p );\n }\n};\n</code></pre>\n\n<p>There are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.)</p>\n\n<pre><code>// Called in one step like so:\nMyObject* ObjectPtr = new (padding) MyObject;\n</code></pre>\n\n<p>Using a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws.</p>\n\n<p>At the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object.</p>\n\n<pre><code>delete ObjectPtr;\n</code></pre>\n\n<p>Summary!</p>\n\n<ol>\n<li><p>Look no casts! <code>operator new</code> and <code>operator delete</code> deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a <code>void*</code> to an object pointer is usually a sign of something logically wrong, even if it does 'just work'.</p></li>\n<li><p>We've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case.</p></li>\n<li><p>Placement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain <code>delete</code> be the correct way to do this so most standard smart pointers will work.</p></li>\n</ol>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9236/'] |
73,159 | <p>Are there any utilities or browser plugins that let you easily switch the version of the Flash player that is being used?</p>
| [{'answer_id': 73175, 'author': 'David Cumps', 'author_id': 4329, 'author_profile': 'https://Stackoverflow.com/users/4329', 'pm_score': 1, 'selected': False, 'text': '<p>Found the following: <a href="http://www.google.be/search?q=firefox%20switch%20flash%20version" rel="nofollow noreferrer">http://www.google.be/search?q=firefox%20switch%20flash%20version</a></p>\n\n<p><a href="http://www.sephiroth.it/weblog/archives/2006/10/flash_switcher_for_firefox.php" rel="nofollow noreferrer">http://www.sephiroth.it/weblog/archives/2006/10/flash_switcher_for_firefox.php</a> (seems nice)</p>\n\n<p><a href="http://www.communitymx.com/content/article.cfm?page=2&cid=6FBA7" rel="nofollow noreferrer">http://www.communitymx.com/content/article.cfm?page=2&cid=6FBA7</a> (seems nicely integrated as well)</p>\n\n<p><a href="https://addons.mozilla.org/nl/firefox/addon/5044" rel="nofollow noreferrer">https://addons.mozilla.org/nl/firefox/addon/5044</a> (from mozilla.org, must be good :p)</p>\n'}, {'answer_id': 73231, 'author': 'Daniel R.', 'author_id': 12118, 'author_profile': 'https://Stackoverflow.com/users/12118', 'pm_score': 2, 'selected': False, 'text': '<p>For Firefox 3.x on Window XP, Ubutntu Linux, and Mac OS X (Tiger and Leopard), <a href="http://www.sephiroth.it/firefox/flash_switcher/" rel="nofollow noreferrer">Flash Switcher</a> works well.</p>\n'}, {'answer_id': 5723594, 'author': 'Matt', 'author_id': 193244, 'author_profile': 'https://Stackoverflow.com/users/193244', 'pm_score': 2, 'selected': False, 'text': '<p>For a cross-browser, cross-platform solution, you can use this python script:</p>\n\n<p><a href="http://www.mattshaw.org/projects/flash-plugin-switcher/" rel="nofollow">http://www.mattshaw.org/projects/flash-plugin-switcher/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12118/'] |
73,162 | <p>Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?</p>
| [{'answer_id': 73203, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 2, 'selected': False, 'text': '<p>The FlashWindowEx Win32 API is the call used to do this. The documentation for it is at:\n<a href="http://msdn.microsoft.com/en-us/library/ms679347(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms679347(VS.85).aspx</a></p>\n'}, {'answer_id': 73208, 'author': 'nathaniel', 'author_id': 11947, 'author_profile': 'https://Stackoverflow.com/users/11947', 'pm_score': 2, 'selected': False, 'text': '<pre><code>HWND hHandle = FindWindow(NULL,"YourApplicationName");\nFLASHWINFO pf;\npf.cbSize = sizeof(FLASHWINFO);\npf.hwnd = hHandle;\npf.dwFlags = FLASHW_TIMER|FLASHW_TRAY; // (or FLASHW_ALL to flash and if it is not minimized)\npf.uCount = 8;\npf.dwTimeout = 75;\n\nFlashWindowEx(&pf);\n</code></pre>\n\n<p>Stolen from experts-exchange member gtokas.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx" rel="nofollow noreferrer">FlashWindowEx</a>.</p>\n'}, {'answer_id': 73209, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 0, 'selected': False, 'text': '<p>I believe you\'re looking for <a href="http://msdn.microsoft.com/en-us/library/ms633539.aspx" rel="nofollow noreferrer"><code>SetForegroundWindow</code></a>.</p>\n'}, {'answer_id': 73287, 'author': 'Ian Boyd', 'author_id': 12597, 'author_profile': 'https://Stackoverflow.com/users/12597', 'pm_score': 2, 'selected': False, 'text': '<p>From a Raymond Chen blog entry: </p>\n\n<blockquote>\n <p><strong><a href="http://blogs.msdn.com/oldnewthing/archive/2008/05/12/8490184.aspx" rel="nofollow noreferrer">How do I flash my window caption and taskbar button manually?</a></strong></p>\n \n <p>How do I flash my window caption and\n taskbar button manually? Commenter\n Jonathan Scheepers wonders about those\n programs that flash their taskbar\n button indefinitely, overriding the\n default flash count set by\n SysteParametersInfo(SPI_SETFOREGROUNDFLASHCOUNT).</p>\n \n <p>The FlashWindowEx function and its\n simpler precursor FlashWindow let a\n program flash its window caption and\n taskbar button manually. The window\n manager flashes the caption\n automatically (and Explorer follows\n the caption by flashing the taskbar\n button) if a program calls\n SetForegroundWindow when it doesn\'t\n have permission to take foreground,\n and it is that automatic flashing that\n the SPI_SETFOREGROUNDFLASHCOUNT\n setting controls.</p>\n \n <p>For illustration purposes, I\'ll\n demonstrate flashing the caption\n manually. This is generally speaking\n not recommended, but since you asked,\n I\'ll show you how. And then promise\n you won\'t do it.</p>\n \n <p>Start with the scratch program and\n make this simple change:</p>\n\n<pre><code>void\nOnSize(HWND hwnd, UINT state, int cx, int cy)\n{\n if (state == SIZE_MINIMIZED) {\n FLASHWINFO fwi = { sizeof(fwi), hwnd,\n FLASHW_TIMERNOFG | FLASHW_ALL };\n FlashWindowEx(&fwi);\n }\n}\n</code></pre>\n \n <p>Compile and run this program, then\n minimize it. When you do, its taskbar\n button flashes indefinitely until you\n click on it. The program responds to\n being minimzed by calling the\n FlashWindowEx function asking for\n everything possible (currently the\n caption and taskbar button) to be\n flashed until the window comes to the\n foreground.</p>\n \n <p>Other members of the FLASHWINFO\n structure let you customize the\n flashing behavior further, such as\n controlling the flash frequency and\n the number of flashes. and if you\n really want to take control, you can\n use FLASHW_ALL and FLASHW_STOP to turn\n your caption and taskbar button on and\n off exactly the way you want it. (Who\n knows, maybe you want to send a\n message in Morse code.)</p>\n \n <p>Published Monday, May 12, 2008 7:00 AM\n by oldnewthing Filed under: Code</p>\n</blockquote>\n'}, {'answer_id': 73383, 'author': 'dummy', 'author_id': 6297, 'author_profile': 'https://Stackoverflow.com/users/6297', 'pm_score': 6, 'selected': True, 'text': '<p>FlashWindowEx is the way to go. See <a href="http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx" rel="noreferrer">here for MSDN documentation</a></p>\n\n<pre><code>[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool FlashWindowEx(ref FLASHWINFO pwfi);\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct FLASHWINFO\n{\n public UInt32 cbSize;\n public IntPtr hwnd;\n public UInt32 dwFlags;\n public UInt32 uCount;\n public UInt32 dwTimeout;\n}\n\npublic const UInt32 FLASHW_ALL = 3; \n</code></pre>\n\n<p>Calling the Function:</p>\n\n<pre><code>FLASHWINFO fInfo = new FLASHWINFO();\n\nfInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));\nfInfo.hwnd = hWnd;\nfInfo.dwFlags = FLASHW_ALL;\nfInfo.uCount = UInt32.MaxValue;\nfInfo.dwTimeout = 0;\n\nFlashWindowEx(ref fInfo);\n</code></pre>\n\n<p>This was shamelessly plugged from <a href="http://pinvoke.net/default.aspx/user32/FlashWindowEx.html" rel="noreferrer">Pinvoke.net</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6896/'] |
73,168 | <p>I am trying to scrape an html table and save its data in a database. What strategies/solutions have you found to be helpful in approaching this program.</p>
<p>I'm most comfortable with Java and PHP but really a solution in any language would be helpful.</p>
<p>EDIT: For more detail, the UTA (Salt Lake's Bus system) provides bus schedules on its website. Each schedule appears in a table that has stations in the header and times of departure in the rows. I would like to go through the schedules and save the information in the table in a form that I can then query. </p>
<p>Here's the <a href="http://www.rideuta.com/ridingUTA/schedules/routeSchedules.aspx" rel="nofollow noreferrer">starting point</a> for the schedules </p>
| [{'answer_id': 73213, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 2, 'selected': False, 'text': '<p>There is a nice book about this topic: <a href="http://oreilly.com/catalog/9780596005771/" rel="nofollow noreferrer">Spidering Hacks by Kevin Hemenway and Tara Calishain</a>. </p>\n'}, {'answer_id': 73216, 'author': 'David Cumps', 'author_id': 4329, 'author_profile': 'https://Stackoverflow.com/users/4329', 'pm_score': 3, 'selected': True, 'text': '<p>It all depends on how properly your HTML to scrape is? If it\'s valid XHTML, you can simply use some XPath queries on it to get whatever you want.</p>\n\n<p>Example of xpath in php: <a href="http://blogoscoped.com/archive/2004_06_23_index.html#108802750834787821" rel="nofollow noreferrer">http://blogoscoped.com/archive/2004_06_23_index.html#108802750834787821</a></p>\n\n<p>A helper class to scrape a table into an array: <a href="http://www.tgreer.com/class_http_php.html" rel="nofollow noreferrer">http://www.tgreer.com/class_http_php.html</a></p>\n'}, {'answer_id': 73217, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 1, 'selected': False, 'text': '<p>I have tried screen-scraping before, but I found it to be very brittle, especially with dynamically-generated code.\nI found a third-party DOM-parser and used it to navigate the source code with Regex-like matching patterns in order to find the data I needed.</p>\n\n<p>I suggested trying to find out if the owners of the site have a published API (often Web Services) for retrieving data from their system. If not, then good luck to you.</p>\n'}, {'answer_id': 73236, 'author': 'Petey', 'author_id': 2059, 'author_profile': 'https://Stackoverflow.com/users/2059', 'pm_score': 2, 'selected': False, 'text': "<p>I've found that scripting languages are generally better suited for doing such tasks. I personally prefer Python, but PHP will work as well. Chopping, mincing and parsing strings in Java is just too much work.</p>\n"}, {'answer_id': 73321, 'author': 'pianohacker', 'author_id': 10956, 'author_profile': 'https://Stackoverflow.com/users/10956', 'pm_score': 1, 'selected': False, 'text': '<p>This would be by far the easiest with Perl, and the following CPAN modules:</p>\n\n<ul>\n<li><a href="http://metacpan.org/pod/HTML::Parser" rel="nofollow noreferrer">http://metacpan.org/pod/HTML::Parser</a></li>\n<li><a href="http://metacpan.org/pod/LWP" rel="nofollow noreferrer">http://metacpan.org/pod/LWP</a></li>\n<li><a href="http://metacpan.org/pod/DBD/mysql" rel="nofollow noreferrer">http://metacpan.org/pod/DBD/mysql</a></li>\n<li><a href="http://metacpan.org/pod/DBI.pm" rel="nofollow noreferrer">http://metacpan.org/pod/DBI.pm</a></li>\n</ul>\n\n<p>CPAN being the main distribution mechanism for Perl modules, and accessible by running the following shell command, for example:</p>\n\n<p><code>\n # cpan HTML::Parser\n</code></p>\n\n<p>If you\'re on Windows, things will be more interesting, but you can still do it: <a href="http://www.perlmonks.org/?node_id=583586" rel="nofollow noreferrer">http://www.perlmonks.org/?node_id=583586</a></p>\n'}, {'answer_id': 73505, 'author': 'cjm', 'author_id': 8355, 'author_profile': 'https://Stackoverflow.com/users/8355', 'pm_score': 1, 'selected': False, 'text': '<p>pianohacker overlooked the <a href="http://metacpan.org/pod/HTML::TableExtract" rel="nofollow noreferrer">HTML::TableExtract</a> module, which was designed for exactly this sort of thing. You\'d still need <a href="http://metacpan.org/pod/LWP" rel="nofollow noreferrer">LWP</a> to retrieve the table.</p>\n'}, {'answer_id': 279752, 'author': 'Thorvaldur', 'author_id': 35781, 'author_profile': 'https://Stackoverflow.com/users/35781', 'pm_score': 1, 'selected': False, 'text': '<p>If what you want is a form a csv table then you can use this:\nusing python:</p>\n\n<p>for example imagine you want to scrape forex quotes in csv form from some site like: <a href="http://www.oanda.com/convert/fxhistory?date_fmt=us&date=11/10/08&date1=01/01/08&exch=USD&exch2=USD&expr=AUD&expr2=AUD&lang=en&margin_fixed=0&format=CSV&redirected=1" rel="nofollow noreferrer">fxoanda</a></p>\n\n<p>then...</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\nimport urllib,string,csv,sys,os\nfrom string import replace\n\ndate_s = \'&date1=01/01/08\'\ndate_f = \'&date=11/10/08\'\nfx_url = \'http://www.oanda.com/convert/fxhistory?date_fmt=us\'\nfx_url_end = \'&lang=en&margin_fixed=0&format=CSV&redirected=1\'\ncur1,cur2 = \'USD\',\'AUD\'\nfx_url = fx_url + date_f + date_s + \'&exch=\' + cur1 +\'&exch2=\' + cur1\nfx_url = fx_url +\'&expr=\' + cur2 + \'&expr2=\' + cur2 + fx_url_end\ndata = urllib.urlopen(fx_url).read()\nsoup = BeautifulSoup(data)\ndata = str(soup.findAll(\'pre\', limit=1))\ndata = replace(data,\'[<pre>\',\'\')\ndata = replace(data,\'</pre>]\',\'\')\nfile_location = \'/Users/location_edit_this\'\nfile_name = file_location + \'usd_aus.csv\'\nfile = open(file_name,"w")\nfile.write(data)\nfile.close()\n</code></pre>\n\n<p>once you have it in this form you can convert the data to any form you like.</p>\n'}, {'answer_id': 4850867, 'author': 'immutabl', 'author_id': 2671514, 'author_profile': 'https://Stackoverflow.com/users/2671514', 'pm_score': 1, 'selected': False, 'text': "<p>At the risk of starting a shitstorm here on SO, I'd suggest that if the format of the table never changes, you could just about get away with using Regularexpressions to parse and capture the content you need.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3274/'] |
73,187 | <p>I want to use a specific foreign language font for a Blackberry application. How is such a font created and loaded onto the Blackberry device?</p>
<p>For example: ਪੰਜਾਬੀ </p>
| [{'answer_id': 75027, 'author': 'Arc the daft', 'author_id': 8615, 'author_profile': 'https://Stackoverflow.com/users/8615', 'pm_score': 2, 'selected': True, 'text': '<p>A quick google search shows that the same thing has been asked at <a href="http://www.blackberryforums.com/developer-forum/100107-using-custom-fonts.html" rel="nofollow noreferrer">blackberry forums</a>.</p>\n\n<p>The solution they came up with is a class for loading the font from a <a href="http://www.fileinfo.net/extension/fnt" rel="nofollow noreferrer">fnt file</a>.</p>\n\n<p>There are <a href="http://www.google.com/search?hl=en&q=free+.fnt+editor&btnG=Search" rel="nofollow noreferrer">programs available</a> to import and edit fnt files.</p>\n'}, {'answer_id': 5527212, 'author': 'hakim', 'author_id': 575772, 'author_profile': 'https://Stackoverflow.com/users/575772', 'pm_score': 2, 'selected': False, 'text': '<p>for Blackberry OS 5 or above, you can use class <a href="http://docs.blackberry.com/en/developers/deliverables/11958/Load_and_use_a_custom_font_899948_11.jsp" rel="nofollow">FontFamily</a> to load your custom font into application.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12113/'] |
73,194 | <p>I'm receiving a recovery feed from an exchange for recovering data missed from their primary feed.</p>
<p>The exchange <strong>strongly</strong> recommends listening to the recovery feed only when data is needed, and leaving the multicast once I have recovered the data I need.</p>
<p>My question is, if I am using asio, and not reading from the NIC when I don't need it, what is the harm? The messages have sequence numbers, so I can't accidentally process an old message "left" on the card.</p>
<p>Is this really harming my application?</p>
| [{'answer_id': 73266, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 3, 'selected': False, 'text': "<p>It's likely <strong>not</strong> harming your application so much as harming your machine - since the nic is still configured into the multicast group, it's still listening to those messages and passing them up, before your software ignores them and they get discarded. That's a lot of extra work that your network stack and kernel are doing, and therefore a lot of extra load on the machine in general, not just your app.</p>\n"}, {'answer_id': 75671, 'author': 'Murali Suriar', 'author_id': 6306, 'author_profile': 'https://Stackoverflow.com/users/6306', 'pm_score': 2, 'selected': False, 'text': '<p>Listening to your recovery feed could also have a potential impact on a network level. As pjz mentioned, your NIC and IP stack will have more frames/packets to process. In addition, more of your available bandwidth is being used up by data that is not being used by your application; this could lead to dropped frames if there is congestion on your link. Whether congestion is likely to occur depends on whether your server is 100Mb or 1Gb attached, how much other traffic your host is sending/receiving, etc.</p>\n\n<p>Another potential concern is the impact on other hosts. If the switch your host is attached to does not have <a href="http://en.wikipedia.org/wiki/IGMP_snooping" rel="nofollow noreferrer">IGMP snooping</a> enabled, then all hosts on the same VLAN will receive the additional multicast traffic, which could lead them to experience the same problems as mentioned above.</p>\n\n<p>If you have a networking team administering your network for you, it may be worth seeking out some recommendations from them? If you feel it is necessary to subscribe to a redundant feed, it would seem prudent to work out what level of redundancy already exists in your network and how likely it is that messages on the primary feed will be lost.</p>\n'}, {'answer_id': 107939, 'author': 'Andrew Edgecombe', 'author_id': 11694, 'author_profile': 'https://Stackoverflow.com/users/11694', 'pm_score': 1, 'selected': False, 'text': '<p>An addition to <a href="https://stackoverflow.com/users/6306/muz">muz\'s</a> comment...</p>\n\n<p>It\'s unlikely that this will make any difference to your system, but it\'s worth being aware that there is an overhead associated with maintaining a multicast membership (assuming that you\'re using IGMP - which is probably reasonable given the restriction about "leaving the multicast")</p>\n\n<p>IGMP requires the sending and processing of multicast group memberships at regular intervals. And (as alluded to in muz\'s comment) if you have any switches or routers between you and the multicast source that are capable of igmp snooping then they are able to disable the multicast for a given network.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2167252/'] |
73,198 | <p>When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?</p>
| [{'answer_id': 73237, 'author': 'Glenn Slaven', 'author_id': 2975, 'author_profile': 'https://Stackoverflow.com/users/2975', 'pm_score': -1, 'selected': False, 'text': "<p>Not sure why you'd want to do that. The underlying data type can't store more than one char, by representing it as a string variable you introduce the need to check lengths before committing to the db, where as if you leave it as is you can just call ToString() on the char to get a string</p>\n"}, {'answer_id': 73812, 'author': 'Grant Wagner', 'author_id': 9254, 'author_profile': 'https://Stackoverflow.com/users/9254', 'pm_score': 0, 'selected': False, 'text': '<pre><code>var whatever =\n from x in something\n select new { yourString = Char.ToString(x.theChar); }\n</code></pre>\n'}, {'answer_id': 73976, 'author': 'James Curran', 'author_id': 12725, 'author_profile': 'https://Stackoverflow.com/users/12725', 'pm_score': 3, 'selected': True, 'text': "<p>You could modify the {database}.designer.cs file. I don't have one handy to check, but I believe it's fairly straight forward --- you'll just have to plow through a lot of code, and remember to re-apply the change if you ever regenerate it.</p>\n\n<p>Alternately, you could create your own class and handle it in the select. For example, given the LINQ generated class:</p>\n\n<pre><code>class MyTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n char OneChar {get; set;}\n}\n</code></pre>\n\n<p>you could easily create: </p>\n\n<pre><code>class MyFixedTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n string OneChar {get; set;}\n public MyFixedTable(MyTable t)\n {\n this,MyNum = t.MyNum;\n this.YourNum = t.YourNum;\n this.OneChar = new string(t.OneChar, 1);\n }\n}\n</code></pre>\n\n<p>Then instead of writing:</p>\n\n<pre><code>var q = from t in db.MyTable\n select t;\n</code></pre>\n\n<p>write</p>\n\n<pre><code>var q = from t in db.MyTable\n select new MyFixTable(t);\n</code></pre>\n"}, {'answer_id': 173294, 'author': 'Jonathan Allen', 'author_id': 5274, 'author_profile': 'https://Stackoverflow.com/users/5274', 'pm_score': 0, 'selected': False, 'text': '<p>Just go to the designer window and change the type to string. I do it all the time, as I find Strings to be easier to use than Char in my code.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12260/'] |
73,212 | <p>How can I exclude the bin folder from SourceSafe in a Visual Studio 2008 web application? I want to be able to check in everything recursively from the solution node without picking up anything in the bin folder.</p>
| [{'answer_id': 73311, 'author': 'cori', 'author_id': 8151, 'author_profile': 'https://Stackoverflow.com/users/8151', 'pm_score': 3, 'selected': True, 'text': '<ul>\n<li>Right-click the folder in your\nproject</li>\n<li>select "Exclude from project"</li>\n</ul>\n'}, {'answer_id': 254063, 'author': 'weiran', 'author_id': 33137, 'author_profile': 'https://Stackoverflow.com/users/33137', 'pm_score': -1, 'selected': False, 'text': "<p>You can hide the folder through Windows explorer, although it'll disappear from your Visual Studio Solution Exporer, I don't think that'll affect the website.</p>\n"}, {'answer_id': 46753898, 'author': 'autopilot', 'author_id': 2545990, 'author_profile': 'https://Stackoverflow.com/users/2545990', 'pm_score': 0, 'selected': False, 'text': '<p>Yes, you could exclude files from source control in your projects.</p>\n\n<p>For example (In Visual Studio), if you added the ConnectionStrings.config file to your project then select the ConnectionStrings.config file in the Solution Explorer and then select "Exclude ConnectionStrings.config from Source Control" from the File->Source Control menu. Now, your file will be ignored by Source Control and won\'t be checked into Source Control.</p>\n\n<p>Note: If you right click on the ConnectionStrings.config file in Solution Explorer and bring up the context menu for it then there is a "Exclude From Project" menu item, THIS IS NOT the option to exclude from Source Control. So do not get confused between the "Exclude ConnectionStrings.config from Source Control" and "Exclude From Project"; they are not the same thing. "Exclude ConnectionStrings.config from Source Control" can only be accessed in the File->Source Control menu.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12599/'] |
73,227 | <p>I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.</p>
| [{'answer_id': 73249, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': -1, 'selected': False, 'text': '<p>Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function. A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.</p>\n'}, {'answer_id': 73255, 'author': 'chessguy', 'author_id': 1908025, 'author_profile': 'https://Stackoverflow.com/users/1908025', 'pm_score': 2, 'selected': False, 'text': "<p>I don't have a ton of experience with this, but the way I would describe it is that a delegate is a wrapper around any function, whereas a lambda expression is itself an anonymous function.</p>\n"}, {'answer_id': 73259, 'author': 'Dan Shield', 'author_id': 4633, 'author_profile': 'https://Stackoverflow.com/users/4633', 'pm_score': 4, 'selected': False, 'text': "<p>Delegates are equivalent to function pointers/method pointers/callbacks (take your pick), and lambdas are pretty much simplified anonymous functions. At least that's what I tell people.</p>\n"}, {'answer_id': 73271, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 2, 'selected': False, 'text': '<p>lambdas are simply syntactic sugar on a delegate. The compiler ends up converting lambdas into delegates.</p>\n\n<p>These are the same, I believe:</p>\n\n<pre><code>Delegate delegate = x => "hi!";\nDelegate delegate = delegate(object x) { return "hi";};\n</code></pre>\n'}, {'answer_id': 73318, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 2, 'selected': False, 'text': '<p>A delegate is a function signature; something like </p>\n\n<pre><code>delegate string MyDelegate(int param1);\n</code></pre>\n\n<p>The delegate does not implement a body. </p>\n\n<p>The lambda is a function call that matches the signature of the delegate. For the above delegate, you might use any of;</p>\n\n<pre><code>(int i) => i.ToString();\n(int i) => "ignored i";\n(int i) => "Step " + i.ToString() + " of 10";\n</code></pre>\n\n<p>The <code>Delegate</code> type is badly named, though; creating an object of type <code>Delegate</code> actually creates a variable which can hold functions -- be they lambdas, static methods, or class methods.</p>\n'}, {'answer_id': 73367, 'author': 'Curt Hagenlocher', 'author_id': 533, 'author_profile': 'https://Stackoverflow.com/users/533', 'pm_score': 2, 'selected': False, 'text': '<p>A delegate is always just basically a function pointer. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For instance,</p>\n\n<pre><code>Func<int, int> f = x => x + 1;\nExpression<Func<int, int>> exprTree = x => x + 1;\n</code></pre>\n\n<p>The first line produces a delegate, while the second produces an expression tree.</p>\n'}, {'answer_id': 73384, 'author': 'Steve g', 'author_id': 12092, 'author_profile': 'https://Stackoverflow.com/users/12092', 'pm_score': 1, 'selected': False, 'text': '<p>Delegates are really just structural typing for functions. You could do the same thing with nominal typing and implementing an anonymous class that implements an interface or abstract class, but that ends up being a lot of code when only one function is needed.</p>\n\n<p>Lambda comes from the idea of lambda calculus of Alonzo Church in the 1930s. It is an anonymous way of creating functions. They become especially useful for composing functions</p>\n\n<p>So while some might say lambda is syntactic sugar for delegates, I would says delegates are a bridge for easing people into lambdas in c#.</p>\n'}, {'answer_id': 73408, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 0, 'selected': False, 'text': '<p>Lambdas are simplified versions of delegates. They have some of the the properties of a <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" rel="nofollow noreferrer">closure</a> like anonymous delegates, but also allow you to use implied typing. A lambda like this:</p>\n\n<pre><code>something.Sort((x, y) => return x.CompareTo(y));\n</code></pre>\n\n<p>is a lot more concise than what you can do with a delegate:</p>\n\n<pre><code>something.Sort(sortMethod);\n...\n\nprivate int sortMethod(SomeType one, SomeType two)\n{\n one.CompareTo(two)\n}\n</code></pre>\n'}, {'answer_id': 73448, 'author': 'Karg', 'author_id': 12685, 'author_profile': 'https://Stackoverflow.com/users/12685', 'pm_score': 5, 'selected': False, 'text': '<p>One difference is that an anonymous delegate can omit parameters while a lambda must match the exact signature. Given:</p>\n\n<pre><code>public delegate string TestDelegate(int i);\n\npublic void Test(TestDelegate d)\n{}\n</code></pre>\n\n<p>you can call it in the following four ways (note that the second line has an anonymous delegate that does not have any parameters):</p>\n\n<pre><code>Test(delegate(int i) { return String.Empty; });\nTest(delegate { return String.Empty; });\nTest(i => String.Empty);\nTest(D);\n\nprivate string D(int i)\n{\n return String.Empty;\n}\n</code></pre>\n\n<p>You cannot pass in a lambda expression that has no parameters or a method that has no parameters. These are not allowed:</p>\n\n<pre><code>Test(() => String.Empty); //Not allowed, lambda must match signature\nTest(D2); //Not allowed, method must match signature\n\nprivate string D2()\n{\n return String.Empty;\n}\n</code></pre>\n'}, {'answer_id': 73819, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 8, 'selected': True, 'text': '<p>They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.</p>\n\n<p>Lambdas are very much like other methods, except for a couple subtle differences.</p>\n\n<ol>\n<li>A normal method is defined in a <a href="http://en.wikipedia.org/wiki/Statement_(programming)" rel="noreferrer">"statement"</a> and tied to a permanent name, whereas a lambda is defined "on the fly" in an <a href="http://en.wikipedia.org/wiki/Expression_(programming)" rel="noreferrer">"expression"</a> and has no permanent name.</li>\n<li>Some lambdas can be used with .NET expression trees, whereas methods cannot.</li>\n</ol>\n\n<p>A delegate is defined like this:</p>\n\n<pre><code>delegate Int32 BinaryIntOp(Int32 x, Int32 y);\n</code></pre>\n\n<p>A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return.</p>\n\n<p>A lambda might be defined like this:</p>\n\n<pre><code>BinaryIntOp sumOfSquares = (a, b) => a*a + b*b;\n</code></pre>\n\n<p>Another thing to note is that although the generic Func and Action types are often considered "lambda types", they are just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action.</p>\n\n<p>Here is an illustration of how Func and Action are "not just for lambdas":</p>\n\n<pre><code>Int32 DiffOfSquares(Int32 x, Int32 y)\n{\n return x*x - y*y;\n}\n\nFunc<Int32, Int32, Int32> funcPtr = DiffOfSquares;\n</code></pre>\n\n<p>Another useful thing to know is that delegate types (not methods themselves) with the same signature but different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them.</p>\n\n<p>Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have "first-class functions". You can use a function\'s name assigned to a delegate variable to essentially create an object representing that function. But it\'s really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you\'ll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much.</p>\n\n<p>Update: Also see <a href="https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#73448">Karg\'s answer</a> illustrating the difference between anonymous delegates vs. methods & lambdas.</p>\n\n<p>Update 2: <a href="https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#74414">James Hart</a> makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs.</p>\n'}, {'answer_id': 74079, 'author': 'Echostorm', 'author_id': 12862, 'author_profile': 'https://Stackoverflow.com/users/12862', 'pm_score': 0, 'selected': False, 'text': "<p>Heres an example I put up awhile on my lame blog. Say you wanted to update a label from a worker thread. I've got 4 examples of how to update that label from 1 to 50 using delegates, anon delegates and 2 types of lambdas.</p>\n\n<pre><code> private void button2_Click(object sender, EventArgs e) \n { \n BackgroundWorker worker = new BackgroundWorker(); \n worker.DoWork += new DoWorkEventHandler(worker_DoWork); \n worker.RunWorkerAsync(); \n } \n\n private delegate void UpdateProgDelegate(int count); \n private void UpdateText(int count) \n { \n if (this.lblTest.InvokeRequired) \n { \n UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText); \n this.Invoke(updateCallBack, new object[] { count }); \n } \n else \n { \n lblTest.Text = count.ToString(); \n } \n } \n\n void worker_DoWork(object sender, DoWorkEventArgs e) \n { \n /* Old Skool delegate usage. See above for delegate and method definitions */ \n for (int i = 0; i < 50; i++) \n { \n UpdateText(i); \n Thread.Sleep(50); \n } \n\n // Anonymous Method \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((MethodInvoker)(delegate() \n { \n lblTest.Text = i.ToString(); \n })); \n Thread.Sleep(50); \n } \n\n /* Lambda using the new Func delegate. This lets us take in an int and \n * return a string. The last parameter is the return type. so \n * So Func<int, string, double> would take in an int and a string \n * and return a double. count is our int parameter.*/ \n Func<int, string> UpdateProgress = (count) => lblTest.Text = count.ToString(); \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke(UpdateProgress, i); \n Thread.Sleep(50); \n } \n\n /* Finally we have a totally inline Lambda using the Action delegate \n * Action is more or less the same as Func but it returns void. We could \n * use it with parameters if we wanted to like this: \n * Action<string> UpdateProgress = (count) => lblT…*/ \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((Action)(() => lblTest.Text = i.ToString())); \n Thread.Sleep(50); \n } \n }\n</code></pre>\n"}, {'answer_id': 74283, 'author': 'Peter Ritchie', 'author_id': 5620, 'author_profile': 'https://Stackoverflow.com/users/5620', 'pm_score': 2, 'selected': False, 'text': '<p>A delegate is a reference to a method with a particular parameter list and return type. It may or may not include an object.</p>\n\n<p>A lambda-expression is a form of anonymous function.</p>\n'}, {'answer_id': 74303, 'author': 'justin.m.chase', 'author_id': 12958, 'author_profile': 'https://Stackoverflow.com/users/12958', 'pm_score': 2, 'selected': False, 'text': '<p>A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.</p>\n\n<p>You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.</p>\n\n<p>The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.</p>\n'}, {'answer_id': 74414, 'author': 'James Hart', 'author_id': 5755, 'author_profile': 'https://Stackoverflow.com/users/5755', 'pm_score': 5, 'selected': False, 'text': "<p>The question is a little ambiguous, which explains the wide disparity in answers you're getting.</p>\n\n<p>You actually asked what the difference is between lambdas and delegates in the .NET framework; that might be one of a number of things. Are you asking:</p>\n\n<ul>\n<li><p>What is the difference between lambda expressions and anonymous delegates in the C# (or VB.NET) language?</p></li>\n<li><p>What is the difference between System.Linq.Expressions.LambdaExpression objects and System.Delegate objects in .NET 3.5?</p></li>\n<li><p>Or something somewhere between or around those extremes?</p></li>\n</ul>\n\n<p>Some people seem to be trying to give you the answer to the question 'what is the difference between C# Lambda expressions and .NET System.Delegate?', which doesn't make a whole lot of sense.</p>\n\n<p>The .NET framework does not in itself understand the concepts of anonymous delegates, lambda expressions, or closures - those are all things defined by language specifications. Think about how the C# compiler translates the definition of an anonymous method into a method on a generated class with member variables to hold closure state; to .NET, there's nothing anonymous about the delegate; it's just anonymous to the C# programmer writing it. That's equally true of a lambda expression assigned to a delegate type.</p>\n\n<p>What .NET <em>DOES</em> understand is the idea of a delegate - a type that describes a method signature, instances of which represent either bound calls to specific methods on specific objects, or unbound calls to a particular method on a particular type that can be invoked against any object of that type, where said method adheres to the said signature. Such types all inherit from System.Delegate.</p>\n\n<p>.NET 3.5 also introduces the System.Linq.Expressions namespace, which contains classes for describing code expressions - and which can also therefore represent bound or unbound calls to methods on particular types or objects. LambdaExpression instances can then be compiled into actual delegates (whereby a dynamic method based on the structure of the expression is codegenned, and a delegate pointer to it is returned).</p>\n\n<p>In C# you can produce instances of System.Expressions.Expression types by assigning a lambda expression to a variable of said type, which will produce the appropriate code to construct the expression at runtime.</p>\n\n<p>Of course, if you <em>were</em> asking what the difference is between lambda expressions and anonymous methods in C#, after all, then all this is pretty much irelevant, and in that case the primary difference is brevity, which leans towards anonymous delegates when you don't care about parameters and don't plan on returning a value, and towards lambdas when you want type inferenced parameters and return types.</p>\n\n<p>And lambda expressions support expression generation.</p>\n"}, {'answer_id': 6460111, 'author': 'Philip Beber', 'author_id': 813016, 'author_profile': 'https://Stackoverflow.com/users/813016', 'pm_score': 2, 'selected': False, 'text': '<p>It is pretty clear the question was meant to be "what\'s the difference between lambdas and <strong>anonymous</strong> delegates?" Out of all the answers here only one person got it right - the main difference is that lambdas can be used to create expression trees as well as delegates.</p>\n\n<p>You can read more on MSDN: <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb397687.aspx</a></p>\n'}, {'answer_id': 27059973, 'author': 'Olorin', 'author_id': 1581875, 'author_profile': 'https://Stackoverflow.com/users/1581875', 'pm_score': 0, 'selected': False, 'text': '<p><em>I assume that your question concerns c# and not .NET, because of the ambiguity of your question, as .NET does not get alone - that is, without c# - comprehension of delegates and lambda expressions.</em></p>\n\n<p>A (<em>normal</em>, in opposition to so called <em>generic</em> delegates, <em>cf</em> later) delegate should be seen as a kind of c++ <code>typedef</code> of a function pointer type, for instance in c++ :</p>\n\n<pre><code>R (*thefunctionpointer) ( T ) ;\n</code></pre>\n\n<p>typedef\'s the type <code>thefunctionpointer</code> which is the type of pointers to a function taking an object of type <code>T</code> and returning an object of type <code>R</code>. You would use it like this :</p>\n\n<pre><code>thefunctionpointer = &thefunction ;\nR r = (*thefunctionpointer) ( t ) ; // where t is of type T\n</code></pre>\n\n<p>where <code>thefunction</code> would be a function taking a <code>T</code> and returning an <code>R</code>.</p>\n\n<p>In c# you would go for</p>\n\n<pre><code>delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed\n</code></pre>\n\n<p>and you would use it like this :</p>\n\n<pre><code>thedelegate thedel = thefunction ;\nR r = thedel ( t ) ; // where t is of type T\n</code></pre>\n\n<p>where <code>thefunction</code> would be a function taking a <code>T</code> and returning an <code>R</code>. This is for delegates, so called normal delegates.</p>\n\n<p>Now, you also have generic delegates in c#, which are delegates that are generic, <em>i.e.</em> that are "templated" so to speak, using thereby a c++ expression. They are defined like this :</p>\n\n<pre><code>public delegate TResult Func<in T, out TResult>(T arg);\n</code></pre>\n\n<p>And you can used them like this :</p>\n\n<pre><code>Func<double, double> thefunctor = thefunction2; // call it a functor because it is\n // really as a functor that you should\n // "see" it\ndouble y = thefunctor(2.0);\n</code></pre>\n\n<p>where <code>thefunction2</code> is a function taking as argument and returning a <code>double</code>.</p>\n\n<p>Now imagine that instead of <code>thefunction2</code> I would like to use a "function" that is nowhere defined for now, by a statement, and that I will never use later. Then c# allows us to use the <em>expression</em> of this function. By expression I mean the "mathematical" (or functional, to stick to programs) expression of it, for instance : to a <code>double x</code> I will <em>associate</em> the <code>double</code> <code>x*x</code>. In maths you write this using <a href="https://math.stackexchange.com/questions/651205/regarding-the-notation-f-a-mapsto-b">the "\\mapsto" latex symbol</a>. In c# the functional notation has been borrowed : <code>=></code>. For instance :</p>\n\n<pre><code>Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not\n // mandatory\n</code></pre>\n\n<p><code>(double x) => x * x</code> is an <a href="http://en.wikipedia.org/wiki/Expression_(computer_science)" rel="nofollow noreferrer"><em>expression</em></a>. It is not a type, whereas delegates (generic or not) are.</p>\n\n<p>Morality ? At end, what is a delegate (resp. generic delegate), if not a function pointer type (resp. wrapped+smart+generic function pointer type), huh ? Something else ! See <a href="http://blog.monstuff.com/archives/000037.html" rel="nofollow noreferrer">this</a> and <a href="http://msdn.microsoft.com/fr-fr/library/system.delegate%28v=vs.110%29.aspx" rel="nofollow noreferrer">that</a>.</p>\n'}, {'answer_id': 50314365, 'author': 'Yogesh Prajapati', 'author_id': 4959238, 'author_profile': 'https://Stackoverflow.com/users/4959238', 'pm_score': 1, 'selected': False, 'text': '<p>Some basic here.\n"Delegate" is actually the name for a variable that holds a reference to a method or a lambda</p>\n\n<p>This is a anonymous method - </p>\n\n<pre><code>(string testString) => { Console.WriteLine(testString); };\n</code></pre>\n\n<p>As anonymous method do not have any name we need a delegate in which we can assign both of these method or expression. For Ex.</p>\n\n<pre><code>delegate void PrintTestString(string testString); // declare a delegate\n\nPrintTestString print = (string testString) => { Console.WriteLine(testString); }; \nprint();\n</code></pre>\n\n<hr>\n\n<p>Same with the lambda expression. Usually we need delegate to use them</p>\n\n<pre><code>s => s.Age > someValue && s.Age < someValue // will return true/false\n</code></pre>\n\n<p>We can use a func delegate to use this expression.</p>\n\n<pre><code>Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;\n\nbool result = checkStudentAge ( Student Object);\n</code></pre>\n'}, {'answer_id': 67167690, 'author': 'Ievgen Martynov', 'author_id': 927030, 'author_profile': 'https://Stackoverflow.com/users/927030', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Short version:</strong></p>\n<p>A delegate is a <strong>type</strong> that represents references to methods. C# <strong>lambda</strong> expression is a syntax to create <strong>delegates</strong> or <strong>expression trees</strong>.</p>\n<p><strong>Kinda long version:</strong></p>\n<p>Delegate is not "the name for a variable" as it\'s said in the accepted answer.</p>\n<p>A delegate is a <strong>type</strong> (literally a type, if you inspect IL, it\'s a class) that represents references to methods (<a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/" rel="nofollow noreferrer">learn.microsoft.com</a>).</p>\n<p><a href="https://i.stack.imgur.com/r0lPp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0lPp.png" alt="enter image description here" /></a></p>\n<p>This type could be initiated to associate its instance with any method with a compatible signature and return type.</p>\n<pre><code>namespace System\n{\n // define a type\n public delegate TResult Func<in T, out TResult>(T arg);\n}\n\n// method with the compatible signature\npublic static bool IsPositive(int int32)\n{\n return int32 > 0;\n}\n\n// initiated and associate\nFunc<int, bool> isPositive = new Func<int, bool>(IsPositive);\n</code></pre>\n<p>C# 2.0 introduced a syntactic sugar, anonymous method, enabling methods to be defined <strong>inline</strong>.</p>\n<pre><code>Func<int, bool> isPositive = delegate(int int32)\n{\n return int32 > 0;\n};\n</code></pre>\n<p>In C# 3.0+, the above anonymous method’s inline definition can be further simplified with lambda expression</p>\n<pre><code>Func<int, bool> isPositive = (int int32) =>\n{\n return int32 > 0;\n};\n</code></pre>\n<p>C# <strong>lambda</strong> expression is a syntax to create <strong>delegates</strong> or <strong>expression trees</strong>. I believe expression trees are not the topic of this question (<a href="https://www.youtube.com/playlist?list=PLRwVmtr-pp06SlwcsqhreZ2byuozdnPlg" rel="nofollow noreferrer">Jamie King about expression trees</a>).</p>\n<p>More could be found <a href="https://weblogs.asp.net/dixin/understanding-csharp-features-5-lambda-expression" rel="nofollow noreferrer">here</a>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538/'] |
73,230 | <p>If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its <strong>not the same input name</strong> as the login. how can I prevent this?</p>
| [{'answer_id': 73283, 'author': 'Toby Mills', 'author_id': 12377, 'author_profile': 'https://Stackoverflow.com/users/12377', 'pm_score': 3, 'selected': True, 'text': '<p>Try using autocomplete="off" as an attribute of the text box. I\'ve used it in the past to stop credit card details being stored by the browser but i dont know if it works with passwords. e.g. <code>print("<input type="text" name="cc" autocomplete="off" />");</code></p>\n'}, {'answer_id': 73291, 'author': 'NGittlen', 'author_id': 10047, 'author_profile': 'https://Stackoverflow.com/users/10047', 'pm_score': 1, 'selected': False, 'text': '<p>I think that FF autofills fields based on the "name" attribute of the field so that if the password box has the name="password" and the change password box has the same it will fill in the same password in both places.\nTry changing the name attribute of one of the boxes.</p>\n'}, {'answer_id': 73392, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Some sites have 3 inputs for changing a password, one for re-entering the current password and two for entering the new password. If the re-entering input was first and got auto-filled, it wouldn't be a problem. </p>\n"}, {'answer_id': 102452, 'author': 'fernandogarcez', 'author_id': 13303, 'author_profile': 'https://Stackoverflow.com/users/13303', 'pm_score': 0, 'selected': False, 'text': '<p>Go in tools->page properties->security on the page you wish to modify.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
73,260 | <p>I've come across a few different applications that monitor my usage while on the computer, but what have you used, and like? whether it be writing down your activities in a composition notbook or install an app that reports silently to a server? what do you like?</p>
| [{'answer_id': 73282, 'author': 'cori', 'author_id': 8151, 'author_profile': 'https://Stackoverflow.com/users/8151', 'pm_score': 1, 'selected': True, 'text': '<p>For explicit time tracking for projects I use <a href="http://slimtimer.com" rel="nofollow noreferrer">SlimTimer</a>. I also run <a href="http://www.rescuetime.com/" rel="nofollow noreferrer">RescueTime</a> to track my time implicitly, but I end up not looking at that data very often.</p>\n'}, {'answer_id': 73290, 'author': 'David Smart', 'author_id': 9623, 'author_profile': 'https://Stackoverflow.com/users/9623', 'pm_score': 0, 'selected': False, 'text': '<p>I use <a href="http://www.neomem.org/" rel="nofollow noreferrer">neomem</a> to keep track of things by hand. This allows me to keep track of more than just time. I often keeps notes associated with the story. This has become a collection of knowledge that I often search.</p>\n'}, {'answer_id': 73307, 'author': 'Dr. Bob', 'author_id': 12182, 'author_profile': 'https://Stackoverflow.com/users/12182', 'pm_score': -1, 'selected': False, 'text': "<p>I prefer writing the times down using pen and paper. That way you can more fairly weigh things that would have been miscalculated if you were recording them with a stopwatch or timer.</p>\n\n<p>If you start on something and have to get up for a few minutes, a timer may count that toward your working time had you neglected to stop or pause the timer. The good-old pen and paper are going to more accurately show which tasks you focused most of your time and energy on...not just the ones that you started earliest and ended latest. It may not be 100% accurate, but neither is the timer if you don't use it properly.</p>\n\n<p>I have used both in the past, and find that there are problems with both, but I prefer the pen and paper method.</p>\n"}, {'answer_id': 73347, 'author': 'JustinD', 'author_id': 12063, 'author_profile': 'https://Stackoverflow.com/users/12063', 'pm_score': -1, 'selected': False, 'text': '<p>We use <a href="http://www.stdtime.com/" rel="nofollow noreferrer">Standard Time</a> as a Time Tracking tool and it\'s got a nice quick tasks window that is relatively small and lets you easily click checkboxes to switch between tasks. You can also create projects/customers and pre-set tasks to be loaded for each project (development, unit testing, documentation, etc...) and then just use the quick tasks window to switch which task you are currently working on without wasting too much time going through a full blown GUI. </p>\n\n<p>It\'s not cheap - about $150/user - so if it\'s for personal use it might not be the best bet, but if you\'re looking for a solution for a team of developers then I\'ve found it to be a good fit.</p>\n'}, {'answer_id': 2134357, 'author': 'y0mbo', 'author_id': 417, 'author_profile': 'https://Stackoverflow.com/users/417', 'pm_score': 0, 'selected': False, 'text': '<p>I use a paper timesheet to track my time. It looks like this:</p>\n\n<p><a href="https://i.stack.imgur.com/pmoHc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmoHc.png" alt="Analog Dashboard"></a><br>\n<sub>(source: <a href="http://redbitbluebit.com/wp-content/uploads/2009/11/timesheet.png" rel="nofollow noreferrer">redbitbluebit.com</a>)</sub> </p>\n\n<p>and as a back up, I use a paid version the excellent <a href="http://timesnapper.com/" rel="nofollow noreferrer">TimeSnapper</a> in case I need to go back and retrace anything I missed tracking the time on.</p>\n'}, {'answer_id': 2134425, 'author': 'chanda', 'author_id': 190418, 'author_profile': 'https://Stackoverflow.com/users/190418', 'pm_score': -1, 'selected': False, 'text': '<p>I use the time tracker plugin on Firefox. It tracks my surfing time of the whole day </p>\n'}, {'answer_id': 7337318, 'author': 'JHolyhead', 'author_id': 930138, 'author_profile': 'https://Stackoverflow.com/users/930138', 'pm_score': -1, 'selected': False, 'text': '<p>I\'ve been using <a href="http://www.toggl.com" rel="nofollow">Toggl</a> for about a year now and I\'ve found it to be spot on. It\'s simple to use and allows you to perform basic reporting against various criteria. You can either input time entries manually or use a stopwatch timer utility.</p>\n\n<p>I tried out several applications before I settled on Toggl. For me, the intuitiveness of the Toggl interface was what decided it. I like my productivity applications to get out of my way and let me do my job and Toggl does just that.</p>\n\n<p>There are various pricing plans, including a free one. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12550/'] |
73,261 | <p>Many of the parameters for interacting with the Office Object model in VSTO require object parameters that are passed by reference, even when the notional type of the parameter is an int or string.</p>
<ol>
<li>I suppose that this mechanism is used so that code can modify the parameter, although I can't figure out why these need to be passed as generic object instead of as their more appropriate types. Can anyone enlighten me?</li>
<li><p>The mechanism I've been using (cribbed from help and MSDN resources) essentially creates a generic object that contains the appropriate data and then passes that to the method, for example:</p>
<p>object nextBookmarkName = "NextContent";
object nextBookmark = this.Bookmarks.get_Item( ref nextBookmarkName ).Range;</p>
<p>Microsoft.Office.Interop.Word.Range newRng = this.Range( ref nextBookmark, ref nextBookmark );</p></li>
</ol>
<p>This seems like a lot of extra code, but I can't see a better way to do it. I'm sure I'm missing something; what is it? Or is this really the best practice?</p>
| [{'answer_id': 73310, 'author': 'KTamas', 'author_id': 6541, 'author_profile': 'https://Stackoverflow.com/users/6541', 'pm_score': 0, 'selected': False, 'text': "<p>I'd be interested in this too. I'm coding several apps that uses automation in Word and I even have things like</p>\n\n<pre><code>object oFalse = false, oTrue = true, oOne = 1;\n</code></pre>\n\n<p>It's very nasty, but it's the only way I know so far. </p>\n\n<p>The only thing I can think of is writing a wrapper class for the frequently used functions...</p>\n"}, {'answer_id': 74950, 'author': 'Joe', 'author_id': 13087, 'author_profile': 'https://Stackoverflow.com/users/13087', 'pm_score': 1, 'selected': True, 'text': '<p>I think it was just poor design of the original Word object model. I know that passing strings by reference can be slightly faster in the COM world because it avoids the need to make a copy, so perhaps that was part of the justification. But the downside is that the callee can modify the value, and in most cases with Word they are input parameters.</p>\n\n<p>I think your technique is the best practice. For the millions of optional parameters that many of the Word object model methods require, you can create a single static field "missing" something like: </p>\n\n<p>object missing = Type.Missing;</p>\n\n<p>// Example\nobject fileName = ...\ndocument.SaveAs(ref fileName, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing);</p>\n'}, {'answer_id': 165598, 'author': 'rasx', 'author_id': 22944, 'author_profile': 'https://Stackoverflow.com/users/22944', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with Joe. I even developed helper structs and classes like this one:</p>\n\n<pre><code>internal struct Argument\n{\n internal static object False = false;\n\n internal static object Missing = System.Type.Missing;\n\n internal static object True = true;\n}\n</code></pre>\n\n<p>And this one:</p>\n\n<pre><code>/// <summary>\n/// Defines the "special characters"\n/// in Microsoft Word that VSTO 1.x\n/// translates into C# strings.\n/// </summary>\ninternal struct Characters\n{\n /// <summary>\n /// Word Table end-of-cell marker.\n /// </summary>\n /// <remarks>\n /// Word Table end-of-row markers are also\n /// equal to this value.\n /// </remarks>\n internal static string CellBreak = "\\r\\a";\n\n /// <summary>\n /// Word line break (^l).\n /// </summary>\n internal static string LineBreak = "\\v";\n\n /// <summary>\n /// Word Paragraph break (^p).\n /// </summary>\n internal static string ParagraphBreak = "\\r";\n}\n</code></pre>\n\n<p>And a few more...</p>\n'}, {'answer_id': 256665, 'author': 'shahkalpesh', 'author_id': 23574, 'author_profile': 'https://Stackoverflow.com/users/23574', 'pm_score': 0, 'selected': False, 'text': '<p>I think, all of this is taken care of with VS.NET 2010 and new language constructs introduced in c# 4.0 (c# will have optional arguments).</p>\n\n<p>See the video by Anders Hejlberg at PDC 2008 on channel9 for changes related to office development.</p>\n\n<p>I cant find that link but this could also be helpful.<br>\n<a href="http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/" rel="nofollow noreferrer">http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8151/'] |
73,286 | <p>I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?</p>
| [{'answer_id': 73363, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 3, 'selected': False, 'text': '<p>You can\'t do this.</p>\n\n<p>If you want to output to the debugger\'s output window, call OutputDebugString.</p>\n\n<p>I found <a href="http://www.flipcode.com/archives/Message_Box_ostream.shtml" rel="noreferrer">this implementation</a> of a \'teestream\' which allows one output to go to multiple streams. You could implement a stream that sends data to OutputDebugString.</p>\n'}, {'answer_id': 73365, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Is this a case of the output screen just flashing and then dissapearing? if so you can keep it open by using cin as your last statement before return.</p>\n'}, {'answer_id': 74542, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 3, 'selected': False, 'text': '<p>You can capture the output of cout like this, for example:</p>\n\n<pre><code>std::streambuf* old_rdbuf = std::cout.rdbuf();\nstd::stringbuf new_rdbuf;\n// replace default output buffer with string buffer\nstd::cout.rdbuf(&new_rdbuf);\n\n// write to new buffer, make sure to flush at the end\nstd::cout << "hello, world" << std::endl;\n\nstd::string s(new_rdbuf.str());\n// restore the default buffer before destroying the new one\nstd::cout.rdbuf(old_rdbuf);\n\n// show that the data actually went somewhere\nstd::cout << s.size() << ": " << s;\n</code></pre>\n\n<p>Magicking it into the Visual Studio 2005 output window is left as an exercise to a Visual Studio 2005 plugin developer. But you could probably redirect it elsewhere, like a file or a custom window, perhaps by writing a custom streambuf class (see also boost.iostream).</p>\n'}, {'answer_id': 78699, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 2, 'selected': False, 'text': "<p>A combination of ben's answer and Mike Dimmick's: you would be implementing a stream_buf_ that ends up calling OutputDebugString. Maybe someone has done this already? Take a look at the two proposed Boost logging libraries.</p>\n"}, {'answer_id': 80782, 'author': 'el2iot2', 'author_id': 8668, 'author_profile': 'https://Stackoverflow.com/users/8668', 'pm_score': 0, 'selected': False, 'text': '<p>Also, depending on your intentions, and what libraries you are using, you may want to use the <a href="http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx" rel="nofollow noreferrer">TRACE macro</a> (<a href="http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library" rel="nofollow noreferrer">MFC</a>) or <a href="http://msdn.microsoft.com/en-us/library/6xkxyz08(VS.80).aspx" rel="nofollow noreferrer">ATLTRACE</a> (<a href="http://en.wikipedia.org/wiki/Active_Template_Library" rel="nofollow noreferrer">ATL</a>).</p>\n'}, {'answer_id': 6086817, 'author': 'Yakov Galka', 'author_id': 277176, 'author_profile': 'https://Stackoverflow.com/users/277176', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve finally implemented this, so I want to share it with you:</p>\n\n<pre><code>#include <vector>\n#include <iostream>\n#include <windows.h>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/tee.hpp>\n\nusing namespace std;\nnamespace io = boost::iostreams;\n\nstruct DebugSink\n{\n typedef char char_type;\n typedef io::sink_tag category;\n\n std::vector<char> _vec;\n\n std::streamsize write(const char *s, std::streamsize n)\n {\n _vec.assign(s, s+n);\n _vec.push_back(0); // we must null-terminate for WINAPI\n OutputDebugStringA(&_vec[0]);\n return n;\n }\n};\n\nint main()\n{\n typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;\n TeeDevice device(DebugSink(), *cout.rdbuf());\n io::stream_buffer<TeeDevice> buf(device);\n cout.rdbuf(&buf);\n\n cout << "hello world!\\n";\n cout.flush(); // you may need to flush in some circumstances\n}\n</code></pre>\n\n<p><strong>BONUS TIP:</strong> If you write:</p>\n\n<pre><code>X:\\full\\file\\name.txt(10) : message\n</code></pre>\n\n<p>to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the \'message\' in status bar. It\'s <em>very</em> useful.</p>\n'}, {'answer_id': 57573500, 'author': 'ejectamenta', 'author_id': 1740850, 'author_profile': 'https://Stackoverflow.com/users/1740850', 'pm_score': 0, 'selected': False, 'text': '<p>Write to a std::ostringsteam and then TRACE that.</p>\n\n<pre><code>std::ostringstream oss;\n\noss << "w:=" << w << " u=" << u << " vt=" << vt << endl;\n\nTRACE(oss.str().data());\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1265473/'] |
73,288 | <p>Looking for a way to read the unique ID / serial# of a USB thumb drive;
please note that<br>
- I am looking for the value of the manufacturer, not the one Windows allocates for it.<br>
- I need to support multiple OS (Windows, Unix, Mac), thus needs to be a Java solution</p>
<p>The idea is to be able to distinguish between different USB thumb drives.</p>
| [{'answer_id': 73548, 'author': 'tim_yates', 'author_id': 6509, 'author_profile': 'https://Stackoverflow.com/users/6509', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve never tried using it (it\'s been on my todo list for a good few months now), but there is the "marge" project on java.net:</p>\n\n<p><a href="http://marge.java.net/" rel="nofollow noreferrer">http://marge.java.net/</a></p>\n\n<p>This should let you connect to bluetooth devices (although I don\'t think it is 100% feature complete, there is demo code on there), and then the ClientDevice class has a "getBluetoothAddress" method which I <em>believe</em> should be unique to that device</p>\n\n<p><a href="http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html" rel="nofollow noreferrer">http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html</a></p>\n\n<p>As I say though, I\'ve never tried it...</p>\n'}, {'answer_id': 73888, 'author': 'Aidos', 'author_id': 12040, 'author_profile': 'https://Stackoverflow.com/users/12040', 'pm_score': 1, 'selected': False, 'text': '<p>I have never investigated this thoroughly, but from memory the <a href="http://users.frii.com/jarvi/rxtx/" rel="nofollow noreferrer">RXTX</a> library implementation of the javax.comm packages are supposedly very good and now have USB support.</p>\n'}, {'answer_id': 74045, 'author': 'Rangachari Anand', 'author_id': 7222, 'author_profile': 'https://Stackoverflow.com/users/7222', 'pm_score': 2, 'selected': False, 'text': '<p>RXTX is the way to go. In the world of model trains, JMRI (Java Model Railroad Interface) has become very popular. JMRI runs on all platforms (Windows, Linux and Mac) and communicates with a variety of USB based devices (command stations). RXTX is in fact used by JMRI.</p>\n'}, {'answer_id': 166282, 'author': 'jassuncao', 'author_id': 1009, 'author_profile': 'https://Stackoverflow.com/users/1009', 'pm_score': 2, 'selected': False, 'text': '<p>You might give a look at the following projects:\n<a href="http://javax-usb.org/" rel="nofollow noreferrer">javax-usb</a> and <a href="http://jusb.sourceforge.net/" rel="nofollow noreferrer">jusb</a>. They seem to support Linux and Windows. </p>\n\n<p>Anyway, since USB access in Java requires the use of native libraries, you might not achieve the required portability.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
73,305 | <p>When creating a setup/MSI with Visual Studio is it possible to make a setup for a simple application that doesn't require administrator permissions to install? If its not possible under Windows XP is it possible under Vista?</p>
<p>For example a simple image manipulation application that allows you to paste photos on top of backgrounds. I believe installing to the Program Files folder requires administrator permissions? Can we install in the \AppData folder instead?</p>
<p>The objective is to create an application which will install for users who are not members of the administrators group on the local machine and will not show the UAC prompt on Vista.</p>
<p>I believe a limitation this method would be that if it installs under the app data folder for the current user other users couldn't run it.</p>
<h3>Update:</h3>
<p>Can you package a click once install in a normal setup.exe type installer? You may ask why we want this - the reason is we have an installer that does a prereq check and installs anything required (such as .NET) and we then downloads and executes the MSI. We would like to display a normal installer start screen too even if that's the only thing displayed. We don't mind if the app can only be seen by one user (the user it's installed for).</p>
| [{'answer_id': 73342, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': "<p>Vista is <em>more</em> restrictive about this kind of thing, so if you can't do it for XP you can bet Vista won't let you either.</p>\n\n<p>You are right that installing to the program files folder using windows installer requires administrative permissions. In fact, <em>all write access</em> to that folder requires admin permsissions, which is why you should no longer store your data in the same folder as your executable.</p>\n\n<p>Fortunately, if you're using .Net you can use ClickOnce deployment instead of an msi, which should allow you to install to a folder in each user's profile without requiring admin permissions.</p>\n"}, {'answer_id': 73361, 'author': 'MrHinsh - Martin Hinshelwood', 'author_id': 11799, 'author_profile': 'https://Stackoverflow.com/users/11799', 'pm_score': 0, 'selected': False, 'text': '<p>The only way that I know of to do this is to build a ClickOnce application in .NET 2.0+</p>\n\n<p>If the user of your application has the correct pre-requsits installed then the application can just be "launched".</p>\n\n<p>Check out: </p>\n\n<ul>\n<li><a href="http://www.vertigo.com/familyshow.aspx" rel="nofollow noreferrer">Microsoft Family.Show</a></li>\n</ul>\n'}, {'answer_id': 73393, 'author': 'junkforce', 'author_id': 2153, 'author_profile': 'https://Stackoverflow.com/users/2153', 'pm_score': 0, 'selected': False, 'text': "<p>IF UAC is enabled, you couldn't write to Program Files. Installing to \\AppData will indeed only install the program for one user.</p>\n\n<p>However, you must note that any configuration changes that require changes to the registry probably(I'd have to double check on that) administrator privilege. Off the top of my head modifications to the desktop background are ultimately stored in HKEY_CURRENT_USER.</p>\n"}, {'answer_id': 73410, 'author': 'gregmac', 'author_id': 7913, 'author_profile': 'https://Stackoverflow.com/users/7913', 'pm_score': 3, 'selected': True, 'text': '<p>ClickOnce is a good solution to this problem. If you go to Project Properties > Publish, you can setup settings for this. In particular, "Install Mode and Settings" is good to look at: </p>\n\n<ul>\n<li>The application is available online only -- this is effectively a "run once" application</li>\n<li>The application is avaiable offline as well (launchable from Start Menu) -- this installs the app on the PC</li>\n</ul>\n\n<p>You don\'t actually have to use the ClickOnce web deployment stuff. If you do a Build > Publish, and then zip up the contents of the publish\\ folder, you can effectively distribute that as an installer. To make it even smoother, create a self-extracting archive from the folder that automatically runs the setup.exe file. </p>\n\n<p>Even if you install this way, if you opt to use it, the online update will still work for the application. All you have to do is put the ClickOnce files online, and put the URL in the project\'s Publish properties page.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3004/'] |
73,308 | <p>I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request? </p>
<p>FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler. </p>
<p>Currently, the code looks like so:</p>
<pre><code>my $ua = LWP::UserAgent->new;
ua->timeout(5); $ua->cookie_jar({});
my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login");
$req->content_type('application/x-www-form-urlencoded');
$req->content("login[user]=$username&login[password]=$password");
# This line never returns
$res = $ua->request($req);
</code></pre>
<p>I've tried using signals to trigger a timeout, but that does not seem to work. </p>
<pre><code>eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(1);
$res = $ua->request($req);
alarm(0);
};
# This never runs
print "here\n";
</code></pre>
<p>The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:</p>
<pre><code># Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
use Sys::SigAction qw( timeout_call );
our $res = undef;
if( timeout_call( 5, sub {$res = $ua->request($req);}) ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
sub ua_request_with_timeout2 {
print "ua_request_with_timeout\n";
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
my $timeout_for_client = $ua->timeout() - 2;
our $socket_has_timedout = 0;
use POSIX;
sigaction SIGALRM, new POSIX::SigAction(
sub {
$socket_has_timedout = 1;
die "alarm timeout";
}
) or die "Error setting SIGALRM handler: $!\n";
my $res = undef;
eval {
alarm ($timeout_for_client);
$res = $ua->request($req);
alarm(0);
};
if ( $socket_has_timedout ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
</code></pre>
| [{'answer_id': 73351, 'author': 'Alex Fort', 'author_id': 12624, 'author_profile': 'https://Stackoverflow.com/users/12624', 'pm_score': 0, 'selected': False, 'text': "<p>From what I understand, the timeout property doesn't take into account DNS timeouts. It's possible that you could make a DNS lookup separately, then make the request to the server if that works, with the correct timeout value set for the useragent.</p>\n\n<p>Is this a DNS problem with the server, or something else?</p>\n\n<p>EDIT: It could also be a problem with IO::Socket. Try updating your IO::Socket module, and see if that helps. I'm pretty sure there was a bug in there that was preventing LWP::UserAgent timeouts from working.</p>\n\n<p>Alex</p>\n"}, {'answer_id': 73374, 'author': 'Stephen Deken', 'author_id': 7154, 'author_profile': 'https://Stackoverflow.com/users/7154', 'pm_score': 5, 'selected': True, 'text': '<p>You might try <a href="http://search.cpan.org/%7Ebradfitz/LWPx-ParanoidAgent-1.02/lib/LWPx/ParanoidAgent.pm" rel="noreferrer">LWPx::ParanoidAgent</a>, a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers.</p>\n<p>Among other things, it allows you to specify a global timeout. It was developed by Brad Fitzpatrick as part of the LiveJournal project.</p>\n'}, {'answer_id': 76379, 'author': 'jkramer', 'author_id': 12523, 'author_profile': 'https://Stackoverflow.com/users/12523', 'pm_score': 1, 'selected': False, 'text': '<p>You can make your own timeout like this:</p>\n\n<pre><code>use LWP::UserAgent;\nuse IO::Pipe;\n\nmy $agent = new LWP::UserAgent;\n\nmy $finished = 0;\nmy $timeout = 5;\n\n$SIG{CHLD} = sub { wait, $finished = 1 };\n\nmy $pipe = new IO::Pipe;\nmy $pid = fork;\n\nif($pid == 0) {\n $pipe->writer;\n my $response = $agent->get("http://stackoverflow.com/");\n $pipe->print($response->content);\n exit;\n}\n\n$pipe->reader;\n\nsleep($timeout);\n\nif($finished) {\n print "Finished!\\n";\n my $content = join(\'\', $pipe->getlines);\n} \nelse {\n kill(9, $pid);\n print "Timed out.\\n";\n} \n</code></pre>\n'}, {'answer_id': 18542076, 'author': 'Andrei Georgescu', 'author_id': 2734397, 'author_profile': 'https://Stackoverflow.com/users/2734397', 'pm_score': 0, 'selected': False, 'text': '<p>The following generalization of one of the original answers also restores the alarm signal handler to the previous handler and adds a second call to alarm(0) in case the call in the eval clock throws a non alarm exception and we want to cancel the alarm. Further $@ inspection and handling can be added:</p>\n\n<pre><code>sub ua_request_with_timeout {\n my $ua = $_[0];\n my $request = $_[1];\n\n # Get whatever timeout is set for LWP and use that to \n # enforce a maximum timeout per request in case of server\n # deadlock. (This has happened.)`enter code here`\n my $timeout_for_client_sec = $ua->timeout();\n our $res_has_timedout = 0; \n\n use POSIX \':signal_h\';\n\n my $newaction = POSIX::SigAction->new(\n sub { $res_has_timedout = 1; die "web request timeout"; },# the handler code ref\n POSIX::SigSet->new(SIGALRM),\n # not using (perl 5.8.2 and later) \'safe\' switch or sa_flags\n ); \n\n my $oldaction = POSIX::SigAction->new();\n if(!sigaction(SIGALRM, $newaction, $oldaction)) {\n log(\'warn\',"Error setting SIGALRM handler: $!");\n return $ua->request($request);\n } \n\n my $response = undef;\n eval {\n alarm ($timeout_for_client_sec);\n $response = $ua->request($request);\n alarm(0);\n }; \n\n alarm(0);# cancel alarm (if eval failed because of non alarm cause)\n if(!sigaction(SIGALRM, $oldaction )) {\n log(\'warn\', "Error resetting SIGALRM handler: $!");\n }; \n\n if ( $res_has_timedout ) {\n log(\'warn\', "Timeout($timeout_for_client_sec sec) while waiting for a response from cred central");\n return HTTP::Response->new(408); #408 is the HTTP timeout\n } else {\n return $response;\n }\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12628/'] |
73,312 | <p>In our embedded system (using a PowerPC processor), we want to disable the processor cache. What steps do we need to take?</p>
<p>To clarify a bit, the application in question must have as constant a speed of execution as we can make it.
Variability in executing the same code path is not acceptable. This is the reason to turn off the cache.</p>
| [{'answer_id': 73316, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 2, 'selected': False, 'text': '<p>From the E600 reference manual:<br>\nThe HID0 special-purpose register contains several bits that invalidate, disable, and lock the instruction and data caches.</p>\n\n<p>You should use HID0[DCE] = 0 to disable the data cache.<br>\nYou should use HID0[ICE] = 0 to disable the instruction cache.</p>\n\n<p>Note that at power up, both caches are disabled.\nYou will need to write this in assembly code.</p>\n'}, {'answer_id': 164483, 'author': 'KeyserSoze', 'author_id': 14116, 'author_profile': 'https://Stackoverflow.com/users/14116', 'pm_score': 1, 'selected': False, 'text': "<p>Perhaps you don't want to globally disable cache, you only want to disable it for a particular address range?</p>\n\n<p>On some processors you can configure TLB (translation lookaside buffer) entries for address ranges such that each range could have caching enabled or disabled. This way you can disable caching for memory mapped I/O, and still leave caching on for the main block of RAM.</p>\n\n<p>The only PowerPC I've done this on was a PowerPC 440EP (from IBM, then AMCC), so I don't know if all PowerPCs work the same way.</p>\n"}, {'answer_id': 164525, 'author': 'jakobengblom2', 'author_id': 23054, 'author_profile': 'https://Stackoverflow.com/users/23054', 'pm_score': 1, 'selected': False, 'text': '<p>What kind of PPC core is it? The cache control is very different between different cores from different vendors... also, disabling the cache is in general considered a really bad thing to do to the machine. Performance becomes so crawlingly slow that you would do as well with an old 8-bit processor (exaggerating a bit). Some ARM variants have TCMs, tightly-coupled memories, that work instead of caches, but I am not aware of any PPC variant with that facility. </p>\n\n<p>Maybe a better solution is to keep Level 1 caches active, and use the on-chip L2 caches as statically mapped RAM instead? That is common on modern PowerQUICC devices, at least. </p>\n'}, {'answer_id': 258673, 'author': 'Dan', 'author_id': 28574, 'author_profile': 'https://Stackoverflow.com/users/28574', 'pm_score': 3, 'selected': True, 'text': "<p>I'm kind of late to the question, and also it's been a while since I did all the low-level processor init code on PPCs, but I seem to remember the cache & MMU being pretty tightly coupled (one had to be enabled to enable the other) and I <em>think</em> in the MMU page tables, you could define the cacheable attribute.</p>\n\n<p>So my point is this: if there's a certain subset of code that must run in deterministic time, maybe you locate that code (via a linker command file) in a region of memory that is defined as non-cacheable in the page tables? That way all the code that can/should benefit from the cache does, and the (hopefully) subset of code that shouldn't, doesn't.</p>\n\n<p>I'd handle it this way anyway, so that later, if you want to enable caching for part of the system, you just need to flip a few bits in the MMU page tables, instead of (re-)writing the init code to set up all the page tables & caching.</p>\n"}, {'answer_id': 1485180, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Turning off the cache will do you no good at all. Your execution speed will drop by an order of magnitude. You would never ship a system like this, so its performance under these conditions is of no interest.</p>\n\n<p>To achieve a steady execution speed, consider one of these approaches:</p>\n\n<p>1) Lock some or all of the cache. All current PowerPC chips from Freescale, IBM, and AMCC offer this feature.</p>\n\n<p>2) If it's a Freescale chip with L2 cache, consider mapping part of that cache as on-chip memory.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/73312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10703/'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.