qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
51,032
<p>Consider these two function definitions:</p> <pre><code>void foo() { } void foo(void) { } </code></pre> <p>Is there any difference between these two? If not, why is the <code>void</code> argument there? Aesthetic reasons?</p>
[ { "answer_id": 51041, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>In C, you use a void in an empty function reference so that the compiler has a prototype, and that prototype has \"no arguments\". In C++, you don't have to tell the compiler that you have a prototype because you can't leave out the prototype.</p>\n" }, { "answer_id": 51044, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": false, "text": "<p>I realize your question pertains to C++, but when it comes to C the answer can be found in <a href=\"https://en.wikipedia.org/wiki/The_C_Programming_Language\" rel=\"nofollow noreferrer\">K&amp;R</a>, pages 72-73:</p>\n<blockquote>\n<p>Furthermore, if a function declaration does not include arguments, as\nin</p>\n<pre><code>double atof();\n</code></pre>\n<p>that too is taken to mean that nothing is to be assumed about the\narguments of atof; all parameter checking is turned off. This special\nmeaning of the empty argument list is intended to permit older C\nprograms to compile with new compilers. But it's a bad idea to use it\nwith new programs. If the function takes arguments, declare them; if\nit takes no arguments, use void.</p>\n</blockquote>\n" }, { "answer_id": 51080, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 9, "selected": true, "text": "<p>In <strong>C</strong>: </p>\n\n<ul>\n<li><code>void foo()</code> means \"a function <code>foo</code> taking an unspecified number of arguments of unspecified type\" </li>\n<li><code>void foo(void)</code> means \"a function <code>foo</code> taking no arguments\"</li>\n</ul>\n\n<p>In <strong>C++</strong>: </p>\n\n<ul>\n<li><code>void foo()</code> means \"a function <code>foo</code> taking no arguments\" </li>\n<li><code>void foo(void)</code> means \"a function <code>foo</code> taking no arguments\"</li>\n</ul>\n\n<p>By writing <code>foo(void)</code>, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an <code>extern \"C\"</code> if we're compiling C++).</p>\n" }, { "answer_id": 36835303, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "<p><strong>C++11 N3337 standard draft</strong></p>\n<p>There is no difference.</p>\n<p><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf</a></p>\n<p><em>Annex C &quot;Compatibility&quot; C.1.7 Clause 8: declarators</em> says:</p>\n<blockquote>\n<p>8.3.5 Change: In C ++ , a function declared with an empty parameter list takes no arguments. In C, an empty\nparameter list means that the number and type of the function arguments are unknown.</p>\n<p>Example:</p>\n<pre class=\"lang-c prettyprint-override\"><code>int f();\n// means int f(void) in C ++\n// int f( unknown ) in C\n</code></pre>\n<p>Rationale: This is to avoid erroneous function calls (i.e., function calls with the wrong number or type of\narguments).</p>\n<p>Effect on original feature: Change to semantics of well-defined feature. This feature was marked as “obsolescent” in C.</p>\n</blockquote>\n<p><em>8.5.3 functions</em> says:</p>\n<blockquote>\n<p>4. The parameter-declaration-clause determines the arguments that can be specified, and their processing, when\nthe function is called. [...] If the parameter-declaration-clause is empty, the function\ntakes no arguments. The parameter list (void) is equivalent to the empty parameter list.</p>\n</blockquote>\n<p><strong>C99</strong></p>\n<p>As mentioned by C++11, <code>int f()</code> specifies nothing about the arguments, and is obsolescent.</p>\n<p>It can either lead to working code or UB.</p>\n<p>I have interpreted the C99 standard in detail at: <a href=\"https://stackoverflow.com/a/36292431/895245\">https://stackoverflow.com/a/36292431/895245</a></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
Consider these two function definitions: ``` void foo() { } void foo(void) { } ``` Is there any difference between these two? If not, why is the `void` argument there? Aesthetic reasons?
In **C**: * `void foo()` means "a function `foo` taking an unspecified number of arguments of unspecified type" * `void foo(void)` means "a function `foo` taking no arguments" In **C++**: * `void foo()` means "a function `foo` taking no arguments" * `void foo(void)` means "a function `foo` taking no arguments" By writing `foo(void)`, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an `extern "C"` if we're compiling C++).
51,054
<p>I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.</p> <p>Similar things can be <a href="https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash">done in BASH</a> in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.</p>
[ { "answer_id": 51069, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 11, "selected": true, "text": "<p>Enjoy:</p>\n\n<pre><code>forfiles -p \"C:\\what\\ever\" -s -m *.* -d &lt;number of days&gt; -c \"cmd /c del @path\"\n</code></pre>\n\n<p>See <a href=\"http://ss64.com/nt/forfiles.html\" rel=\"noreferrer\"><code>forfiles</code> documentation</a> for more details.</p>\n\n<p>For more goodies, refer to <em><a href=\"http://www.ss64.com/nt/\" rel=\"noreferrer\">An A-Z Index of the Windows&nbsp;XP command line</a></em>.</p>\n\n<p>If you don't have <code>forfiles</code> installed on your machine, copy it from any <a href=\"http://en.wikipedia.org/wiki/Windows_Server_2003\" rel=\"noreferrer\">Windows&nbsp;Server&nbsp;2003</a> to your Windows&nbsp;XP machine at <code>%WinDir%\\system32\\</code>. This is possible since the EXE is fully compatible between Windows&nbsp;Server&nbsp;2003 and Windows&nbsp;XP.</p>\n\n<p>Later versions of Windows and Windows&nbsp;Server have it installed by default.</p>\n\n<p>For Windows&nbsp;7 and newer (including Windows&nbsp;10):</p>\n\n<p>The syntax has changed a little. Therefore the updated command is:</p>\n\n<pre><code>forfiles /p \"C:\\what\\ever\" /s /m *.* /D -&lt;number of days&gt; /C \"cmd /c del @path\"\n</code></pre>\n" }, { "answer_id": 52003, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 2, "selected": false, "text": "<p>You might be able to pull this off. You can take a look at <a href=\"https://stackoverflow.com/questions/51837/open-one-of-a-series-of-files-using-a-batch-file\">this question</a>, for a simpler example. The complexity comes, when you start comparing the dates. It may be easy to tell if the date is greater or not, but there are many situations to consider if you need to actually get the difference between two dates.</p>\n\n<p>In other words - don't try to invent this, unless you really can't use the third party tools.</p>\n" }, { "answer_id": 1322886, "author": "Jay", "author_id": 151152, "author_profile": "https://Stackoverflow.com/users/151152", "pm_score": 5, "selected": false, "text": "<p>Ok was bored a bit and came up with this, which contains my version of a poor man's Linux epoch replacement limited for daily usage (no time retention):</p>\n\n<p>7daysclean.cmd</p>\n\n<pre><code>@echo off\nsetlocal ENABLEDELAYEDEXPANSION\nset day=86400\nset /a year=day*365\nset /a strip=day*7\nset dSource=C:\\temp\n\ncall :epoch %date%\nset /a slice=epoch-strip\n\nfor /f \"delims=\" %%f in ('dir /a-d-h-s /b /s %dSource%') do (\n call :epoch %%~tf\n if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)\n)\nexit /b 0\n\nrem Args[1]: Year-Month-Day\n:epoch\n setlocal ENABLEDELAYEDEXPANSION\n for /f \"tokens=1,2,3 delims=-\" %%d in ('echo %1') do set Years=%%d&amp; set Months=%%e&amp; set Days=%%f\n if \"!Months:~0,1!\"==\"0\" set Months=!Months:~1,1!\n if \"!Days:~0,1!\"==\"0\" set Days=!Days:~1,1!\n set /a Days=Days*day\n set /a _months=0\n set i=1&amp;&amp; for %%m in (31 28 31 30 31 30 31 31 30 31 30 31) do if !i! LSS !Months! (set /a _months=!_months! + %%m*day&amp;&amp; set /a i+=1)\n set /a Months=!_months!\n set /a Years=(Years-1970)*year\n set /a Epoch=Years+Months+Days\n endlocal&amp; set Epoch=%Epoch%\n exit /b 0\n</code></pre>\n\n<h2>USAGE</h2>\n\n<p><code>set /a strip=day*7</code> : Change <strong>7</strong> for the number of days to keep.</p>\n\n<p><code>set dSource=C:\\temp</code> : This is the starting directory to check for files.</p>\n\n<h2>NOTES</h2>\n\n<p>This is non-destructive code, it will display what would have happened.</p>\n\n<p>Change :</p>\n\n<pre><code>if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)\n</code></pre>\n\n<p>to something like :</p>\n\n<pre><code>if !epoch! LEQ %slice% del /f %%f\n</code></pre>\n\n<p>so files actually get deleted</p>\n\n<p><strong>February</strong>: is hard-coded to 28 days. Bissextile years is a hell to add, really. if someone has an idea that would not add 10 lines of code, go ahead and post so I add it to my code.</p>\n\n<p><strong>epoch</strong>: I did not take time into consideration, as the need is to delete files older than a certain date, taking hours/minutes would have deleted files from a day that was meant for keeping.</p>\n\n<h2>LIMITATION</h2>\n\n<p><strong>epoch</strong> takes for granted your short date format is YYYY-MM-DD. It would need to be adapted for other settings or a run-time evaluation (read sShortTime, user-bound configuration, configure proper field order in a filter and use the filter to extract the correct data from the argument).</p>\n\n<p>Did I mention I hate this editor's auto-formating? it removes the blank lines and the copy-paste is a hell.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 1322976, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 4, "selected": false, "text": "<p>Have a look at my <a href=\"https://stackoverflow.com/questions/324267/batch-file-to-delete-files-older-than-a-specified-date/324349#324349\">answer</a> to a <a href=\"https://stackoverflow.com/questions/324267/batch-file-to-delete-files-older-than-a-specified-date\">similar question</a>:</p>\n\n<pre><code>REM del_old.bat\nREM usage: del_old MM-DD-YYY\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa &gt;&gt; FILES_TO_KEEP.TXT\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist \"%%~nxa\" del \"%%~nxa\"\n</code></pre>\n\n<p>This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.</p>\n\n<p><strong>update:</strong> I notice that HerbCSO has improved on the above script. I recommend using <a href=\"https://stackoverflow.com/questions/324267/batch-file-to-delete-files-older-than-a-specified-date/1180746#1180746\">his version</a> instead.</p>\n" }, { "answer_id": 3161104, "author": "J.R.", "author_id": 381472, "author_profile": "https://Stackoverflow.com/users/381472", "pm_score": 3, "selected": false, "text": "<p>How about this modification on <a href=\"https://stackoverflow.com/a/1322886/3074564\">7daysclean.cmd</a> to take a leap year into account?</p>\n\n<p>It can be done in less than 10 lines of coding!</p>\n\n<pre><code>set /a Leap=0\nif (Month GEQ 2 and ((Years%4 EQL 0 and Years%100 NEQ 0) or Years%400 EQL 0)) set /a Leap=day\nset /a Months=!_months!+Leap\n</code></pre>\n\n<hr>\n\n<p><strong>Edit by Mofi:</strong></p>\n\n<p>The condition above contributed by <a href=\"https://stackoverflow.com/users/381472/j-r\">J.R.</a> evaluates always to <strong>false</strong> because of invalid syntax.</p>\n\n<p>And <code>Month GEQ 2</code> is also wrong because adding 86400 seconds for one more day must be done in a leap year only for the months March to December, but not for February.</p>\n\n<p>A working code to take leap day into account - in current year only - in batch file <strong>7daysclean.cmd</strong> posted by <a href=\"https://stackoverflow.com/users/151152/jay\">Jay</a> would be:</p>\n\n<pre><code>set \"LeapDaySecs=0\"\nif %Month% LEQ 2 goto CalcMonths\nset /a \"LeapRule=Years%%4\"\nif %LeapRule% NEQ 0 goto CalcMonths\nrem The other 2 rules can be ignored up to year 2100.\nset /A \"LeapDaySecs=day\"\n:CalcMonths\nset /a Months=!_months!+LeapDaySecs\n</code></pre>\n" }, { "answer_id": 4383245, "author": "neuracnu", "author_id": 19277, "author_profile": "https://Stackoverflow.com/users/19277", "pm_score": 2, "selected": false, "text": "<p>If you have the XP resource kit, you can use robocopy to move all the old directories into a single directory, then use rmdir to delete just that one:</p>\n\n<pre><code>mkdir c:\\temp\\OldDirectoriesGoHere\nrobocopy c:\\logs\\SoManyDirectoriesToDelete\\ c:\\temp\\OldDirectoriesGoHere\\ /move /minage:7\nrmdir /s /q c:\\temp\\OldDirectoriesGoHere\n</code></pre>\n" }, { "answer_id": 4436614, "author": "segero", "author_id": 551504, "author_profile": "https://Stackoverflow.com/users/551504", "pm_score": 4, "selected": false, "text": "<p>My command is</p>\n\n<pre><code>forfiles -p \"d:\\logs\" -s -m*.log -d-15 -c\"cmd /c del @PATH\\@FILE\" \n</code></pre>\n\n<p><code>@PATH</code> - is just path in my case, so I had to use <code>@PATH\\@FILE</code></p>\n\n<p>also <code>forfiles /?</code> not working for me too, but <code>forfiles</code> (without \"?\") worked fine.</p>\n\n<p>And the only question I have: how to add multiple mask (for example \"<em>.log|</em>.bak\")?</p>\n\n<p>All this regarding forfiles.exe that I <a href=\"ftp://ftp.microsoft.com/ResKit/y2kfix/x86/\" rel=\"noreferrer\">downloaded here</a> (on win XP)</p>\n\n<p>But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command. </p>\n\n<p>For Windows Server 2003 I'm using this command:</p>\n\n<pre><code>forfiles -p \"d:\\Backup\" -s -m *.log -d -15 -c \"cmd /c del @PATH\"\n</code></pre>\n" }, { "answer_id": 4800680, "author": "Paris", "author_id": 589995, "author_profile": "https://Stackoverflow.com/users/589995", "pm_score": 3, "selected": false, "text": "<p>Copy this code and save it as <code>DelOldFiles.vbs</code>.</p>\n\n<p>USAGE IN CMD : <code>cscript //nologo DelOldFiles.vbs 15</code></p>\n\n<p>15 means to delete files older than 15 days in past.</p>\n\n<pre><code> 'copy from here\n Function DeleteOlderFiles(whichfolder)\n Dim fso, f, f1, fc, n, ThresholdDate\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n Set f = fso.GetFolder(whichfolder)\n Set fc = f.Files\n Set objArgs = WScript.Arguments\n n = 0\n If objArgs.Count=0 Then\n howmuchdaysinpast = 0\n Else\n howmuchdaysinpast = -objArgs(0)\n End If\n ThresholdDate = DateAdd(\"d\", howmuchdaysinpast, Date) \n For Each f1 in fc\n If f1.DateLastModified&lt;ThresholdDate Then\n Wscript.StdOut.WriteLine f1\n f1.Delete\n n = n + 1 \n End If\n Next\n Wscript.StdOut.WriteLine \"Deleted \" &amp; n &amp; \" file(s).\"\n End Function\n\n If Not WScript.FullName = WScript.Path &amp; \"\\cscript.exe\" Then\n WScript.Echo \"USAGE ONLY IN COMMAND PROMPT: cscript DelOldFiles.vbs 15\" &amp; vbCrLf &amp; \"15 means to delete files older than 15 days in past.\"\n WScript.Quit 0 \n End If\n\n DeleteOlderFiles(\".\")\n 'to here\n</code></pre>\n" }, { "answer_id": 6149776, "author": "Iman", "author_id": 772718, "author_profile": "https://Stackoverflow.com/users/772718", "pm_score": 6, "selected": false, "text": "<p>Run the following <a href=\"https://technet.microsoft.com/en-us/library/cc733145.aspx\" rel=\"noreferrer\">commands</a>:</p>\n\n<pre><code>ROBOCOPY C:\\source C:\\destination /mov /minage:7\ndel C:\\destination /q\n</code></pre>\n\n<p>Move all the files (using /mov, which moves files and then deletes them as opposed to /move which moves whole filetrees which are then deleted) via robocopy to another location, and then execute a delete command on that path and you're all good. </p>\n\n<p>Also if you have a directory with lots of data in it you can use <code>/mir</code> switch </p>\n" }, { "answer_id": 6275689, "author": "Arno Jansen", "author_id": 788773, "author_profile": "https://Stackoverflow.com/users/788773", "pm_score": 5, "selected": false, "text": "<pre><code>forfiles /p \"v:\" /s /m *.* /d -3 /c \"cmd /c del @path\"\n</code></pre>\n\n<p>You should do <code>/d -3</code> (3 days earlier) This works fine for me. So all the complicated batches could be in the trash bin. Also <code>forfiles</code> don't support UNC paths, so make a network connection to a specific drive.</p>\n" }, { "answer_id": 8123408, "author": "Aidan Ewen", "author_id": 795896, "author_profile": "https://Stackoverflow.com/users/795896", "pm_score": 3, "selected": false, "text": "<p>Use forfiles. </p>\n\n<p>There are different versions. Early ones use unix style parameters. </p>\n\n<p>My version (for server 2000 - note no space after switches)- </p>\n\n<pre><code>forfiles -p\"C:\\what\\ever\" -s -m*.* -d&lt;number of days&gt; -c\"cmd /c del @path\"\n</code></pre>\n\n<p>To add forfiles to XP, get the exe from <a href=\"ftp://ftp.microsoft.com/ResKit/y2kfix/x86/\" rel=\"noreferrer\">ftp://ftp.microsoft.com/ResKit/y2kfix/x86/</a></p>\n\n<p>and add it to C:\\WINDOWS\\system32</p>\n" }, { "answer_id": 10358807, "author": "NotJustClarkKent", "author_id": 334695, "author_profile": "https://Stackoverflow.com/users/334695", "pm_score": 3, "selected": false, "text": "<p>For Windows Server 2008 R2:</p>\n\n<pre><code>forfiles /P c:\\sql_backups\\ /S /M *.sql /D -90 /C \"cmd /c del @PATH\"\n</code></pre>\n\n<p>This will delete all <em>.sql</em> files older than <em>90</em> days.</p>\n" }, { "answer_id": 16234804, "author": "Graham Laight", "author_id": 1649135, "author_profile": "https://Stackoverflow.com/users/1649135", "pm_score": 3, "selected": false, "text": "<p>IMO, JavaScript is gradually becoming a universal scripting standard: it is probably available in more products than any other scripting language (in Windows, it is available using the Windows Scripting Host). I have to clean out old files in lots of folders, so here is a JavaScript function to do that:</p>\n\n<pre><code>// run from an administrator command prompt (or from task scheduler with full rights): wscript jscript.js\n// debug with: wscript /d /x jscript.js\n\nvar fs = WScript.CreateObject(\"Scripting.FileSystemObject\");\n\nclearFolder('C:\\\\temp\\\\cleanup');\n\nfunction clearFolder(folderPath)\n{\n // calculate date 3 days ago\n var dateNow = new Date();\n var dateTest = new Date();\n dateTest.setDate(dateNow.getDate() - 3);\n\n var folder = fs.GetFolder(folderPath);\n var files = folder.Files;\n\n for( var it = new Enumerator(files); !it.atEnd(); it.moveNext() )\n {\n var file = it.item();\n\n if( file.DateLastModified &lt; dateTest)\n {\n var filename = file.name;\n var ext = filename.split('.').pop().toLowerCase();\n\n if (ext != 'exe' &amp;&amp; ext != 'dll')\n {\n file.Delete(true);\n }\n }\n }\n\n var subfolders = new Enumerator(folder.SubFolders);\n for (; !subfolders.atEnd(); subfolders.moveNext())\n {\n clearFolder(subfolders.item().Path);\n }\n}\n</code></pre>\n\n<p>For each folder to clear, just add another call to the clearFolder() function. This particular code also preserves exe and dll files, and cleans up subfolders as well.</p>\n" }, { "answer_id": 20671056, "author": "Goran B.", "author_id": 2175524, "author_profile": "https://Stackoverflow.com/users/2175524", "pm_score": 2, "selected": false, "text": "<p>this is nothing amazing, but i needed to do something like this today and run it as scheduled task etc.</p>\n\n<p>batch file, DelFilesOlderThanNDays.bat below with sample exec w/ params:</p>\n\n<blockquote>\n <p>DelFilesOlderThanNDays.bat <strong>7</strong> <em>C:\\dir1\\dir2\\dir3\\logs</em> <strong>*.log</strong></p>\n</blockquote>\n\n<pre><code>echo off\ncls\nEcho(\nSET keepDD=%1\nSET logPath=%2 :: example C:\\dir1\\dir2\\dir3\\logs\nSET logFileExt=%3\nSET check=0\nIF [%3] EQU [] SET logFileExt=*.log &amp; echo: file extention not specified (default set to \"*.log\")\nIF [%2] EQU [] echo: file directory no specified (a required parameter), exiting! &amp; EXIT /B \nIF [%1] EQU [] echo: number of days not specified? :)\necho(\necho: in path [ %logPath% ]\necho: finding all files like [ %logFileExt% ]\necho: older than [ %keepDD% ] days\necho(\n::\n::\n:: LOG\necho: &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: executed on %DATE% %TIME% &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: in path [ %logPath% ] &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: finding all files like [ %logFileExt% ] &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: older than [ %keepDD% ] days &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\n::\nFORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c \"cmd /c echo @path\" &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt 2&lt;&amp;1\nIF %ERRORLEVEL% EQU 0 (\n FORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c \"cmd /c echo @path\"\n)\n::\n::\n:: LOG\nIF %ERRORLEVEL% EQU 0 (\n echo: &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\n echo: deleting files ... &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\n echo: &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\n SET check=1\n)\n::\n::\nIF %check% EQU 1 (\n FORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c \"cmd /c del @path\"\n)\n::\n:: RETURN &amp; LOG\n::\nIF %ERRORLEVEL% EQU 0 echo: deletion successfull! &amp; echo: deletion successfull! &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- &gt;&gt; c:\\trimLogFiles\\logBat\\log.txt\n</code></pre>\n" }, { "answer_id": 20893589, "author": "Lectrode", "author_id": 1284754, "author_profile": "https://Stackoverflow.com/users/1284754", "pm_score": 2, "selected": false, "text": "<p>I think <a href=\"https://stackoverflow.com/a/1322976/1284754\">e.James's answer</a> is good since it works with unmodified versions of Windows as early as Windows 2000 SP4 (and possibly earlier), but it required writing to an external file. Here is a modified version that does not create an external text file while maintaining the compatibility:</p>\n\n<pre><code>REM del_old.cmd\nREM usage: del_old MM-DD-YYYY\nsetlocal enabledelayedexpansion\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /d:%1 /L /I null') do @if exist \"%%~nxa\" set \"excludefiles=!excludefiles!;;%%~nxa;;\"\nfor /f \"tokens=*\" %%a IN ('dir /b') do @(@echo \"%excludefiles%\"|FINDSTR /C:\";;%%a;;\"&gt;nul || if exist \"%%~nxa\" DEL /F /Q \"%%a\"&gt;nul 2&gt;&amp;1)\n</code></pre>\n\n<p>To be true to the original question, here it is in a script that does ALL the math for you if you call it with the number of days as the parameter:</p>\n\n<pre><code>REM del_old_compute.cmd\nREM usage: del_old_compute N\nsetlocal enabledelayedexpansion\nset /a days=%1&amp;set cur_y=%DATE:~10,4%&amp;set cur_m=%DATE:~4,2%&amp;set cur_d=%DATE:~7,2%\nfor /f \"tokens=1 delims==\" %%a in ('set cur_') do if \"!%%a:~0,1!\"==\"0\" set /a %%a=!%%a:~1,1!+0\nset mo_2=28&amp;set /a leapyear=cur_y*10/4\nif %leapyear:~-1% equ 0 set mo_2=29\nset mo_1=31&amp;set mo_3=31&amp;set mo_4=30&amp;set mo_5=31\nset mo_6=30&amp;set mo_7=31&amp;set mo_8=31&amp;set mo_9=30\nset mo_10=31&amp;set mo_11=30&amp;set mo_12=31\nset /a past_y=(days/365)\nset /a monthdays=days-((past_y*365)+((past_y/4)*1))&amp;&amp;set /a past_y=cur_y-past_y&amp;set months=0\n:setmonth\nset /a minusmonth=(cur_m-1)-months\nif %minusmonth% leq 0 set /a minusmonth+=12\nset /a checkdays=(mo_%minusmonth%)\nif %monthdays% geq %checkdays% set /a months+=1&amp;set /a monthdays-=checkdays&amp;goto :setmonth\nset /a past_m=cur_m-months\nset /a lastmonth=cur_m-1\nif %lastmonth% leq 0 set /a lastmonth+=12\nset /a lastmonth=mo_%lastmonth%\nset /a past_d=cur_d-monthdays&amp;set adddays=::\nif %past_d% leq 0 (set /a past_m-=1&amp;set adddays=)\nif %past_m% leq 0 (set /a past_m+=12&amp;set /a past_y-=1)\nset mo_2=28&amp;set /a leapyear=past_y*10/4\nif %leapyear:~-1% equ 0 set mo_2=29\n%adddays%set /a past_d+=mo_%past_m%\nset d=%past_m%-%past_d%-%past_y%\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /d:%d% /L /I null') do @if exist \"%%~nxa\" set \"excludefiles=!excludefiles!;;%%~nxa;;\"\nfor /f \"tokens=*\" %%a IN ('dir /b') do @(@echo \"%excludefiles%\"|FINDSTR /C:\";;%%a;;\"&gt;nul || if exist \"%%~nxa\" DEL /F /Q \"%%a\"&gt;nul 2&gt;&amp;1)\n</code></pre>\n\n<p>NOTE: The code above takes into account leap years, as well as the exact number of days in each month. The only maximum is the total number of days there have been since 0/0/0 (after that it returns negative years).</p>\n\n<p>NOTE: The math only goes one way; it cannot correctly get future dates from negative input (it will try, but will likely go past the last day of the month).</p>\n" }, { "answer_id": 22401809, "author": "Tobias Järvelöv", "author_id": 1141914, "author_profile": "https://Stackoverflow.com/users/1141914", "pm_score": 2, "selected": false, "text": "<p>Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.</p>\n\n<pre><code>net use Z: /delete\nnet use Z: \\\\unc\\path\\to\\my\\folder\nforfiles /p Z: /s /m *.gz /D -7 /C \"cmd /c del @path\"\n</code></pre>\n\n<p>This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as</p>\n\n<pre><code>net use Z: \\\\unc\\path\\to\\my\\folder\nif %errorlevel% equ 0 (\n forfiles /p Z: /s /m *.gz /D -7 /C \"cmd /c del @path\"\n) else (\n echo \"Z: is already in use, please use another drive letter!\"\n)\n</code></pre>\n" }, { "answer_id": 28395552, "author": "Mofi", "author_id": 3074564, "author_profile": "https://Stackoverflow.com/users/3074564", "pm_score": 3, "selected": false, "text": "<p>There are very often relative date/time related questions to solve with batch file. But command line interpreter <strong>cmd.exe</strong> has no function for date/time calculations. Lots of good working solutions using additional console applications or scripts have been posted already here, on other pages of Stack Overflow and on other websites.</p>\n<p>Common for operations based on date/time is the requirement to convert a date/time string to seconds since a determined day. Very common is 1970-01-01 00:00:00 UTC. But any later day could be also used depending on the date range required to support for a specific task.</p>\n<p><a href=\"https://stackoverflow.com/users/151152/jay\">Jay</a> posted <a href=\"https://stackoverflow.com/a/1322886/3074564\">7daysclean.cmd</a> containing a fast &quot;date to seconds&quot; solution for command line interpreter <strong>cmd.exe</strong>. But it does not take leap years correct into account. <a href=\"https://stackoverflow.com/users/381472/j-r\">J.R.</a> posted an <a href=\"https://stackoverflow.com/a/3161104/3074564\">add-on</a> for taking leap day in current year into account, but ignoring the other leap years since base year, i.e. since 1970.</p>\n<p>I use since 20 years static tables (arrays) created once with a small C function for quickly getting the number of days including leap days from 1970-01-01 in date/time conversion functions in my applications written in C/C++.</p>\n<p>This very fast table method can be used also in batch code using <strong>FOR</strong> command. So I decided to code the batch subroutine <code>GetSeconds</code> which calculates the number of seconds since 1970-01-01 00:00:00 UTC for a date/time string passed to this routine.</p>\n<p><strong>Note:</strong> Leap seconds are not taken into account as the Windows file systems also do not support leap seconds.</p>\n<p>First, the tables:</p>\n<ol>\n<li><p>Days since 1970-01-01 00:00:00 UTC for each year including leap days.</p>\n<pre><code>1970 - 1979: 0 365 730 1096 1461 1826 2191 2557 2922 3287\n1980 - 1989: 3652 4018 4383 4748 5113 5479 5844 6209 6574 6940\n1990 - 1999: 7305 7670 8035 8401 8766 9131 9496 9862 10227 10592\n2000 - 2009: 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245\n2010 - 2019: 14610 14975 15340 15706 16071 16436 16801 17167 17532 17897\n2020 - 2029: 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550\n2030 - 2039: 21915 22280 22645 23011 23376 23741 24106 24472 24837 25202\n2040 - 2049: 25567 25933 26298 26663 27028 27394 27759 28124 28489 28855\n2050 - 2059: 29220 29585 29950 30316 30681 31046 31411 31777 32142 32507\n2060 - 2069: 32872 33238 33603 33968 34333 34699 35064 35429 35794 36160\n2070 - 2079: 36525 36890 37255 37621 37986 38351 38716 39082 39447 39812\n2080 - 2089: 40177 40543 40908 41273 41638 42004 42369 42734 43099 43465\n2090 - 2099: 43830 44195 44560 44926 45291 45656 46021 46387 46752 47117\n2100 - 2106: 47482 47847 48212 48577 48942 49308 49673\n</code></pre>\n<p>Calculating the seconds for year 2039 to 2106 with epoch beginning 1970-01-01 is only possible with using an unsigned 32-bit variable, i.e. unsigned long (or unsigned int) in C/C++.</p>\n<p>But <strong>cmd.exe</strong> use for mathematical expressions a signed 32-bit variable. Therefore the maximum value is 2147483647 (0x7FFFFFFF) which is 2038-01-19 03:14:07.</p>\n</li>\n<li><p>Leap year information (No/Yes) for the years 1970 to 2106.</p>\n<pre><code>1970 - 1989: N N Y N N N Y N N N Y N N N Y N N N Y N\n1990 - 2009: N N Y N N N Y N N N Y N N N Y N N N Y N\n2010 - 2029: N N Y N N N Y N N N Y N N N Y N N N Y N\n2030 - 2049: N N Y N N N Y N N N Y N N N Y N N N Y N\n2050 - 2069: N N Y N N N Y N N N Y N N N Y N N N Y N\n2070 - 2089: N N Y N N N Y N N N Y N N N Y N N N Y N\n2090 - 2106: N N Y N N N Y N N N N N N N Y N N\n ^ year 2100\n</code></pre>\n</li>\n<li><p>Number of days to first day of each month in current year.</p>\n<pre><code> Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\nYear with 365 days: 0 31 59 90 120 151 181 212 243 273 304 334\nYear with 366 days: 0 31 60 91 121 152 182 213 244 274 305 335\n</code></pre>\n</li>\n</ol>\n<p>Converting a date to number of seconds since 1970-01-01 is quite easy using those tables.</p>\n<p><strong>Attention please!</strong></p>\n<p>The format of date and time strings depends on Windows region and language settings. The delimiters and the order of tokens assigned to the environment variables <code>Day</code>, <code>Month</code> and <code>Year</code> in first <strong>FOR</strong> loop of <code>GetSeconds</code> must be adapted to local date/time format if necessary.</p>\n<p>It is necessary to adapt the date string of the environment variable if date format in environment variable <strong>DATE</strong> is different to date format used by command <strong>FOR</strong> on <code>%%~tF</code>.</p>\n<p>For example when <code>%DATE%</code> expands to <code>Sun 02/08/2015</code> while <code>%%~tF</code> expands to <code>02/08/2015 07:38 PM</code> the code below can be used with modifying line 4 to:</p>\n<pre><code>call :GetSeconds &quot;%DATE:~4% %TIME%&quot;\n</code></pre>\n<p>This results in passing to subroutine just <code>02/08/2015</code> - the date string without the 3 letters of weekday abbreviation and the separating space character.</p>\n<p>Alternatively following could be used to pass current date in correct format:</p>\n<pre><code>call :GetSeconds &quot;%DATE:~-10% %TIME%&quot;\n</code></pre>\n<p>Now the last 10 characters from date string are passed to function <code>GetSeconds</code> and therefore it does not matter if date string of environment variable <strong>DATE</strong> is with or without weekday as long as day and month are always with 2 digits in expected order, i.e. in format <code>dd/mm/yyyy</code> or <code>dd.mm.yyyy</code>.</p>\n<p>Here is the batch code with explaining comments which just outputs which file to delete and which file to keep in <code>C:\\Temp</code> folder tree, see code of first <strong>FOR</strong> loop.</p>\n<pre><code>@echo off\nsetlocal EnableExtensions DisableDelayedExpansion\nrem Get seconds since 1970-01-01 for current date and time.\ncall :GetSeconds &quot;%DATE% %TIME%&quot;\nrem Subtract seconds for 7 days from seconds value.\nset /A &quot;LastWeek=Seconds-7*86400&quot;\n\nrem For each file in each subdirectory of C:\\Temp get last modification date\nrem (without seconds -&gt; append second 0) and determine the number of seconds\nrem since 1970-01-01 for this date/time. The file can be deleted if seconds\nrem value is lower than the value calculated above.\n\nfor /F &quot;delims=&quot; %%# in ('dir /A-D-H-S /B /S &quot;C:\\Temp&quot;') do (\n call :GetSeconds &quot;%%~t#:0&quot;\n set &quot;FullFileName=%%#&quot;\n setlocal EnableDelayedExpansion\n rem if !Seconds! LSS %LastWeek% del /F &quot;!FullFileName!&quot;\n if !Seconds! LEQ %LastWeek% (\n echo Delete &quot;!FullFileName!&quot;\n ) else (\n echo Keep &quot;!FullFileName!&quot;\n )\n endlocal\n)\nendlocal\ngoto :EOF\n\n\nrem No validation is made for best performance. So make sure that date\nrem and hour in string is in a format supported by the code below like\nrem MM/DD/YYYY hh:mm:ss or M/D/YYYY h:m:s for English US date/time.\n\n:GetSeconds\nrem If there is &quot; AM&quot; or &quot; PM&quot; in time string because of using 12 hour\nrem time format, remove those 2 strings and in case of &quot; PM&quot; remember\nrem that 12 hours must be added to the hour depending on hour value.\n\nset &quot;DateTime=%~1&quot;\nset &quot;Add12Hours=0&quot;\nif not &quot;%DateTime: AM=%&quot; == &quot;%DateTime%&quot; (\n set &quot;DateTime=%DateTime: AM=%&quot;\n) else if not &quot;%DateTime: PM=%&quot; == &quot;%DateTime%&quot; (\n set &quot;DateTime=%DateTime: PM=%&quot;\n set &quot;Add12Hours=1&quot;\n)\n\nrem Get year, month, day, hour, minute and second from first parameter.\n\nfor /F &quot;tokens=1-6 delims=,-./: &quot; %%A in (&quot;%DateTime%&quot;) do (\n rem For English US date MM/DD/YYYY or M/D/YYYY\n set &quot;Day=%%B&quot; &amp; set &quot;Month=%%A&quot; &amp; set &quot;Year=%%C&quot;\n rem For German date DD.MM.YYYY or English UK date DD/MM/YYYY\n rem set &quot;Day=%%A&quot; &amp; set &quot;Month=%%B&quot; &amp; set &quot;Year=%%C&quot;\n set &quot;Hour=%%D&quot; &amp; set &quot;Minute=%%E&quot; &amp; set &quot;Second=%%F&quot;\n)\nrem echo Date/time is: %Year%-%Month%-%Day% %Hour%:%Minute%:%Second%\n\nrem Remove leading zeros from the date/time values or calculation could be wrong.\nif &quot;%Month:~0,1%&quot; == &quot;0&quot; if not &quot;%Month:~1%&quot; == &quot;&quot; set &quot;Month=%Month:~1%&quot;\nif &quot;%Day:~0,1%&quot; == &quot;0&quot; if not &quot;%Day:~1%&quot; == &quot;&quot; set &quot;Day=%Day:~1%&quot;\nif &quot;%Hour:~0,1%&quot; == &quot;0&quot; if not &quot;%Hour:~1%&quot; == &quot;&quot; set &quot;Hour=%Hour:~1%&quot;\nif &quot;%Minute:~0,1%&quot; == &quot;0&quot; if not &quot;%Minute:~1%&quot; == &quot;&quot; set &quot;Minute=%Minute:~1%&quot;\nif &quot;%Second:~0,1%&quot; == &quot;0&quot; if not &quot;%Second:~1%&quot; == &quot;&quot; set &quot;Second=%Second:~1%&quot;\n\nrem Add 12 hours for time range 01:00:00 PM to 11:59:59 PM,\nrem but keep the hour as is for 12:00:00 PM to 12:59:59 PM.\nif %Add12Hours% == 1 if %Hour% LSS 12 set /A Hour+=12\n\nset &quot;DateTime=&quot;\nset &quot;Add12Hours=&quot;\n\nrem Must use two arrays as more than 31 tokens are not supported\nrem by command line interpreter cmd.exe respectively command FOR.\nset /A &quot;Index1=Year-1979&quot;\nset /A &quot;Index2=Index1-30&quot;\n\nif %Index1% LEQ 30 (\n rem Get number of days to year for the years 1980 to 2009.\n for /F &quot;tokens=%Index1% delims= &quot; %%Y in (&quot;3652 4018 4383 4748 5113 5479 5844 6209 6574 6940 7305 7670 8035 8401 8766 9131 9496 9862 10227 10592 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245&quot;) do set &quot;Days=%%Y&quot;\n for /F &quot;tokens=%Index1% delims= &quot; %%L in (&quot;Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N&quot;) do set &quot;LeapYear=%%L&quot;\n) else (\n rem Get number of days to year for the years 2010 to 2038.\n for /F &quot;tokens=%Index2% delims= &quot; %%Y in (&quot;14610 14975 15340 15706 16071 16436 16801 17167 17532 17897 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550 21915 22280 22645 23011 23376 23741 24106 24472 24837&quot;) do set &quot;Days=%%Y&quot;\n for /F &quot;tokens=%Index2% delims= &quot; %%L in (&quot;N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N&quot;) do set &quot;LeapYear=%%L&quot;\n)\n\nrem Add the days to month in year.\nif &quot;%LeapYear%&quot; == &quot;N&quot; (\n for /F &quot;tokens=%Month% delims= &quot; %%M in (&quot;0 31 59 90 120 151 181 212 243 273 304 334&quot;) do set /A &quot;Days+=%%M&quot;\n) else (\n for /F &quot;tokens=%Month% delims= &quot; %%M in (&quot;0 31 60 91 121 152 182 213 244 274 305 335&quot;) do set /A &quot;Days+=%%M&quot;\n)\n\nrem Add the complete days in month of year.\nset /A &quot;Days+=Day-1&quot;\n\nrem Calculate the seconds which is easy now.\nset /A &quot;Seconds=Days*86400+Hour*3600+Minute*60+Second&quot;\n\nrem Exit this subroutine.\ngoto :EOF\n</code></pre>\n<p>For optimal performance it would be best to remove all comments, i.e. all lines starting with <strong>rem</strong> after 0-4 leading spaces.</p>\n<p>And the arrays can be made also smaller, i.e. decreasing the time range from 1980-01-01 00:00:00 to 2038-01-19 03:14:07 as currently supported by the batch code above for example to 2015-01-01 to 2019-12-31 as the code below uses which really deletes files older than 7 days in <code>C:\\Temp</code> folder tree.</p>\n<p>Further the batch code below is optimized for 24 hours time format.</p>\n<pre><code>@echo off\nsetlocal EnableExtensions DisableDelayedExpansion\ncall :GetSeconds &quot;%DATE:~-10% %TIME%&quot;\nset /A &quot;LastWeek=Seconds-7*86400&quot;\n\nfor /F &quot;delims=&quot; %%# in ('dir /A-D-H-S /B /S &quot;C:\\Temp&quot;') do (\n call :GetSeconds &quot;%%~t#:0&quot;\n set &quot;FullFileName=%%#&quot;\n setlocal EnableDelayedExpansion\n if !Seconds! LSS %LastWeek% del /F &quot;!FullFileName!&quot;\n endlocal\n)\nendlocal\ngoto :EOF\n\n:GetSeconds\nfor /F &quot;tokens=1-6 delims=,-./: &quot; %%A in (&quot;%~1&quot;) do (\n set &quot;Day=%%B&quot; &amp; set &quot;Month=%%A&quot; &amp; set &quot;Year=%%C&quot;\n set &quot;Hour=%%D&quot; &amp; set &quot;Minute=%%E&quot; &amp; set &quot;Second=%%F&quot;\n)\nif &quot;%Month:~0,1%&quot; == &quot;0&quot; if not &quot;%Month:~1%&quot; == &quot;&quot; set &quot;Month=%Month:~1%&quot;\nif &quot;%Day:~0,1%&quot; == &quot;0&quot; if not &quot;%Day:~1%&quot; == &quot;&quot; set &quot;Day=%Day:~1%&quot;\nif &quot;%Hour:~0,1%&quot; == &quot;0&quot; if not &quot;%Hour:~1%&quot; == &quot;&quot; set &quot;Hour=%Hour:~1%&quot;\nif &quot;%Minute:~0,1%&quot; == &quot;0&quot; if not &quot;%Minute:~1%&quot; == &quot;&quot; set &quot;Minute=%Minute:~1%&quot;\nif &quot;%Second:~0,1%&quot; == &quot;0&quot; if not &quot;%Second:~1%&quot; == &quot;&quot; set &quot;Second=%Second:~1%&quot;\nset /A &quot;Index=Year-2014&quot;\nfor /F &quot;tokens=%Index% delims= &quot; %%Y in (&quot;16436 16801 17167 17532 17897&quot;) do set &quot;Days=%%Y&quot;\nfor /F &quot;tokens=%Index% delims= &quot; %%L in (&quot;N Y N N N&quot;) do set &quot;LeapYear=%%L&quot;\nif &quot;%LeapYear%&quot; == &quot;N&quot; (\n for /F &quot;tokens=%Month% delims= &quot; %%M in (&quot;0 31 59 90 120 151 181 212 243 273 304 334&quot;) do set /A &quot;Days+=%%M&quot;\n) else (\n for /F &quot;tokens=%Month% delims= &quot; %%M in (&quot;0 31 60 91 121 152 182 213 244 274 305 335&quot;) do set /A &quot;Days+=%%M&quot;\n)\nset /A &quot;Days+=Day-1&quot;\nset /A &quot;Seconds=Days*86400+Hour*3600+Minute*60+Second&quot;\ngoto :EOF\n</code></pre>\n<p>For even more information about date and time formats and file time comparisons on Windows see my answer on <a href=\"https://stackoverflow.com/a/32670346/3074564\">Find out if file is older than 4 hours in batch file</a> with lots of additional information about file times.</p>\n" }, { "answer_id": 29420453, "author": "Sting", "author_id": 782991, "author_profile": "https://Stackoverflow.com/users/782991", "pm_score": 3, "selected": false, "text": "<p>Might I add a humble contribution to this already valuable thread. I'm finding that other solutions might get rid of the actual error text but are ignoring the %ERRORLEVEL% which signals a fail in my application. AND I legitimately want %ERRORLEVEL% just as long as it isn't the \"No files found\" error.</p>\n\n<p><strong>Some Examples:</strong></p>\n\n<p><strong>Debugging and eliminating the error specifically:</strong> </p>\n\n<pre><code>forfiles /p \"[file path...]\\IDOC_ARCHIVE\" /s /m *.txt /d -1 /c \"cmd /c del @path\" 2&gt;&amp;1 | findstr /V /O /C:\"ERROR: No files found with the specified search criteria.\"2&gt;&amp;1 | findstr ERROR&amp;&amp;ECHO found error||echo found success\n</code></pre>\n\n<p><strong>Using a oneliner to return ERRORLEVEL success or failure:</strong></p>\n\n<pre><code>forfiles /p \"[file path...]\\IDOC_ARCHIVE\" /s /m *.txt /d -1 /c \"cmd /c del @path\" 2&gt;&amp;1 | findstr /V /O /C:\"ERROR: No files found with the specified search criteria.\"2&gt;&amp;1 | findstr ERROR&amp;&amp;EXIT /B 1||EXIT /B 0\n</code></pre>\n\n<p><strong>Using a oneliner to keep the ERRORLEVEL at zero for success within the context of a batchfile in the midst of other code (ver > nul resets the ERRORLEVEL):</strong></p>\n\n<pre><code>forfiles /p \"[file path...]\\IDOC_ARCHIVE\" /s /m *.txt /d -1 /c \"cmd /c del @path\" 2&gt;&amp;1 | findstr /V /O /C:\"ERROR: No files found with the specified search criteria.\"2&gt;&amp;1 | findstr ERROR&amp;&amp;ECHO found error||ver &gt; nul\n</code></pre>\n\n<p><strong>For a SQL Server Agent CmdExec job step I landed on the following. I don't know if it's a bug, but the CmdExec within the step only recognizes the first line of code:</strong></p>\n\n<pre><code>cmd /e:on /c \"forfiles /p \"C:\\SQLADMIN\\MAINTREPORTS\\SQL2\" /s /m *.txt /d -1 /c \"cmd /c del @path\" 2&gt;&amp;1 | findstr /V /O /C:\"ERROR: No files found with the specified search criteria.\"2&gt;&amp;1 | findstr ERROR&amp;&amp;EXIT 1||EXIT 0\"&amp;exit %errorlevel%\n</code></pre>\n" }, { "answer_id": 31628166, "author": "Viktor Ka", "author_id": 4329986, "author_profile": "https://Stackoverflow.com/users/4329986", "pm_score": 4, "selected": false, "text": "<p>For windows 2012 R2 the following would work:</p>\n\n<pre><code> forfiles /p \"c:\\FOLDERpath\" /d -30 /c \"cmd /c del @path\"\n</code></pre>\n\n<p>to see the files which will be deleted use this</p>\n\n<pre><code> forfiles /p \"c:\\FOLDERpath\" /d -30 /c \"cmd /c echo @path @fdate\"\n</code></pre>\n" }, { "answer_id": 38958120, "author": "Shawn Pauliszyn", "author_id": 5095809, "author_profile": "https://Stackoverflow.com/users/5095809", "pm_score": 2, "selected": false, "text": "<p><strong>ROBOCOPY</strong> works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, <strong>move the files to the trash!!!</strong> </p>\n\n<p>This is is a few lines of my backup batch file for example:</p>\n\n<pre><code>SET FilesToClean1=C:\\Users\\pauls12\\Temp\nSET FilesToClean2=C:\\Users\\pauls12\\Desktop\\1616 - Champlain\\Engineering\\CAD\\Backups\n\nSET RecycleBin=C:\\$Recycle.Bin\\S-1-5-21-1480896384-1411656790-2242726676-748474\n\nrobocopy \"%FilesToClean1%\" \"%RecycleBin%\" /mov /MINLAD:15 /XA:SH /NC /NDL /NJH /NS /NP /NJS\nrobocopy \"%FilesToClean2%\" \"%RecycleBin%\" /mov /MINLAD:30 /XA:SH /NC /NDL /NJH /NS /NP /NJS\n</code></pre>\n\n<p>It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.</p>\n\n<p>This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.</p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 44065466, "author": "Snickbrack", "author_id": 3992990, "author_profile": "https://Stackoverflow.com/users/3992990", "pm_score": 1, "selected": false, "text": "<p>This one did it for me. It works with a date and you can substract the wanted amount in years to go back in time:</p>\n\n<pre><code>@echo off\n\nset m=%date:~-7,2%\nset /A m\nset dateYear=%date:~-4,4%\nset /A dateYear -= 2\nset DATE_DIR=%date:~-10,2%.%m%.%dateYear% \n\nforfiles /p \"C:\\your\\path\\here\\\" /s /m *.* /d -%DATE_DIR% /c \"cmd /c del @path /F\"\n\npause\n</code></pre>\n\n<p>the <code>/F</code> in the <code>cmd /c del @path /F</code> forces the specific file to be deleted in some the cases the file can be read-only.</p>\n\n<p>the <code>dateYear</code> is the year Variable and there you can change the substract to your own needs</p>\n" }, { "answer_id": 45113009, "author": "efdummy", "author_id": 2513412, "author_profile": "https://Stackoverflow.com/users/2513412", "pm_score": 1, "selected": false, "text": "<p>My script to delete files older than a specific year :</p>\n\n<pre><code>@REM _______ GENERATE A CMD TO DELETE FILES OLDER THAN A GIVEN YEAR\n@REM _______ (given in _olderthanyear variable)\n@REM _______ (you must LOCALIZE the script depending on the dir cmd console output)\n@REM _______ (we assume here the following line's format \"11/06/2017 15:04 58 389 SpeechToText.zip\")\n\n@set _targetdir=c:\\temp\n@set _olderthanyear=2017\n\n@set _outfile1=\"%temp%\\deleteoldfiles.1.tmp.txt\"\n@set _outfile2=\"%temp%\\deleteoldfiles.2.tmp.txt\"\n\n @if not exist \"%_targetdir%\" (call :process_error 1 DIR_NOT_FOUND \"%_targetdir%\") &amp; (goto :end)\n\n:main\n @dir /a-d-h-s /s /b %_targetdir%\\*&gt;%_outfile1%\n @for /F \"tokens=*\" %%F in ('type %_outfile1%') do @call :process_file_path \"%%F\" %_outfile2%\n @goto :end\n\n:end\n @rem ___ cleanup and exit\n @if exist %_outfile1% del %_outfile1%\n @if exist %_outfile2% del %_outfile2%\n @goto :eof\n\n:process_file_path %1 %2\n @rem ___ get date info of the %1 file path\n @dir %1 | find \"/\" | find \":\" &gt; %2\n @for /F \"tokens=*\" %%L in ('type %2') do @call :process_line \"%%L\" %1\n @goto :eof\n\n:process_line %1 %2\n @rem ___ generate a del command for each file older than %_olderthanyear%\n @set _var=%1\n @rem LOCALIZE HERE (char-offset,string-length)\n @set _fileyear=%_var:~0,4%\n @set _fileyear=%_var:~7,4%\n @set _filepath=%2\n @if %_fileyear% LSS %_olderthanyear% echo @REM %_fileyear%\n @if %_fileyear% LSS %_olderthanyear% echo @del %_filepath%\n @goto :eof\n\n:process_error %1 %2\n @echo RC=%1 MSG=%2 %3\n @goto :eof\n</code></pre>\n" }, { "answer_id": 49322063, "author": "GBGOLC", "author_id": 2048573, "author_profile": "https://Stackoverflow.com/users/2048573", "pm_score": 3, "selected": false, "text": "<p>Gosh, a lot of answers already. A simple and convenient route I found was to execute ROBOCOPY.EXE twice in sequential order from a single Windows command line instruction using the <strong>&amp;</strong> parameter.</p>\n\n<pre><code>ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 &amp; ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 /PURGE\n</code></pre>\n\n<p>In this example it works by picking all files (<em>.</em>) that are older than 30 days old and moving them to the target folder. The second command does the same again with the addition of the <strong>PURGE</strong> command which means remove files in the target folder that don’t exist in the source folder.\nSo essentially, the first command MOVES files and the second DELETES because they no longer exist in the source folder when the second command is invoked.</p>\n\n<p>Consult ROBOCOPY's documentation and use the /L switch when testing.</p>\n" }, { "answer_id": 64800901, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 0, "selected": false, "text": "<p>More flexible way is to use <a href=\"https://github.com/npocmaka/batch.scripts/blob/master/hybrids/jscript/FileTimeFilterJS.bat\" rel=\"nofollow noreferrer\"><code>FileTimeFilterJS.bat</code></a>:</p>\n<pre><code>@echo off\n\n::::::::::::::::::::::\nset &quot;_DIR=C:\\Users\\npocmaka\\Downloads&quot;\nset &quot;_DAYS=-5&quot;\n::::::::::::::::::::::\n\nfor /f &quot;tokens=* delims=&quot; %%# in ('FileTimeFilterJS.bat &quot;%_DIR%&quot; -dd %_DAYS%') do (\n echo deleting &quot;%%~f#&quot;\n echo del /q /f &quot;%%~f#&quot;\n)\n</code></pre>\n<p>The script will allow you to use measurements like days, minutes ,seconds or hours.\nTo choose weather to filter the files by time of creation, access or modification\nTo list files before or after a certain date (or between two dates)\nTo choose if to show files or dirs (or both)\nTo be recursive or not</p>\n" }, { "answer_id": 66343607, "author": "Miguel Carrillo", "author_id": 11762632, "author_profile": "https://Stackoverflow.com/users/11762632", "pm_score": 3, "selected": false, "text": "<p><strong>Delete all Files older than 3 days</strong></p>\n<pre><code>forfiles -p &quot;C:\\folder&quot; -m *.* -d -3 -c &quot;cmd /c del /q @path&quot;\n</code></pre>\n<p><strong>Delete Directories older than 3 days</strong></p>\n<pre><code>forfiles -p &quot;C:\\folder&quot; -d -3 -c &quot;cmd /c IF @isdir == TRUE rd /S /Q @path&quot;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task. Similar things can be [done in BASH](https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash) in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.
Enjoy: ``` forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path" ``` See [`forfiles` documentation](http://ss64.com/nt/forfiles.html) for more details. For more goodies, refer to *[An A-Z Index of the Windows XP command line](http://www.ss64.com/nt/)*. If you don't have `forfiles` installed on your machine, copy it from any [Windows Server 2003](http://en.wikipedia.org/wiki/Windows_Server_2003) to your Windows XP machine at `%WinDir%\system32\`. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP. Later versions of Windows and Windows Server have it installed by default. For Windows 7 and newer (including Windows 10): The syntax has changed a little. Therefore the updated command is: ``` forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path" ```
51,092
<p>Consider the Oracle <code>emp</code> table. I'd like to get the employees with the top salary with <code>department = 20</code> and <code>job = clerk</code>. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:</p> <pre><code>select * from scott.emp where deptno = 20 and job = 'CLERK' and sal = (select max(sal) from scott.emp where deptno = 20 and job = 'CLERK') </code></pre> <p>This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a <code>group by</code>? BTW, if this matters, I am using Oracle.</p>
[ { "answer_id": 51103, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 3, "selected": true, "text": "<p>The following is slightly over-engineered, but is a good SQL pattern for \"top x\" queries.</p>\n\n<pre><code>SELECT \n * \nFROM \n scott.emp\nWHERE \n (deptno,job,sal) IN\n (SELECT \n deptno,\n job,\n max(sal) \n FROM \n scott.emp\n WHERE \n deptno = 20 \n and job = 'CLERK'\n GROUP BY \n deptno,\n job\n )\n</code></pre>\n\n<p>Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question <a href=\"https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424\">SQL Query to get latest price</a></p>\n" }, { "answer_id": 51164, "author": "avernet", "author_id": 5295, "author_profile": "https://Stackoverflow.com/users/5295", "pm_score": 0, "selected": false, "text": "<p>That's great! I didn't know you could do a comparison of (x, y, z) with the result of a SELECT statement. This works great with Oracle.</p>\n\n<p>As a side-note for other readers, the above query is missing a \"=\" after \"(deptno,job,sal)\". Maybe the Stack Overflow formatter ate it (?).</p>\n\n<p>Again, thanks Mark.</p>\n" }, { "answer_id": 51369, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 2, "selected": false, "text": "<p>If I was certain of the targeted database I'd go with Mark Nold's solution, but if you ever want some dialect agnostic SQL*, try</p>\n\n<pre><code>SELECT * \nFROM scott.emp e\nWHERE e.deptno = 20 \nAND e.job = 'CLERK'\nAND e.sal = (\n SELECT MAX(e2.sal) \n FROM scott.emp e2\n WHERE e.deptno = e2.deptno \n AND e.job = e2.job\n)\n</code></pre>\n\n<p>*I believe this should work everywhere, but I don't have the environments to test it.</p>\n" }, { "answer_id": 51682, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 0, "selected": false, "text": "<p>In Oracle you can also use the EXISTS statement, which in some cases is faster.</p>\n\n<p>For example...\nSELECT name, number\nFROM cust \nWHERE cust IN\n ( SELECT cust_id FROM big_table )\n AND entered > SYSDATE -1\nwould be slow.</p>\n\n<p>but\nSELECT name, number\nFROM cust <strong>c</strong>\nWHERE EXISTS\n ( SELECT cust_id FROM big_table <strong>WHERE cust_id=c.cust_id</strong> )\n AND entered > SYSDATE -1\nwould be very fast with proper indexing. You can also use this with multiple parameters.</p>\n" }, { "answer_id": 57562, "author": "NateSchneider", "author_id": 5129, "author_profile": "https://Stackoverflow.com/users/5129", "pm_score": 0, "selected": false, "text": "<p>There are many solutions. You could also keep your original query layout by simply adding table aliases and joining on the column names, you would still only have DEPTNO = 20 and JOB = 'CLERK' in the query once.</p>\n\n<pre><code>SELECT \n * \nFROM \n scott.emp emptbl\nWHERE\n emptbl.DEPTNO = 20 \n AND emptbl.JOB = 'CLERK'\n AND emptbl.SAL = \n (\n select \n max(salmax.SAL) \n from \n scott.emp salmax\n where \n salmax.DEPTNO = emptbl.DEPTNO\n AND salmax.JOB = emptbl.JOB\n )\n</code></pre>\n\n<p>It could also be noted that the key word \"ALL\" can be used for these types of queries which would allow you to remove the \"MAX\" function.</p>\n\n<pre><code>SELECT \n * \nFROM \n scott.emp emptbl\nWHERE\n emptbl.DEPTNO = 20 \n AND emptbl.JOB = 'CLERK'\n AND emptbl.SAL &gt;= ALL \n (\n select \n salmax.SAL\n from \n scott.emp salmax\n where \n salmax.DEPTNO = emptbl.DEPTNO\n AND salmax.JOB = emptbl.JOB\n )\n</code></pre>\n\n<p>I hope that helps and makes sense.</p>\n" }, { "answer_id": 63160, "author": "Gabor Kecskemeti", "author_id": 6572, "author_profile": "https://Stackoverflow.com/users/6572", "pm_score": 1, "selected": false, "text": "<p>In Oracle I'd do it with an analytical function, so you'd only query the emp table once :</p>\n\n<pre><code>SELECT *\n FROM (SELECT e.*, MAX (sal) OVER () AS max_sal\n FROM scott.emp e\n WHERE deptno = 20 \n AND job = 'CLERK')\n WHERE sal = max_sal\n</code></pre>\n\n<p>It's simpler, easier to read and more efficient. </p>\n\n<p>If you want to modify it to list list this information for all departments, then you'll need to use the \"PARTITION BY\" clause in OVER:</p>\n\n<pre><code>SELECT *\n FROM (SELECT e.*, MAX (sal) OVER (PARTITION BY deptno) AS max_sal\n FROM scott.emp e\n WHERE job = 'CLERK')\n WHERE sal = max_sal\nORDER BY deptno\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
Consider the Oracle `emp` table. I'd like to get the employees with the top salary with `department = 20` and `job = clerk`. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with: ``` select * from scott.emp where deptno = 20 and job = 'CLERK' and sal = (select max(sal) from scott.emp where deptno = 20 and job = 'CLERK') ``` This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a `group by`? BTW, if this matters, I am using Oracle.
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. ``` SELECT * FROM scott.emp WHERE (deptno,job,sal) IN (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) ``` Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price](https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424)
51,093
<p>Jeff covered this a while back <a href="http://www.codinghorror.com/blog/archives/000811.html" rel="nofollow noreferrer">on his blog</a> in terms of 32 bit Vista.</p> <p>Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem?</p>
[ { "answer_id": 51100, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 2, "selected": false, "text": "<p>In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing.</p>\n\n<pre><code>2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb.\n</code></pre>\n\n<p>Although there are some ways around it. (Look up the jump from 16-bit computing to 32-bit computing. They hit the same problem.)</p>\n" }, { "answer_id": 51101, "author": "Alasdair", "author_id": 2654, "author_profile": "https://Stackoverflow.com/users/2654", "pm_score": 0, "selected": false, "text": "<p>Linux supports a technology called PAE that lets you use more than 4GB of memory, however I don't know whether Ubuntu has it on by default. You may need to compile a new kernel.</p>\n\n<p>Edit: Some threads on the Ubuntu forums suggest that the server kernel has PAE on by default, you could try installing that.</p>\n" }, { "answer_id": 51102, "author": "sphereinabox", "author_id": 2775, "author_profile": "https://Stackoverflow.com/users/2775", "pm_score": 2, "selected": false, "text": "<p>Yes, 32 bit ubuntu has the same memory limitations.</p>\n\n<p>There are exceptions to the 4GB limitation, but they are application specific... As in, Microsoft Sql Server can use 16 gigabytes with \"Physical address Extensions\" [PAE] configured and supported and... ugh\n<a href=\"http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3703755&amp;SiteID=17\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3703755&amp;SiteID=17</a></p>\n\n<p>Also drivers in ubuntu and windows both reduce the amount of memory available from the 4GB address space by mapping memory from that 4GB to devices. Graphics cards are particularly bad at this, your 256MB graphics card is using up at least 256MB of your address space...</p>\n\n<p>If you can [your drivers support it, and cpu is new enough] install a 64 bit os. Your 32 bit applications and games will run fine. </p>\n" }, { "answer_id": 51106, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>Well, with windows, there's something called <a href=\"http://en.wikipedia.org/wiki/Physical_Address_Extension\" rel=\"nofollow noreferrer\">PAE</a>, which means you can access up to 64 GB of memory on a windows machine. The downside is that most apps don't support actually using more than 4 GB of RAM. Only a small number of apps, like SQL Server are programmed to actually take advantage of all the extra memory.</p>\n" }, { "answer_id": 51387, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 2, "selected": false, "text": "<p>Ubuntu server has PAE enabled in the kernel, the desktop version does not have this feature enabled by default.</p>\n\n<p>This explains, by the way, why Ubuntu server does not work in some hardware emulators whereas the desktop edition does</p>\n" }, { "answer_id": 51409, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 2, "selected": false, "text": "<p>There seems to be some confusion around PAE. PAE is \"Page Address Extension\", and is by no means a Windows feature. It is a hack Intel put in their Pentium II (and newer) chips to allow machines to access 64GB of memory. On Windows, applications need to support PAE explicitely, but in the open source world, packages can be compiled and optimized to your liking. The packages that could use more than 4GB of memory on Ubuntu (and other Linux distro's) are compiled with PAE support. This includes all server-specific software.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
Jeff covered this a while back [on his blog](http://www.codinghorror.com/blog/archives/000811.html) in terms of 32 bit Vista. Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem?
In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing. ``` 2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb. ``` Although there are some ways around it. (Look up the jump from 16-bit computing to 32-bit computing. They hit the same problem.)
51,098
<p>I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner. I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).</p> <p>Any help would be great. References on how to do this or something similar are just as good as concrete code samples.</p>
[ { "answer_id": 51111, "author": "Michael Pryor", "author_id": 245, "author_profile": "https://Stackoverflow.com/users/245", "pm_score": 4, "selected": true, "text": "<p>In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.</p>\n\n<p>See <a href=\"http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=302\" rel=\"noreferrer\">this tutorial</a> for more info.</p>\n\n<p>I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like:</p>\n\n<pre><code>Dim xl: Set xl = CreateObject(\"Excel.Application\")\nxl.Open \"\\\\the\\share\\file.xls\"\n\nDim ws: Set ws = xl.Worksheets(1)\nws.Cells(0,1).Value = \"New Value\"\nws.Save\n\nxl.Quit constSilent\n</code></pre>\n" }, { "answer_id": 51375, "author": "paulmorriss", "author_id": 2983, "author_profile": "https://Stackoverflow.com/users/2983", "pm_score": 0, "selected": false, "text": "<p>You can open a spreadsheet in a single line:</p>\n\n<pre><code>Workbooks.Open FileName:=\"\\\\the\\share\\file.xls\"\n</code></pre>\n\n<p>and refer to it as the active workbook:</p>\n\n<pre><code>Range(\"A1\").value = \"New value\"\n</code></pre>\n" }, { "answer_id": 51413, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "<p>Copy the following in your <code>ThisWorkbook</code> object to watch for specific changes. In this case when you increase a numeric value to another numeric value. </p>\n\n<p>NB: you will have to replace <code>Workbook-SheetChange</code> and <code>Workbook-SheetSelectionChange</code> with an underscore. Ex: <code>Workbook_SheetChange</code> and <code>Workbook_SheetSelectionChange</code> the underscore gets escaped in Markdown code.</p>\n\n<pre><code>Option Explicit\nDim varPreviousValue As Variant ' required for IsThisMyChange() . This should be made more unique since it's in the global space.\n\n\nPrivate Sub Workbook-SheetChange(ByVal Sh As Object, ByVal Target As Range)\n ' required for IsThisMyChange()\n IsThisMyChange Sh, Target\nEnd Sub\n\nPrivate Sub Workbook-SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)\n ' This implements and awful way of accessing the previous value via a global.\n ' not pretty but required for IsThisMyChange()\n varPreviousValue = Target.Cells(1, 1).Value ' NB: This is used so that if a Merged set of cells if referenced only the first cell is used\nEnd Sub\n\nPrivate Sub IsThisMyChange(Sh As Object, Target As Range)\n Dim isMyChange As Boolean\n Dim dblValue As Double\n Dim dblPreviousValue As Double\n\n isMyChange = False\n\n ' Simple catch all. If either number cant be expressed as doubles, then exit.\n On Error GoTo ErrorHandler\n dblValue = CDbl(Target.Value)\n dblPreviousValue = CDbl(varPreviousValue)\n On Error GoTo 0 ' This turns off \"On Error\" statements in VBA.\n\n\n If dblValue &gt; dblPreviousValue Then\n isMyChange = True\n End If\n\n\n If isMyChange Then\n MsgBox (\"You've increased the value of \" &amp; Target.Address)\n End If\n\n\n ' end of normal execution\n Exit Sub\n\n\nErrorHandler:\n ' Do nothing much.\n Exit Sub\n\nEnd Sub\n</code></pre>\n\n<p>If you are wishing to change another workbook based on this, i'd think about checking to see if the workbook is already open first... or even better design a solution that can batch up all your changes and do them at once. Continuously changing another spreadsheet based on you listening to this one could be painful.</p>\n" }, { "answer_id": 54640, "author": "Justin Bennett", "author_id": 271, "author_profile": "https://Stackoverflow.com/users/271", "pm_score": 0, "selected": false, "text": "<p>After playing with this for a while, I found the Michael's pseudo-code was the closest, but here's how I did it:</p>\n\n<pre><code>Dim xl As Excel.Application\nSet xl = CreateObject(\"Excel.Application\")\nxl.Workbooks.Open \"\\\\owghome1\\bennejm$\\testing.xls\"\nxl.Sheets(\"Sheet1\").Select\n</code></pre>\n\n<p>Then, manipulate the sheet... maybe like this:</p>\n\n<pre><code>xl.Cells(x, y).Value = \"Some text\"\n</code></pre>\n\n<p>When you're done, use these lines to finish up:</p>\n\n<pre><code>xl.Workbooks.Close\nxl.Quit\n</code></pre>\n\n<p>If changes were made, the user will be prompted to save the file before it's closed. There might be a way to save automatically, but this way is actually better so I'm leaving it like it is.</p>\n\n<p>Thanks for all the help!</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271/" ]
I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner. I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though). Any help would be great. References on how to do this or something similar are just as good as concrete code samples.
In Excel, you would likely just write code to open the other worksheet, modify it and then save the data. See [this tutorial](http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=302) for more info. I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like: ``` Dim xl: Set xl = CreateObject("Excel.Application") xl.Open "\\the\share\file.xls" Dim ws: Set ws = xl.Worksheets(1) ws.Cells(0,1).Value = "New Value" ws.Save xl.Quit constSilent ```
51,108
<p>I really enjoyed <a href="http://www.codinghorror.com/blog/archives/001148.html" rel="noreferrer">Jeff's post</a> on <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming" rel="noreferrer">Spartan Programming</a>. I agree that code like that is a joy to read. Unfortunately, I'm not so sure it would necessarily be a joy to work with.</p> <p>For years I have read about and adhered to the "one-expression-per-line" practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like:</p> <pre><code>while (bytes = read(...)) { ... } while (GetMessage(...)) { ... } </code></pre> <p>Recently, I've advocated one expression per line for more practical reasons - debugging and production support. Getting a log file from production that claims a NullPointer exception at "line 65" which reads:</p> <pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber()); </code></pre> <p>is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the "most likely" object that was null ... this is a real practical pain.</p> <p>One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I've just created ...</p> <p>I try to be neat - but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse - but it really has come in handy when tracing things down in production or stepping through my or someone else's code.</p> <p>What style do <em>you</em> advocate and can you rationalize it in a practical sense?</p>
[ { "answer_id": 51112, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 2, "selected": false, "text": "<p>One expression per line.</p>\n\n<p>There is no reason to obfuscate your code. The extra time you take typing the few extra terms, you save in debug time.</p>\n" }, { "answer_id": 51147, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": false, "text": "<p>I think the ideal solution is to find a balance between the extremes. There is no way to write a rule that will fit in all situations; it comes with experience. Declaring each intermediate variable on its own line will make reading the code more difficult, which will also contribute to the difficulty in maintenance. By the same token, debugging is much more difficult if you inline the intermediate values.</p>\n\n<p>The 'sweet spot' is somewhere in the middle.</p>\n" }, { "answer_id": 51152, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 2, "selected": false, "text": "<p>I tend to err on the side of readability, not necessarily debuggability. The examples you gave should definitely be avoided, but I feel that judicious use of multiple expressions can make the code more concise and comprehensible.</p>\n" }, { "answer_id": 51166, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 4, "selected": true, "text": "<p>In <strong>The Pragmatic Programmer</strong> Hunt and Thomas talk about a study they term the Law of Demeter and it focuses on the coupling of functions to modules other than there own. By allowing a function to never reach a 3rd level in it's coupling you significantly reduce the number of errors and increase the maintainability of the code. </p>\n\n<p>So:</p>\n\n<blockquote>\n <p>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());</p>\n</blockquote>\n\n<p>Is close to a felony because we are 4 objects down the rat hole. That means to change something in one of those objects I have to know that you called this whole stack right here in this very method. What a pain.</p>\n\n<p>Better:</p>\n\n<blockquote>\n <p>Account.getUser();</p>\n</blockquote>\n\n<p>Note this runs counter to the expressive forms of programming that are now really popular with mocking software. The trade off there is that you have a tightly coupled interface anyway, and the expressive syntax just makes it easier to use.</p>\n" }, { "answer_id": 51182, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 2, "selected": false, "text": "<p>I'm usually in the \"shorter is better\" camp. Your example is good:</p>\n\n<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>I would cringe if I saw that over four lines instead of one--I don't think it'd make it easier to read or understand. The way you presented it here, it's clear that you're digging for a single object. This isn't better:</p>\n\n<pre><code>obja State = session.getState();\nobjb Account = State.getAccount();\nobjc AccountNumber = Account.getAccountNumber();\nObjectA a = getTheUser(AccountNumber);\n</code></pre>\n\n<p>This is a compromise:</p>\n\n<pre><code>objb Account = session.getState().getAccount();\nObjectA a = getTheUser(Account.getAccountNumber());\n</code></pre>\n\n<p>but I still prefer the single line expression. Here's an anecdotal reason: it's difficult for me to reread and error-check the 4-liner right now for dumb typos; the single line doesn't have this problem because there are simply fewer characters.</p>\n" }, { "answer_id": 51484, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 0, "selected": false, "text": "<p>Maintainability, and with it, readability, is king. Luckily, shorter very often means more readable.</p>\n\n<p>Here are a few tips I enjoy using to slice and dice code:</p>\n\n<ul>\n<li><strong>Variable names</strong>: how would you describe this variable to someone else on your team? You would <em>not</em> say \"the numberOfLinesSoFar integer\". You would say \"numLines\" or something similar - comprehensible and short. Don't pretend like the maintainer doesn't know the code at all, but make sure you yourself could figure out what the variable is, even if you forgot your own act of writing it. Yes, this is kind of obvious, but it's worth more effort than I see many coders put into it, so I list it first.</li>\n<li><strong>Control flow</strong>: Avoid lots of closing clauses at once (a series of }'s in C++). Usually when you see this, there's a way to avoid it. A common case is something like</li>\n</ul>\n\n<p>:</p>\n\n<pre><code>if (things_are_ok) {\n // Do a lot of stuff.\n return true;\n} else {\n ExpressDismay(error_str);\n return false;\n}\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code>if (!things_are_ok) return ExpressDismay(error_str);\n// Do a lot of stuff.\nreturn true;\n</code></pre>\n\n<p>if we can get ExpressDismay (or a wrapper thereof) to return false.</p>\n\n<p>Another case is:</p>\n\n<ul>\n<li><strong>Loop iterations</strong>: the more standard, the better. For shorter loops, it's good to use one-character iterators when the variable is never used except as an index into a single object.</li>\n</ul>\n\n<p>The particular case I would argue here is against the \"right\" way to use an STL container:</p>\n\n<pre><code>for (vector&lt;string&gt;::iterator a_str = my_vec.begin(); a_str != my_vec.end(); ++a_str)\n</code></pre>\n\n<p>is a lot wordier, and requires overloaded pointer operators *a_str or a_str->size() in the loop. For containers that have fast random access, the following is a lot easier to read:</p>\n\n<pre><code>for (int i = 0; i &lt; my_vec.size(); ++i)\n</code></pre>\n\n<p>with references to my_vec[i] in the loop body, which won't confuse anyone.</p>\n\n<p>Finally, I often see coders take pride in their line number counts. But it's not the line numbers that count! I'm not sure of the best way to implement this, but if you have any influence over your coding culture, I'd try to shift the reward toward those with compact classes :)</p>\n" }, { "answer_id": 51533, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 0, "selected": false, "text": "<p>Good explanation. I think this is version of the general <a href=\"http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm\" rel=\"nofollow noreferrer\">Divide and Conquer</a> mentality.</p>\n" }, { "answer_id": 4297073, "author": "Zecc", "author_id": 400127, "author_profile": "https://Stackoverflow.com/users/400127", "pm_score": 2, "selected": false, "text": "<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>This is a bad example, probably because you just wrote something from the top of your head.\nYou are assigning, to variable named <code>a</code> of type <code>ObjectA</code>, the return value of a function named <code>getTheUser</code>.<br>\nSo let's assume you wrote this instead:</p>\n\n<pre><code>User u = getTheUser(session.getState().getAccount().getAccountNumber());\n</code></pre>\n\n<p>I would break this expression like so:</p>\n\n<pre><code>Account acc = session.getState().getAccount();\nUser user = getTheUser( acc.getAccountNumber() );\n</code></pre>\n\n<p>My reasoning is: how would I think about what I am doing with this code?<br>\nI would probably think: \"first I need to get the account from the session and then I get the user using that account's number\".</p>\n\n<p>The code should read the way you think. Variables should refer to the main entities involved; not so much to their properties (so I wouldn't store the account number in a variable).</p>\n\n<p>A second factor to have in mind is: will I ever need to refer to this entity again in this context?<br>\nIf, say, I'm pulling more stuff out of the session state, I would introduce <code>SessionState state = session.getState()</code>.</p>\n\n<p>This all seems obvious, but I'm afraid I have some difficulty putting in words why it makes sense, not being a native English speaker and all.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4910/" ]
I really enjoyed [Jeff's post](http://www.codinghorror.com/blog/archives/001148.html) on [Spartan Programming](http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming). I agree that code like that is a joy to read. Unfortunately, I'm not so sure it would necessarily be a joy to work with. For years I have read about and adhered to the "one-expression-per-line" practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like: ``` while (bytes = read(...)) { ... } while (GetMessage(...)) { ... } ``` Recently, I've advocated one expression per line for more practical reasons - debugging and production support. Getting a log file from production that claims a NullPointer exception at "line 65" which reads: ``` ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber()); ``` is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the "most likely" object that was null ... this is a real practical pain. One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I've just created ... I try to be neat - but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse - but it really has come in handy when tracing things down in production or stepping through my or someone else's code. What style do *you* advocate and can you rationalize it in a practical sense?
In **The Pragmatic Programmer** Hunt and Thomas talk about a study they term the Law of Demeter and it focuses on the coupling of functions to modules other than there own. By allowing a function to never reach a 3rd level in it's coupling you significantly reduce the number of errors and increase the maintainability of the code. So: > > ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber()); > > > Is close to a felony because we are 4 objects down the rat hole. That means to change something in one of those objects I have to know that you called this whole stack right here in this very method. What a pain. Better: > > Account.getUser(); > > > Note this runs counter to the expressive forms of programming that are now really popular with mocking software. The trade off there is that you have a tightly coupled interface anyway, and the expressive syntax just makes it easier to use.
51,113
<p>It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?</p>
[ { "answer_id": 51120, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 5, "selected": false, "text": "<pre><code>if(dr.Read())\n{\n //do stuff\n}\nelse\n{\n //it's empty\n}\n</code></pre>\n\n<p>usually you'll do this though:</p>\n\n<pre><code>while(dr.Read())\n{\n}\n</code></pre>\n" }, { "answer_id": 51121, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": false, "text": "<p>Yes, if you want to use the interface then Read until false is the only way to test. If you are looking for a generic <code>IDataReader</code> implementation, you could try <code>DbDataReader</code> and use the <code>HasRows</code> property.</p>\n" }, { "answer_id": 16146731, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>You can just cast <code>System.Data.IDataReader</code> to <code>System.Data.Common.DbDataReader</code> </p>\n\n<pre><code>using (System.Data.IDataReader IReader = ICommand.ExecuteReader())\n{\n if (((System.Data.Common.DbDataReader)IReader).HasRows)\n {\n //do stuff\n }\n} // End Using IReader \n</code></pre>\n\n<p>It's pure evil, but it (usually) works ;) </p>\n\n<p>(assuming your instance of <code>IDataReader</code> is implemented by a custom ADO.NET provider, and not some custom silly class of yours which just implements <code>IDataReader</code> instead of deriving from <code>DbDataReader</code> [which implements <code>IDataReader</code>]).</p>\n" }, { "answer_id": 29829487, "author": "SimonGates", "author_id": 387809, "author_profile": "https://Stackoverflow.com/users/387809", "pm_score": 2, "selected": false, "text": "<p>Just stumbled across this problem and came up with this...</p>\n\n<pre><code>bool isBeforeEoF;\n\ndo\n{\n isBeforeEoF = reader.Read();\n\n if (isBeforeEoF)\n {\n yield return new Foo()\n {\n StreamID = (Guid)reader[\"ID\"],\n FileType = (string)reader[\"Type\"],\n Name = (string)reader[\"Name\"],\n RelativePath = (string)reader[\"RelativePath\"]\n }; \n }\n\n} while (isBeforeEoF);\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?
``` if(dr.Read()) { //do stuff } else { //it's empty } ``` usually you'll do this though: ``` while(dr.Read()) { } ```
51,129
<p>In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that?</p> <p>For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back </p> <pre><code>&lt;xml&gt;&lt;somekey&gt;somevalue&lt;/somekey&gt;&lt;/xml&gt; </code></pre> <p>I'd like it to spit out "somevalue".</p>
[ { "answer_id": 51136, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "<p>I think it will be useful to read this first:</p>\n\n<p><a href=\"https://web.archive.org/web/20211020134836/https://aspnet.4guysfromrolla.com/articles/062602-1.aspx\" rel=\"nofollow noreferrer\">Creating and Consuming a Web Service</a> (in .NET)</p>\n\n<p>This is a series of tutorials of how web services are used in .NET, including how XML input is used (deserialization).</p>\n" }, { "answer_id": 51143, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You can use something like that:</p>\n\n<pre><code>var client = new WebClient();\nvar response = client.UploadValues(\"www.webservice.com\", \"POST\", new NameValueCollection {{\"fXML\", \"1\"}});\nusing (var reader = new StringReader(Encoding.UTF8.GetString(response)))\n{\n var xml = XElement.Load(reader);\n var value = xml.Element(\"somekey\").Value;\n Console.WriteLine(\"Some value: \" + value); \n}\n</code></pre>\n\n<p>Note I didn't have a chance to test this code, but it should work :)</p>\n" }, { "answer_id": 51225, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": true, "text": "<p>I use this code and it works great:</p>\n\n<pre><code>System.Xml.XmlDocument xd = new System.Xml.XmlDocument;\nxd.Load(\"http://www.webservice.com/webservice?fXML=1\");\nstring xPath = \"/xml/somekey\";\n// this node's inner text contains \"somevalue\"\nreturn xd.SelectSingleNode(xPath).InnerText;\n</code></pre>\n\n<hr>\n\n<p>EDIT: I just realized you're talking about a webservice and not just plain XML. In your Visual Studio Solution, try right clicking on References in Solution Explorer and choose \"Add a Web Reference\". A dialog will appear asking for a URL, you can just paste it in: \"<a href=\"http://www.webservice.com/webservice.asmx\" rel=\"nofollow noreferrer\">http://www.webservice.com/webservice.asmx</a>\". VS will autogenerate all the helpers you need. Then you can just call:</p>\n\n<pre><code>com.webservice.www.WebService ws = new com.webservice.www.WebService();\n// this assumes your web method takes in the fXML as an integer attribute\nreturn ws.SomeWebMethod(1);\n</code></pre>\n" }, { "answer_id": 51383, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>It may also be worth adding that if you need to specifically use POST rather than SOAP then you can configure the web service to receive POST calls:</p>\n\n<p>Check out the page on MSDN:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa719747(VS.71).aspx\" rel=\"nofollow noreferrer\">Configuration Options for XML Web Services Created Using ASP.NET</a></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ]
In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that? For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back ``` <xml><somekey>somevalue</somekey></xml> ``` I'd like it to spit out "somevalue".
I use this code and it works great: ``` System.Xml.XmlDocument xd = new System.Xml.XmlDocument; xd.Load("http://www.webservice.com/webservice?fXML=1"); string xPath = "/xml/somekey"; // this node's inner text contains "somevalue" return xd.SelectSingleNode(xPath).InnerText; ``` --- EDIT: I just realized you're talking about a webservice and not just plain XML. In your Visual Studio Solution, try right clicking on References in Solution Explorer and choose "Add a Web Reference". A dialog will appear asking for a URL, you can just paste it in: "<http://www.webservice.com/webservice.asmx>". VS will autogenerate all the helpers you need. Then you can just call: ``` com.webservice.www.WebService ws = new com.webservice.www.WebService(); // this assumes your web method takes in the fXML as an integer attribute return ws.SomeWebMethod(1); ```
51,139
<p>I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values. Any ideas? I'm thinking I could use a DataReader source to generate the preset values by doing the following:</p> <pre><code>SELECT 'foo' as 'attribute1', 'bar' as 'attribute2' </code></pre> <p>The question is, how would I insert one row of this type for every row in the XML data source?</p>
[ { "answer_id": 51158, "author": "Tadmas", "author_id": 3750, "author_profile": "https://Stackoverflow.com/users/3750", "pm_score": 2, "selected": false, "text": "<p>I've never tried it, but it looks like you might be able to use a <a href=\"http://msdn.microsoft.com/en-us/library/ms141069(SQL.90).aspx\" rel=\"nofollow noreferrer\">Derived Column transformation</a> to do it: set the expression for attribute1 to <code>\"foo\"</code> and the expression for attribute2 to <code>\"bar\"</code>.</p>\n\n<p>You'd then transform the original data source, then only use the derived columns in your destination. If you still need the original source, you can Multicast it to create a duplicate.</p>\n\n<p>At least I think this will work, based on the documentation. YMMV.</p>\n" }, { "answer_id": 52159, "author": "jwolly2", "author_id": 5202, "author_profile": "https://Stackoverflow.com/users/5202", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if I understand the question... My assumption is that you have <em>n</em> number of records coming into SSIS from your data source, and you want your output to have <em>n</em> * 2 records.</p>\n\n<p>In order to do this, you can do the following:</p>\n\n<ul>\n<li>multicast to create multiple copies of your input data</li>\n<li>derived column transforms to set the \"preset\" values on the copies</li>\n<li>sort</li>\n<li>merge</li>\n</ul>\n\n<p>Am I on the right track w/ what you're trying to accomplish?</p>\n" }, { "answer_id": 88120, "author": "CodeRot", "author_id": 14134, "author_profile": "https://Stackoverflow.com/users/14134", "pm_score": 0, "selected": false, "text": "<p>I would probably switch to using a Script Task and place your logic in there. You may still be able leverage the File Reading and other objects in SSIS to save some code.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4550/" ]
I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values. Any ideas? I'm thinking I could use a DataReader source to generate the preset values by doing the following: ``` SELECT 'foo' as 'attribute1', 'bar' as 'attribute2' ``` The question is, how would I insert one row of this type for every row in the XML data source?
I've never tried it, but it looks like you might be able to use a [Derived Column transformation](http://msdn.microsoft.com/en-us/library/ms141069(SQL.90).aspx) to do it: set the expression for attribute1 to `"foo"` and the expression for attribute2 to `"bar"`. You'd then transform the original data source, then only use the derived columns in your destination. If you still need the original source, you can Multicast it to create a duplicate. At least I think this will work, based on the documentation. YMMV.
51,148
<p>I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.</p> <p>So how in C# would I so this in the example below?</p> <pre><code>using System.Diagnostics; ... Process foo = new Process(); foo.StartInfo.FileName = @"C:\bar\foo.exe"; foo.StartInfo.Arguments = "Username Password"; bool isRunning = //TODO: Check to see if process foo.exe is already running if (isRunning) { //TODO: Switch to foo.exe process } else { foo.Start(); } </code></pre>
[ { "answer_id": 51149, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 6, "selected": true, "text": "<p>This should do it for ya.</p>\n\n<p><a href=\"http://www.dreamincode.net/code/snippet1541.htm\" rel=\"noreferrer\">Check Processes</a></p>\n\n<pre><code>//Namespaces we need to use\nusing System.Diagnostics;\n\npublic bool IsProcessOpen(string name)\n{\n //here we're going to get a list of all running processes on\n //the computer\n foreach (Process clsProcess in Process.GetProcesses()) {\n //now we're going to see if any of the running processes\n //match the currently running processes. Be sure to not\n //add the .exe to the name you provide, i.e: NOTEPAD,\n //not NOTEPAD.EXE or false is always returned even if\n //notepad is running.\n //Remember, if you have the process running more than once, \n //say IE open 4 times the loop thr way it is now will close all 4,\n //if you want it to just close the first one it finds\n //then add a return; after the Kill\n if (clsProcess.ProcessName.Contains(name))\n {\n //if the process is found to be running then we\n //return a true\n return true;\n }\n }\n //otherwise we return a false\n return false;\n}\n\n</code>\n</pre>\n" }, { "answer_id": 51151, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You can simply enumerate processes using <a href=\"http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx\" rel=\"nofollow noreferrer\">Process.GetProcesses</a> method.</p>\n" }, { "answer_id": 51154, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 1, "selected": false, "text": "<p>I think the complete answer to your problem requires understanding of what happens when your application determines that an instance of foo.exe is already running i.e what does '//TODO: Switch to foo.exe process' actually mean?</p>\n" }, { "answer_id": 51155, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>I have used the AppActivate function in VB runtime to activate an existing process.\nYou will have to import Microsoft.VisualBasic dll into the C# project.</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing Microsoft.VisualBasic;\n\nnamespace ConsoleApplication3\n{\n class Program\n {\n static void Main(string[] args)\n {\n Process[] proc = Process.GetProcessesByName(\"notepad\");\n Interaction.AppActivate(proc[0].MainWindowTitle);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 51173, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": false, "text": "<p>You can use LINQ as well,</p>\n\n<pre><code>var processExists = Process.GetProcesses().Any(p =&gt; p.ProcessName.Contains(\"&lt;your process name&gt;\"));\n</code></pre>\n" }, { "answer_id": 51181, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 1, "selected": false, "text": "<p>In a past project I needed to prevent multiple execution of a process, so I added a some code in the init section of that process which creates a named mutex. This mutext was created and acquired before continuing the rest of the process. If the process can create the mutex and acquire it, then it is the first one running. If another process already controls the mutex, then the one which fails is not the first so it exits immediately. </p>\n\n<p>I was just trying to prevent a second instance from running, due to dependencies on specific hardware interfaces. Depending on what you need with that \"switch to\" line, you might need a more specific solution such as a process id or handle.</p>\n\n<p>Also, I had source code access to the process I was trying to start. If you can not modify the code, adding the mutex is obviously not an option.</p>\n" }, { "answer_id": 51189, "author": "csjohnst", "author_id": 1292, "author_profile": "https://Stackoverflow.com/users/1292", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Mnebuerquo wrote: </p>\n \n <blockquote>\n <p>Also, I had source code access to the\n process I was trying to start. If you\n can not modify the code, adding the\n mutex is obviously not an option.</p>\n </blockquote>\n</blockquote>\n\n<p>I don't have source code access to the process I want to run. </p>\n\n<p>I have ended up using the proccess MainWindowHandle to switch to the process once I have found it is alread running:</p>\n\n<pre><code>[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n" }, { "answer_id": 51222, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>Two concerns to keep in mind:</p>\n\n<ol>\n<li><p>Your example involved placing a\npassword on a command line. That\ncleartext representation of a secret\ncould be a security vulnerability.</p></li>\n<li><p>When enumerating processes, ask\nyourself which processes you really\nwant to enumerate. All users, or\njust the current user? What if the\ncurrent user is logged in twice (two\ndesktops)?</p></li>\n</ol>\n" }, { "answer_id": 23824382, "author": "Israel Ocbina", "author_id": 1990838, "author_profile": "https://Stackoverflow.com/users/1990838", "pm_score": 2, "selected": false, "text": "<p>I found out that Mutex is not working like in the Console application. So using WMI to query processes that can be seen using Task Manager window will solved your problem.</p>\n\n<p>Use something like this:</p>\n\n<pre><code>static bool isStillRunning() {\n string processName = Process.GetCurrentProcess().MainModule.ModuleName;\n ManagementObjectSearcher mos = new ManagementObjectSearcher();\n mos.Query.QueryString = @\"SELECT * FROM Win32_Process WHERE Name = '\" + processName + @\"'\";\n if (mos.Get().Count &gt; 1)\n {\n return true;\n }\n else\n return false;\n}\n</code></pre>\n\n<p>NOTE: Add assembly reference \"System.Management\" to enable the type intellisense.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1292/" ]
I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it. So how in C# would I so this in the example below? ``` using System.Diagnostics; ... Process foo = new Process(); foo.StartInfo.FileName = @"C:\bar\foo.exe"; foo.StartInfo.Arguments = "Username Password"; bool isRunning = //TODO: Check to see if process foo.exe is already running if (isRunning) { //TODO: Switch to foo.exe process } else { foo.Start(); } ```
This should do it for ya. [Check Processes](http://www.dreamincode.net/code/snippet1541.htm) ``` //Namespaces we need to use using System.Diagnostics; public bool IsProcessOpen(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { //now we're going to see if any of the running processes //match the currently running processes. Be sure to not //add the .exe to the name you provide, i.e: NOTEPAD, //not NOTEPAD.EXE or false is always returned even if //notepad is running. //Remember, if you have the process running more than once, //say IE open 4 times the loop thr way it is now will close all 4, //if you want it to just close the first one it finds //then add a return; after the Kill if (clsProcess.ProcessName.Contains(name)) { //if the process is found to be running then we //return a true return true; } } //otherwise we return a false return false; } ```
51,150
<p>When an application is behind another applications and I click on my application's taskbar icon, I expect the entire application to come to the top of the z-order, even if an app-modal, WS_POPUP dialog box is open.</p> <p>However, some of the time, for some of my (and others') dialog boxes, only the dialog box comes to the front; the rest of the application stays behind.</p> <p>I've looked at Spy++ and for the ones that work correctly, I can see WM_WINDOWPOSCHANGING being sent to the dialog's parent. For the ones that leave the rest of the application behind, WM_WINDOWPOSCHANGING is not being sent to the dialog's parent.</p> <p>I have an example where one dialog usually brings the whole app with it and the other does not. Both the working dialog box and the non-working dialog box have the same window style, substyle, parent, owner, ontogeny.</p> <p>In short, both are WS_POPUPWINDOW windows created with DialogBoxParam(), having passed in identical HWNDs as the third argument.</p> <p>Has anyone else noticed this behavioral oddity in Windows programs? What messages does the TaskBar send to the application when I click its button? Who's responsibility is it to ensure that <em>all</em> of the application's windows come to the foreground?</p> <p>In my case the base parentage is an MDI frame...does that factor in somehow?</p>
[ { "answer_id": 51160, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 0, "selected": false, "text": "<p>Is the dialog's parent window set correctly?</p>\n\n<p>After I posted this, I started my own Windows Forms application and reproduced the problem you describe. I have two dialogs, one works correctly the other does not and I can't see any immediate reason is to why they behave differently. I'll update this post if I find out.</p>\n\n<p>Raymond Chen where are you!</p>\n" }, { "answer_id": 99547, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": false, "text": "<p>When you click on the taskbar icon Windows will send a <strong>WM_ACTIVATE</strong> message to your application.</p>\n\n<p>Are you sure your code is passing the <strong>WM_ACTIVATE</strong> message to the <strong>DefWindowProc</strong> window procedure for processing?</p>\n" }, { "answer_id": 1777881, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 3, "selected": false, "text": "<p>I know this is very old now, but I just stumbled across it, and I know the answer.</p>\n\n<p>In the applications you've seen (and written) where bringing the dialog box to the foreground did <strong>not</strong> bring the main window up along with it, the developer has simply neglected to specify the owner of the dialog box.</p>\n\n<p>This applies to both modal windows, like dialog boxes and message boxes, as well as to modeless windows. Setting the owner of a modeless popup also keeps the popup above its owner at all times.</p>\n\n<p>In the Win32 API, the functions to bring up a dialog box or a message box take the owner window as a parameter:</p>\n\n<pre><code>INT_PTR DialogBox(\n HINSTANCE hInstance,\n LPCTSTR lpTemplate,\n HWND hWndParent, /* this is the owner */\n DLGPROC lpDialogFunc\n);\n\nint MessageBox(\n HWND hWnd, /* this is the owner */\n LPCTSTR lpText,\n LPCTSTR lpCaption,\n UINT uType\n);\n</code></pre>\n\n<p>Similary, in .NET WinForms, the owner can be specified:</p>\n\n<pre><code>public DialogResult ShowDialog(\n IWin32Window owner\n)\n\npublic static DialogResult Show(\n IWin32Window owner,\n string text\n) /* ...and other overloads that include this first parameter */\n</code></pre>\n\n<p>Additionally, in WinForms, it's easy to set the owner of a modeless window:</p>\n\n<pre><code>public void Show(\n IWin32Window owner,\n)\n</code></pre>\n\n<p>or, equivalently:</p>\n\n<pre><code>form.Owner = this;\nform.Show();\n</code></pre>\n\n<p>In straight WinAPI code, the owner of a modeless window can be set when the window is created:</p>\n\n<pre><code>HWND CreateWindow(\n LPCTSTR lpClassName,\n LPCTSTR lpWindowName,\n DWORD dwStyle,\n int x,\n int y,\n int nWidth,\n int nHeight,\n HWND hWndParent, /* this is the owner if dwStyle does not contain WS_CHILD */\n HMENU hMenu,\n HINSTANCE hInstance,\n LPVOID lpParam\n);\n</code></pre>\n\n<p>or afterwards:</p>\n\n<pre><code>SetWindowLong(hWndPopup, GWL_HWNDPARENT, (LONG)hWndOwner);\n</code></pre>\n\n<p>or (64-bit compatible)</p>\n\n<pre><code>SetWindowLongPtr(hWndPopup, GWLP_HWNDPARENT, (LONG_PTR)hWndOwner);\n</code></pre>\n\n<p>Note that MSDN has the following to say about <a href=\"http://msdn.microsoft.com/en-us/library/ms644898(VS.85).aspx\" rel=\"noreferrer\">SetWindowLong[Ptr]</a>:</p>\n\n<blockquote>\n <p>Do not call <strong>SetWindowLongPtr</strong> with the GWLP_HWNDPARENT index to change the parent of a child window. Instead, use the <a href=\"http://msdn.microsoft.com/en-us/library/ms633541(VS.85).aspx\" rel=\"noreferrer\">SetParent</a> function. </p>\n</blockquote>\n\n<p>This is somewhat misleading, as it seems to imply that the last two snippets above are wrong. This isn't so. Calling <code>SetParent</code> will turn the intended popup into a <em>child</em> of the parent window (setting its <code>WS_CHILD</code> bit), rather than making it an owned window. The code above is the correct way to make an existing popup an owned window.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
When an application is behind another applications and I click on my application's taskbar icon, I expect the entire application to come to the top of the z-order, even if an app-modal, WS\_POPUP dialog box is open. However, some of the time, for some of my (and others') dialog boxes, only the dialog box comes to the front; the rest of the application stays behind. I've looked at Spy++ and for the ones that work correctly, I can see WM\_WINDOWPOSCHANGING being sent to the dialog's parent. For the ones that leave the rest of the application behind, WM\_WINDOWPOSCHANGING is not being sent to the dialog's parent. I have an example where one dialog usually brings the whole app with it and the other does not. Both the working dialog box and the non-working dialog box have the same window style, substyle, parent, owner, ontogeny. In short, both are WS\_POPUPWINDOW windows created with DialogBoxParam(), having passed in identical HWNDs as the third argument. Has anyone else noticed this behavioral oddity in Windows programs? What messages does the TaskBar send to the application when I click its button? Who's responsibility is it to ensure that *all* of the application's windows come to the foreground? In my case the base parentage is an MDI frame...does that factor in somehow?
I know this is very old now, but I just stumbled across it, and I know the answer. In the applications you've seen (and written) where bringing the dialog box to the foreground did **not** bring the main window up along with it, the developer has simply neglected to specify the owner of the dialog box. This applies to both modal windows, like dialog boxes and message boxes, as well as to modeless windows. Setting the owner of a modeless popup also keeps the popup above its owner at all times. In the Win32 API, the functions to bring up a dialog box or a message box take the owner window as a parameter: ``` INT_PTR DialogBox( HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent, /* this is the owner */ DLGPROC lpDialogFunc ); int MessageBox( HWND hWnd, /* this is the owner */ LPCTSTR lpText, LPCTSTR lpCaption, UINT uType ); ``` Similary, in .NET WinForms, the owner can be specified: ``` public DialogResult ShowDialog( IWin32Window owner ) public static DialogResult Show( IWin32Window owner, string text ) /* ...and other overloads that include this first parameter */ ``` Additionally, in WinForms, it's easy to set the owner of a modeless window: ``` public void Show( IWin32Window owner, ) ``` or, equivalently: ``` form.Owner = this; form.Show(); ``` In straight WinAPI code, the owner of a modeless window can be set when the window is created: ``` HWND CreateWindow( LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, /* this is the owner if dwStyle does not contain WS_CHILD */ HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam ); ``` or afterwards: ``` SetWindowLong(hWndPopup, GWL_HWNDPARENT, (LONG)hWndOwner); ``` or (64-bit compatible) ``` SetWindowLongPtr(hWndPopup, GWLP_HWNDPARENT, (LONG_PTR)hWndOwner); ``` Note that MSDN has the following to say about [SetWindowLong[Ptr]](http://msdn.microsoft.com/en-us/library/ms644898(VS.85).aspx): > > Do not call **SetWindowLongPtr** with the GWLP\_HWNDPARENT index to change the parent of a child window. Instead, use the [SetParent](http://msdn.microsoft.com/en-us/library/ms633541(VS.85).aspx) function. > > > This is somewhat misleading, as it seems to imply that the last two snippets above are wrong. This isn't so. Calling `SetParent` will turn the intended popup into a *child* of the parent window (setting its `WS_CHILD` bit), rather than making it an owned window. The code above is the correct way to make an existing popup an owned window.
51,165
<p>I have a list of objects I wish to sort based on a field <code>attr</code> of type string. I tried using <code>-</code></p> <pre><code>list.sort(function (a, b) { return a.attr - b.attr }) </code></pre> <p>but found that <code>-</code> doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?</p>
[ { "answer_id": 51169, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 11, "selected": true, "text": "<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare\" rel=\"noreferrer\"><code>String.prototype.localeCompare</code></a> a per your example:</p>\n\n<pre><code>list.sort(function (a, b) {\n return ('' + a.attr).localeCompare(b.attr);\n})\n</code></pre>\n\n<p>We force a.attr to be a string to avoid exceptions. <code>localeCompare</code> has been supported <a href=\"https://learn.microsoft.com/en-us/scripting/javascript/reference/localecompare-method-string-javascript\" rel=\"noreferrer\">since Internet Explorer 6</a> and Firefox 1. You may also see the following code used that doesn't respect a locale:</p>\n\n<pre><code>if (item1.attr &lt; item2.attr)\n return -1;\nif ( item1.attr &gt; item2.attr)\n return 1;\nreturn 0;\n</code></pre>\n" }, { "answer_id": 51170, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 4, "selected": false, "text": "<p>You should use > or &lt; and == here. So the solution would be:</p>\n\n<pre><code>list.sort(function(item1, item2) {\n var val1 = item1.attr,\n val2 = item2.attr;\n if (val1 == val2) return 0;\n if (val1 &gt; val2) return 1;\n if (val1 &lt; val2) return -1;\n});\n</code></pre>\n" }, { "answer_id": 14757938, "author": "Manav", "author_id": 141220, "author_profile": "https://Stackoverflow.com/users/141220", "pm_score": 3, "selected": false, "text": "<p>I had been bothered about this for long, so I finally researched this and give you this long winded reason for why things are the way they are.</p>\n\n<p>From the <a href=\"http://ecma262-5.com/ELS5_HTML.htm\" rel=\"noreferrer\">spec</a>:</p>\n\n<pre><code>Section 11.9.4 The Strict Equals Operator ( === )\n\nThe production EqualityExpression : EqualityExpression === RelationalExpression\nis evaluated as follows: \n- Let lref be the result of evaluating EqualityExpression.\n- Let lval be GetValue(lref).\n- Let rref be the result of evaluating RelationalExpression.\n- Let rval be GetValue(rref).\n- Return the result of performing the strict equality comparison \n rval === lval. (See 11.9.6)\n</code></pre>\n\n<p>So now we go to 11.9.6</p>\n\n<pre><code>11.9.6 The Strict Equality Comparison Algorithm\n\nThe comparison x === y, where x and y are values, produces true or false. \nSuch a comparison is performed as follows: \n- If Type(x) is different from Type(y), return false.\n- If Type(x) is Undefined, return true.\n- If Type(x) is Null, return true.\n- If Type(x) is Number, then\n...\n- If Type(x) is String, then return true if x and y are exactly the \n same sequence of characters (same length and same characters in \n corresponding positions); otherwise, return false.\n</code></pre>\n\n<p>That's it. <strong>The triple equals operator applied to strings returns true iff the arguments are exactly the same strings (same length and same characters in corresponding positions).</strong></p>\n\n<p>So <code>===</code> will work in the cases when we're trying to compare strings which might have arrived from different sources, but which we know will eventually have the same values - a common enough scenario for inline strings in our code. For example, if we have a variable named <code>connection_state</code>, and we wish to know which one of the following states <code>['connecting', 'connected', 'disconnecting', 'disconnected']</code> is it in right now, we can directly use the <code>===</code>. </p>\n\n<p>But there's more. Just above 11.9.4, there is a short note:</p>\n\n<pre><code>NOTE 4 \n Comparison of Strings uses a simple equality test on sequences of code \n unit values. There is no attempt to use the more complex, semantically oriented\n definitions of character or string equality and collating order defined in the \n Unicode specification. Therefore Strings values that are canonically equal\n according to the Unicode standard could test as unequal. In effect this \n algorithm assumes that both Strings are already in normalized form.\n</code></pre>\n\n<p>Hmm. What now? Externally obtained strings can, and most likely will, be weird unicodey, and our gentle <code>===</code> won't do them justice. In comes <code>localeCompare</code> to the rescue:</p>\n\n<pre><code>15.5.4.9 String.prototype.localeCompare (that)\n ...\n The actual return values are implementation-defined to permit implementers \n to encode additional information in the value, but the function is required \n to define a total ordering on all Strings and to return 0 when comparing\n Strings that are considered canonically equivalent by the Unicode standard. \n</code></pre>\n\n<p>We can go home now.</p>\n\n<p><strong>tl;dr;</strong></p>\n\n<p>To compare strings in javascript, use <code>localeCompare</code>; if you know that the strings have no non-ASCII components because they are, for example, internal program constants, then <code>===</code> also works.</p>\n" }, { "answer_id": 19573507, "author": "eggmatters", "author_id": 1010444, "author_profile": "https://Stackoverflow.com/users/1010444", "pm_score": 0, "selected": false, "text": "<p>In your operation in your initial question, you are performing the following operation:</p>\n\n<pre><code>item1.attr - item2.attr\n</code></pre>\n\n<p>So, assuming those are numbers (i.e. item1.attr = \"1\", item2.attr = \"2\") You still may use the \"===\" operator (or other strict evaluators) provided that you ensure type. The following should work:</p>\n\n<pre><code>return parseInt(item1.attr) - parseInt(item2.attr);\n</code></pre>\n\n<p>If they are alphaNumeric, then do use localCompare().</p>\n" }, { "answer_id": 26295229, "author": "Adrien Be", "author_id": 759452, "author_profile": "https://Stackoverflow.com/users/759452", "pm_score": 8, "selected": false, "text": "<h2>An updated answer (October 2014)</h2>\n\n<p>I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.</p>\n\n<h3>Long story short</h3>\n\n<p><code>localeCompare()</code> character support is badass, just use it.\nAs pointed out by <code>Shog9</code>, the answer to your question is:</p>\n\n<pre><code>return item1.attr.localeCompare(item2.attr);\n</code></pre>\n\n<h3>Bugs found in all the custom javascript \"natural string sort order\" implementations</h3>\n\n<p>There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called \"natural string sort order\"</p>\n\n<p>When \"playing\" with these implementations, I always noticed some strange \"natural sorting order\" choice, or rather mistakes (or omissions in the best cases).</p>\n\n<p>Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.</p>\n\n<p>You will then find them appearing mixed up in different places, typically that could be:</p>\n\n<ul>\n<li>some will be between the uppercase 'Z' and the lowercase 'a' </li>\n<li>some will be between the '9' and the uppercase 'A'</li>\n<li>some will be after lowercase 'z'</li>\n</ul>\n\n<p>When one would have expected special characters to all be \"grouped\" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase &amp; uppercase being \"together\" one after another), or all after letters.</p>\n\n<p>My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).</p>\n\n<p>Research on the custom implementations:</p>\n\n<ul>\n<li><code>Natural Compare Lite</code> <a href=\"https://github.com/litejs/natural-compare-lite\" rel=\"noreferrer\">https://github.com/litejs/natural-compare-lite</a> : Fails at sorting consistently <a href=\"https://github.com/litejs/natural-compare-lite/issues/1\" rel=\"noreferrer\">https://github.com/litejs/natural-compare-lite/issues/1</a> and <a href=\"http://jsbin.com/bevututodavi/1/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/bevututodavi/1/edit?js,console</a> , basic latin characters sorting <a href=\"http://jsbin.com/bevututodavi/5/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/bevututodavi/5/edit?js,console</a> </li>\n<li><code>Natural Sort</code> <a href=\"https://github.com/javve/natural-sort\" rel=\"noreferrer\">https://github.com/javve/natural-sort</a> : Fails at sorting consistently, see issue <a href=\"https://github.com/javve/natural-sort/issues/7\" rel=\"noreferrer\">https://github.com/javve/natural-sort/issues/7</a> and see basic latin characters sorting <a href=\"http://jsbin.com/cipimosedoqe/3/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/cipimosedoqe/3/edit?js,console</a> </li>\n<li><code>Javascript Natural Sort</code> <a href=\"https://github.com/overset/javascript-natural-sort\" rel=\"noreferrer\">https://github.com/overset/javascript-natural-sort</a> : seems rather neglected since February 2012, Fails at sorting consistently, see issue <a href=\"https://github.com/overset/javascript-natural-sort/issues/16\" rel=\"noreferrer\">https://github.com/overset/javascript-natural-sort/issues/16</a></li>\n<li><code>Alphanum</code> <a href=\"http://www.davekoelle.com/files/alphanum.js\" rel=\"noreferrer\">http://www.davekoelle.com/files/alphanum.js</a> , Fails at sorting consistently, see <a href=\"http://jsbin.com/tuminoxifuyo/1/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/tuminoxifuyo/1/edit?js,console</a></li>\n</ul>\n\n<h3>Browsers' native \"natural string sort order\" implementations via <code>localeCompare()</code></h3>\n\n<p><code>localeCompare()</code> oldest implementation (without the locales and options arguments) is supported by IE6+, see <a href=\"http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx</a> (scroll down to localeCompare() method).\nThe built-in <code>localeCompare()</code> method does a much better job at sorting, even international &amp; special characters.\nThe only problem using the <code>localeCompare()</code> method is that <a href=\"https://code.google.com/p/v8/issues/detail?id=459\" rel=\"noreferrer\">\"the locale and sort order used are entirely implementation dependent\". In other words, when using localeCompare such as stringOne.localeCompare(stringTwo): Firefox, Safari, Chrome &amp; IE have a different sort order for Strings.</a></p>\n\n<p>Research on the browser-native implementations:</p>\n\n<ul>\n<li><a href=\"http://jsbin.com/beboroyifomu/1/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/beboroyifomu/1/edit?js,console</a> - basic latin characters comparison with localeCompare()\n<a href=\"http://jsbin.com/viyucavudela/2/\" rel=\"noreferrer\">http://jsbin.com/viyucavudela/2/</a> - basic latin characters comparison with localeCompare() for testing on IE8</li>\n<li><a href=\"http://jsbin.com/beboroyifomu/2/edit?js,console\" rel=\"noreferrer\">http://jsbin.com/beboroyifomu/2/edit?js,console</a> - basic latin characters in string comparison : consistency check in string vs when a character is alone</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare</a> - IE11+ supports the new locales &amp; options arguments</li>\n</ul>\n\n<h3>Difficulty of \"string natural sorting order\"</h3>\n\n<p>Implementing a solid algorithm (meaning: consistent but also covering a wide range of characters) is a very tough task. UTF8 contains <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"noreferrer\">more than 2000 characters</a> &amp; <a href=\"http://www.unicode.org/standard/supported.html\" rel=\"noreferrer\">covers more than 120 scripts (languages)</a>. \nFinally, there are some specification for this tasks, it is called the \"Unicode Collation Algorithm\", which can be found at <a href=\"http://www.unicode.org/reports/tr10/\" rel=\"noreferrer\">http://www.unicode.org/reports/tr10/</a> . You can find more information about this on this question I posted <a href=\"https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order\">https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order</a></p>\n\n<h2>Final conclusion</h2>\n\n<p>So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters &amp; scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid &amp; meaningful sort orders.</p>\n\n<p>So as pointed out by <code>Shog9</code>, the answer to your question is:</p>\n\n<pre><code>return item1.attr.localeCompare(item2.attr);\n</code></pre>\n\n<h3>Further reading:</h3>\n\n<ul>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order\">https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order</a></li>\n<li><a href=\"https://stackoverflow.com/questions/51165/how-do-you-do-string-comparison-in-javascript\">How do you do string comparison in JavaScript?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/2802341/natural-sort-of-text-and-numbers-javascript\">Javascript : natural sort of alphanumerical strings</a></li>\n<li><a href=\"https://stackoverflow.com/questions/4373018/sort-array-of-numeric-alphabetical-elements-natural-sort/\">Sort Array of numeric &amp; alphabetical elements (Natural Sort)</a></li>\n<li><a href=\"https://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array\">Sort mixed alpha/numeric array</a></li>\n<li><a href=\"https://web.archive.org/web/20130929122019/http://my.opera.com/GreyWyvern/blog/show.dml/1671288\" rel=\"noreferrer\">https://web.archive.org/web/20130929122019/http://my.opera.com/GreyWyvern/blog/show.dml/1671288</a></li>\n<li><a href=\"https://web.archive.org/web/20131005224909/http://www.davekoelle.com/alphanum.html\" rel=\"noreferrer\">https://web.archive.org/web/20131005224909/http://www.davekoelle.com/alphanum.html</a></li>\n<li><a href=\"http://snipplr.com/view/36012/javascript-natural-sort/\" rel=\"noreferrer\">http://snipplr.com/view/36012/javascript-natural-sort/</a></li>\n<li><a href=\"http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/\" rel=\"noreferrer\">http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/</a></li>\n</ul>\n\n<p>Thanks to Shog9's nice answer, which put me in the \"right\" direction I believe</p>\n" }, { "answer_id": 39281302, "author": "Petr Varyagin", "author_id": 5149578, "author_profile": "https://Stackoverflow.com/users/5149578", "pm_score": 1, "selected": false, "text": "<pre><code>list.sort(function(item1, item2){\n return +(item1.attr &gt; item2.attr) || +(item1.attr === item2.attr) - 1;\n}) \n</code></pre>\n\n<p>How they work samples:</p>\n\n<pre><code>+('aaa'&gt;'bbb')||+('aaa'==='bbb')-1\n+(false)||+(false)-1\n0||0-1\n-1\n\n+('bbb'&gt;'aaa')||+('bbb'==='aaa')-1\n+(true)||+(false)-1\n1||0-1\n1\n\n+('aaa'&gt;'aaa')||+('aaa'==='aaa')-1\n+(false)||+(true)-1\n0||1-1\n0\n</code></pre>\n" }, { "answer_id": 40355107, "author": "mpyw", "author_id": 1846562, "author_profile": "https://Stackoverflow.com/users/1846562", "pm_score": 6, "selected": false, "text": "<h1>Answer (in Modern ECMAScript)</h1>\n\n<pre><code>list.sort((a, b) =&gt; (a.attr &gt; b.attr) - (a.attr &lt; b.attr))\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>list.sort((a, b) =&gt; +(a.attr &gt; b.attr) || -(a.attr &lt; b.attr))\n</code></pre>\n\n<h1>Description</h1>\n\n<p>Casting a boolean value to a number yields the following:</p>\n\n<ul>\n<li><code>true</code> -> <code>1</code></li>\n<li><code>false</code> -> <code>0</code></li>\n</ul>\n\n<p>Consider three possible patterns:</p>\n\n<ul>\n<li>x is larger than y: <code>(x &gt; y) - (y &lt; x)</code> -> <code>1 - 0</code> -> <code>1</code></li>\n<li>x is equal to y: <code>(x &gt; y) - (y &lt; x)</code> -> <code>0 - 0</code> -> <code>0</code></li>\n<li>x is smaller than y: <code>(x &gt; y) - (y &lt; x)</code> -> <code>0 - 1</code> -> <code>-1</code></li>\n</ul>\n\n<p>(Alternative)</p>\n\n<ul>\n<li>x is larger than y: <code>+(x &gt; y) || -(x &lt; y)</code> -> <code>1 || 0</code> -> <code>1</code></li>\n<li>x is equal to y: <code>+(x &gt; y) || -(x &lt; y)</code> -> <code>0 || 0</code> -> <code>0</code></li>\n<li>x is smaller than y: <code>+(x &gt; y) || -(x &lt; y)</code> -> <code>0 || -1</code> -> <code>-1</code></li>\n</ul>\n\n<p>So these logics are equivalent to typical sort comparator functions.</p>\n\n<pre><code>if (x == y) {\n return 0;\n}\nreturn x &gt; y ? 1 : -1;\n</code></pre>\n" }, { "answer_id": 49989678, "author": "Julio Munoz", "author_id": 4122286, "author_profile": "https://Stackoverflow.com/users/4122286", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;!doctype html&gt;\n&lt;html&gt;\n&lt;body&gt;\n&lt;p id = \"myString\"&gt;zyxtspqnmdba&lt;/p&gt;\n&lt;p id = \"orderedString\"&gt;&lt;/p&gt;\n&lt;script&gt;\nvar myString = document.getElementById(\"myString\").innerHTML;\norderString(myString);\nfunction orderString(str) {\n var i = 0;\n var myArray = str.split(\"\");\n while (i &lt; str.length){\n var j = i + 1;\n while (j &lt; str.length) {\n if (myArray[j] &lt; myArray[i]){\n var temp = myArray[i];\n myArray[i] = myArray[j];\n myArray[j] = temp;\n }\n j++;\n }\n i++;\n }\n var newString = myArray.join(\"\");\n document.getElementById(\"orderedString\").innerHTML = newString;\n}\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 55153827, "author": "geckos", "author_id": 652528, "author_profile": "https://Stackoverflow.com/users/652528", "pm_score": 4, "selected": false, "text": "<p>Nested ternary arrow function</p>\n\n<pre><code>(a,b) =&gt; (a &lt; b ? -1 : a &gt; b ? 1 : 0)\n</code></pre>\n" }, { "answer_id": 55590696, "author": "Abdul", "author_id": 9359891, "author_profile": "https://Stackoverflow.com/users/9359891", "pm_score": -1, "selected": false, "text": "<pre><code>var str = ['v','a','da','c','k','l']\nvar b = str.join('').split('').sort().reverse().join('')\nconsole.log(b)\n</code></pre>\n" }, { "answer_id": 58049712, "author": "Alejadro Xalabarder", "author_id": 1191101, "author_profile": "https://Stackoverflow.com/users/1191101", "pm_score": 5, "selected": false, "text": "<p>since strings can be compared directly in javascript, this will do the job</p>\n\n<pre><code>list.sort(function (a, b) {\n return a.attr &gt; b.attr ? 1: -1;\n})\n</code></pre>\n\n<p>the subtraction in a sort function is used only when non alphabetical (numerical) sort is desired and of course it does not work with strings</p>\n" }, { "answer_id": 64611883, "author": "tash", "author_id": 11932012, "author_profile": "https://Stackoverflow.com/users/11932012", "pm_score": 3, "selected": false, "text": "<p>An explanation of why the approach in the question doesn't work:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let products = [\n { name: &quot;laptop&quot;, price: 800 },\n { name: &quot;phone&quot;, price:200},\n { name: &quot;tv&quot;, price: 1200}\n];\nproducts.sort( (a, b) =&gt; {\n {let value= a.name - b.name; console.log(value); return value}\n});\n\n&gt; 2 NaN\n</code></pre>\n<p>Subtraction between strings returns NaN.</p>\n<p>Echoing @Alejadro's answer, the right approach is--</p>\n<p><code>products.sort( (a,b) =&gt; a.name &gt; b.name ? 1 : -1 )</code></p>\n" }, { "answer_id": 65979128, "author": "TrickOrTreat", "author_id": 11502061, "author_profile": "https://Stackoverflow.com/users/11502061", "pm_score": 2, "selected": false, "text": "<p>Use sort() straight forward without any <code>-</code> or <code>&lt;</code></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>const areas = ['hill', 'beach', 'desert', 'mountain']\nconsole.log(areas.sort())\n\n// To print in descending way\nconsole.log(areas.sort().reverse())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68123055, "author": "deathfry", "author_id": 13029968, "author_profile": "https://Stackoverflow.com/users/13029968", "pm_score": 2, "selected": false, "text": "<p>There should be ascending and descending orders functions</p>\n<pre><code>if (order === 'asc') {\n return a.localeCompare(b);\n}\nreturn b.localeCompare(a);\n</code></pre>\n" }, { "answer_id": 70430101, "author": "Felix Orinda", "author_id": 13779529, "author_profile": "https://Stackoverflow.com/users/13779529", "pm_score": 3, "selected": false, "text": "<p>In javascript, we use the <code>.localCompare</code> method to sort strings</p>\n<p>For Typescript</p>\n<pre><code>const data = [&quot;jane&quot;, &quot;mike&quot;, &quot;salome&quot;, &quot;ababus&quot;, &quot;buisa&quot;, &quot;dennis&quot;];\n\nconst sort = (arr: string[], mode?: 'desc' | 'asc') =&gt; \n !mode || mode === &quot;asc&quot;\n ? arr.sort((a, b) =&gt; a.localeCompare(b))\n : arr.sort((a, b) =&gt; b.localeCompare(a));\n\n\nconsole.log(sort(data, 'desc'));// [ 'salome', 'mike', 'jane', 'dennis', 'buisa', 'ababus' ]\nconsole.log(sort(data, 'asc')); // [ 'ababus', 'buisa', 'dennis', 'jane', 'mike', 'salome' ]\n\n\n</code></pre>\n<p>For JS</p>\n<pre><code>const data = [&quot;jane&quot;, &quot;mike&quot;, &quot;salome&quot;, &quot;ababus&quot;, &quot;buisa&quot;, &quot;dennis&quot;];\n\n/**\n * @param {string[]} arr\n * @param {&quot;asc&quot;|&quot;desc&quot;} mode\n */\nconst sort = (arr, mode = &quot;asc&quot;) =&gt;\n !mode || mode === &quot;asc&quot;\n ? arr.sort((a, b) =&gt; a.localeCompare(b))\n : arr.sort((a, b) =&gt; b.localeCompare(a));\n\nconsole.log(sort(data, 'desc'));// [ 'salome', 'mike', 'jane', 'dennis', 'buisa', 'ababus' ]\nconsole.log(sort(data, 'asc')); // [ 'ababus', 'buisa', 'dennis', 'jane', 'mike', 'salome' ]\n</code></pre>\n" }, { "answer_id": 70890849, "author": "xmedeko", "author_id": 254109, "author_profile": "https://Stackoverflow.com/users/254109", "pm_score": 2, "selected": false, "text": "<p>If you want to control locales (or case or accent), then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator\" rel=\"nofollow noreferrer\"><code>Intl.collator</code></a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const collator = new Intl.Collator();\nlist.sort((a, b) =&gt; collator.compare(a.attr, b.attr));\n</code></pre>\n<p>You can construct collator like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>new Intl.Collator(&quot;en&quot;);\nnew Intl.Collator(&quot;en&quot;, {sensitivity: &quot;case&quot;});\n...\n</code></pre>\n<p>see the above link for doc.</p>\n<p>Note: unlike some other solutions, it handles <code>null, undefined</code> the JS way, i.e. moves them to the end.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
I have a list of objects I wish to sort based on a field `attr` of type string. I tried using `-` ``` list.sort(function (a, b) { return a.attr - b.attr }) ``` but found that `-` doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?
Use [`String.prototype.localeCompare`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare) a per your example: ``` list.sort(function (a, b) { return ('' + a.attr).localeCompare(b.attr); }) ``` We force a.attr to be a string to avoid exceptions. `localeCompare` has been supported [since Internet Explorer 6](https://learn.microsoft.com/en-us/scripting/javascript/reference/localecompare-method-string-javascript) and Firefox 1. You may also see the following code used that doesn't respect a locale: ``` if (item1.attr < item2.attr) return -1; if ( item1.attr > item2.attr) return 1; return 0; ```
51,176
<p>I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO's. So the data layer might project DTO's like the following:</p> <pre><code>(from c in dataContext.Customers where c.Active == true select new DTO.Customer { CustomerID = c.CustomerID, Name = c.CustomerName, ... }).ToList() </code></pre> <p>Although building the DTO objects adds work, this feels like a better approach to a tight binding between Business &amp; Data layers and means I can test the Business layer without a database being present.</p> <p>My question is, is this good practice?, Is there a way of generating the DTO's (maybe via SQLMetal), and what other problems might I strike as the project progresses.</p>
[ { "answer_id": 51186, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>In my opinion in most cases DTO objects are not needed when dealing with LINQ. Generated LINQ classes can be easily tested. LINQ gives you ability to query your data from different sources using identical queries. It gives you ability to test your queries against lists of objects instead of real db.</p>\n" }, { "answer_id": 51196, "author": "BirgerH", "author_id": 5164, "author_profile": "https://Stackoverflow.com/users/5164", "pm_score": 4, "selected": true, "text": "<p>I don't know if it's best practice but I have written similar code in the not so recent past because I too felt that I could improve the separation of concerns by using my own classes instead of the LINQ-designer-generated ones within my application.</p>\n\n<p>You may want to consider just returning an IQueryable&lt;Customer&gt; instead of an IList&lt;Customer&gt; from your data-access method. Since IQueryable&lt;T&gt; inherits from IEnumerable&lt;T&gt; the rest of your app should be able to deal with it quite well. You can also convert it to a List when you really need to.</p>\n\n<p>The advantage of this is that you can dynamically modify your query quite easily and minimze the amount of data returned from SQL Server.</p>\n\n<p>E.g. if your method signature is\nIQueryable&lt;Customer&gt; GetCustomers() you could get a single customer by calling GetCustomers().Where(c => c.CustomerID == 101).Single();</p>\n\n<p>In this example only one record would be returned from the database whereas I imagine currently your code would return either all customers or you'd be required to write separate methods (and thus very repetitive code) to cater for all the different things you may want to filter by.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5136/" ]
I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO's. So the data layer might project DTO's like the following: ``` (from c in dataContext.Customers where c.Active == true select new DTO.Customer { CustomerID = c.CustomerID, Name = c.CustomerName, ... }).ToList() ``` Although building the DTO objects adds work, this feels like a better approach to a tight binding between Business & Data layers and means I can test the Business layer without a database being present. My question is, is this good practice?, Is there a way of generating the DTO's (maybe via SQLMetal), and what other problems might I strike as the project progresses.
I don't know if it's best practice but I have written similar code in the not so recent past because I too felt that I could improve the separation of concerns by using my own classes instead of the LINQ-designer-generated ones within my application. You may want to consider just returning an IQueryable<Customer> instead of an IList<Customer> from your data-access method. Since IQueryable<T> inherits from IEnumerable<T> the rest of your app should be able to deal with it quite well. You can also convert it to a List when you really need to. The advantage of this is that you can dynamically modify your query quite easily and minimze the amount of data returned from SQL Server. E.g. if your method signature is IQueryable<Customer> GetCustomers() you could get a single customer by calling GetCustomers().Where(c => c.CustomerID == 101).Single(); In this example only one record would be returned from the database whereas I imagine currently your code would return either all customers or you'd be required to write separate methods (and thus very repetitive code) to cater for all the different things you may want to filter by.
51,180
<p>I'm tearing my hair out with this one. If I start a block comment <code>/*</code> in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk <code>*</code>. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?</p>
[ { "answer_id": 51194, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 6, "selected": true, "text": "<p><strong>Update: this setting was changed in VS 2015 update 2. See <a href=\"https://stackoverflow.com/a/36319097/4294399\">this answer</a>.</strong></p>\n<p><a href=\"http://forums.msdn.microsoft.com/en-US/csharpide/thread/a41e3652-efe2-4f81-ad3e-94994974fcb2/\" rel=\"nofollow noreferrer\">This post</a> addresses your question. The gist of it is:</p>\n<pre><code>Text Editor &gt; C# &gt; Advanced &gt; Generate XML documentation comments for ///\n</code></pre>\n" }, { "answer_id": 8235889, "author": "wozza", "author_id": 295301, "author_profile": "https://Stackoverflow.com/users/295301", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>#if false\n\n whatever you want here\n and here\n\n#endif\n</code></pre>\n" }, { "answer_id": 36319097, "author": "Nick", "author_id": 1931573, "author_profile": "https://Stackoverflow.com/users/1931573", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://www.visualstudio.com/en-us/news/vs2015-update2-vs.aspx\" rel=\"noreferrer\">Visual Studio 2015 Update 2</a> has (finally) addressed this problem!</p>\n\n<p>A new option as been added to <code>Tools &gt; Options &gt; Text Editor &gt; C# &gt; Advanced</code> named <code>Insert * at the start of new lines when writing /* */ comments</code>.</p>\n\n<p>Disabling this option prevents the editor from automatically prefixing block comments with asterisks. It only took 7.5 years and 4 major releases :)</p>\n\n<p><a href=\"https://i.stack.imgur.com/iNcjt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iNcjt.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4458/" ]
I'm tearing my hair out with this one. If I start a block comment `/*` in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk `*`. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?
**Update: this setting was changed in VS 2015 update 2. See [this answer](https://stackoverflow.com/a/36319097/4294399).** [This post](http://forums.msdn.microsoft.com/en-US/csharpide/thread/a41e3652-efe2-4f81-ad3e-94994974fcb2/) addresses your question. The gist of it is: ``` Text Editor > C# > Advanced > Generate XML documentation comments for /// ```
51,185
<p>Does javascript use immutable or mutable strings? Do I need a "string builder"?</p>
[ { "answer_id": 51188, "author": "JC Grubbs", "author_id": 4541, "author_profile": "https://Stackoverflow.com/users/4541", "pm_score": 0, "selected": false, "text": "<p>JavaScript strings are indeed immutable.</p>\n" }, { "answer_id": 51191, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 0, "selected": false, "text": "<p>Strings in Javascript are immutable</p>\n" }, { "answer_id": 51193, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 6, "selected": false, "text": "<p>from the <a href=\"http://oreilly.com/catalog/9780596000486/\" rel=\"nofollow noreferrer\">rhino book</a>:</p>\n\n<blockquote>\n <p>In JavaScript, strings are immutable objects, which means that the\n characters within them may not be changed and that any operations on\n strings actually create new strings. Strings are assigned by\n reference, not by value. In general, when an object is assigned by\n reference, a change made to the object through one reference will be\n visible through all other references to the object. Because strings\n cannot be changed, however, you can have multiple references to a\n string object and not worry that the string value will change without\n your knowing it</p>\n</blockquote>\n" }, { "answer_id": 51199, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": false, "text": "<p><strong>Performance tip:</strong></p>\n\n<p>If you have to concatenate large strings, put the string parts into an array and use the <code>Array.Join()</code> method to get the overall string. This can be many times faster for concatenating a large number of strings. </p>\n\n<p>There is no <code>StringBuilder</code> in JavaScript.</p>\n" }, { "answer_id": 51215, "author": "BirgerH", "author_id": 5164, "author_profile": "https://Stackoverflow.com/users/5164", "pm_score": 1, "selected": false, "text": "<p>Regarding your question (in your comment to Ash's response) about the StringBuilder in ASP.NET Ajax the experts seem to disagree on this one.</p>\n\n<p>Christian Wenz says in his book <em>Programming ASP.NET AJAX</em> (O'Reilly) that \"this approach does not have any measurable effect on memory (in fact, the implementation seems to be a tick slower than the standard approach).\"</p>\n\n<p>On the other hand Gallo et al say in their book <em>ASP.NET AJAX in Action</em> (Manning) that \"When the number of strings to concatenate is larger, the string builder becomes an essential object to avoid huge performance drops.\"</p>\n\n<p>I guess you'd need to do your own benchmarking and results might differ between browsers, too. However, even if it doesn't improve performance it might still be considered \"useful\" for programmers who are used to coding with StringBuilders in languages like C# or Java.</p>\n" }, { "answer_id": 4717855, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 9, "selected": true, "text": "<p>They are immutable. You cannot change a character within a string with something like <code>var myString = &quot;abbdef&quot;; myString[2] = 'c'</code>. The string manipulation methods such as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim\" rel=\"noreferrer\"><code>trim</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"noreferrer\"><code>slice</code></a> return new strings.</p>\n<p>In the same way, if you have two references to the same string, modifying one doesn't affect the other</p>\n<pre><code>let a = b = &quot;hello&quot;;\na = a + &quot; world&quot;;\n// b is not affected\n</code></pre>\n<p>However, I've always heard what Ash mentioned in his answer (that using Array.join is faster for concatenation) so I wanted to test out the different methods of concatenating strings and abstracting the fastest way into a StringBuilder. I wrote some tests to see if this is true (it isn't!).</p>\n<p>This was what I believed would be the fastest way, though I kept thinking that adding a method call may make it slower...</p>\n<pre><code>function StringBuilder() {\n this._array = [];\n this._index = 0;\n}\n\nStringBuilder.prototype.append = function (str) {\n this._array[this._index] = str;\n this._index++;\n}\n\nStringBuilder.prototype.toString = function () {\n return this._array.join('');\n}\n</code></pre>\n<p>Here are performance speed tests. All three of them create a gigantic string made up of concatenating <code>&quot;Hello diggity dog&quot;</code> one hundred thousand times into an empty string.</p>\n<p>I've created three types of tests</p>\n<ul>\n<li>Using <code>Array.push</code> and <code>Array.join</code></li>\n<li>Using Array indexing to avoid <code>Array.push</code>, then using <code>Array.join</code></li>\n<li>Straight string concatenation</li>\n</ul>\n<p>Then I created the same three tests by abstracting them into <code>StringBuilderConcat</code>, <code>StringBuilderArrayPush</code> and <code>StringBuilderArrayIndex</code> <a href=\"http://jsperf.com/string-concat-without-sringbuilder/5\" rel=\"noreferrer\">http://jsperf.com/string-concat-without-sringbuilder/5</a> Please go there and run tests so we can get a nice sample. Note that I fixed a small bug, so the data for the tests got wiped, I will update the table once there's enough performance data. Go to <a href=\"http://jsperf.com/string-concat-without-sringbuilder/5\" rel=\"noreferrer\">http://jsperf.com/string-concat-without-sringbuilder/5</a> for the old data table.</p>\n<p>Here are some numbers (Latest update in Ma5rch 2018), if you don't want to follow the link. The number on each test is in 1000 operations/second (<strong>higher is better</strong>)</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Browser</th>\n<th>Index</th>\n<th>Push</th>\n<th>Concat</th>\n<th>SBIndex</th>\n<th>SBPush</th>\n<th>SBConcat</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Chrome 71.0.3578</td>\n<td>988</td>\n<td>1006</td>\n<td>2902</td>\n<td>963</td>\n<td>1008</td>\n<td>2902</td>\n</tr>\n<tr>\n<td>Firefox 65</td>\n<td>1979</td>\n<td>1902</td>\n<td>2197</td>\n<td>1917</td>\n<td>1873</td>\n<td>1953</td>\n</tr>\n<tr>\n<td>Edge</td>\n<td>593</td>\n<td>373</td>\n<td>952</td>\n<td>361</td>\n<td>415</td>\n<td>444</td>\n</tr>\n<tr>\n<td>Exploder 11</td>\n<td>655</td>\n<td>532</td>\n<td>761</td>\n<td>537</td>\n<td>567</td>\n<td>387</td>\n</tr>\n<tr>\n<td>Opera 58.0.3135</td>\n<td>1135</td>\n<td>1200</td>\n<td>4357</td>\n<td>1137</td>\n<td>1188</td>\n<td>4294</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><strong>Findings</strong></p>\n<ul>\n<li><p>Nowadays, all evergreen browsers handle string concatenation well. <code>Array.join</code> only helps IE 11</p>\n</li>\n<li><p>Overall, Opera is fastest, 4 times as fast as Array.join</p>\n</li>\n<li><p>Firefox is second and <code>Array.join</code> is only slightly slower in FF but considerably slower (3x) in Chrome.</p>\n</li>\n<li><p>Chrome is third but string concat is 3 times faster than Array.join</p>\n</li>\n<li><p>Creating a StringBuilder seems to not affect perfomance too much.</p>\n</li>\n</ul>\n<p>Hope somebody else finds this useful</p>\n<p><strong>Different Test Case</strong></p>\n<p>Since @RoyTinker thought that my test was flawed, I created a new case that doesn't create a big string by concatenating the same string, it uses a different character for each iteration. String concatenation still seemed faster or just as fast. Let's get those tests running.</p>\n<p>I suggest everybody should keep thinking of other ways to test this, and feel free to add new links to different test cases below.</p>\n<p><a href=\"http://jsperf.com/string-concat-without-sringbuilder/7\" rel=\"noreferrer\">http://jsperf.com/string-concat-without-sringbuilder/7</a></p>\n" }, { "answer_id": 32074982, "author": "GibboK", "author_id": 379008, "author_profile": "https://Stackoverflow.com/users/379008", "pm_score": 2, "selected": false, "text": "<p><strong>Strings are immutable</strong> – they cannot change, we can only ever make new strings.</p>\n\n<p>Example:</p>\n\n<pre><code>var str= \"Immutable value\"; // it is immutable\n\nvar other= statement.slice(2, 10); // new string\n</code></pre>\n" }, { "answer_id": 33127871, "author": "zhanziyang", "author_id": 4315171, "author_profile": "https://Stackoverflow.com/users/4315171", "pm_score": 2, "selected": false, "text": "<p>The string type value is immutable, <strong>but</strong> the String object, which is created by using the String() constructor, is mutable, because it is an object and you can add new properties to it.</p>\n\n<pre><code>&gt; var str = new String(\"test\")\nundefined\n&gt; str\n[String: 'test']\n&gt; str.newProp = \"some value\"\n'some value'\n&gt; str\n{ [String: 'test'] newProp: 'some value' }\n</code></pre>\n\n<p>Meanwhile, although you can add new properties, you can't change the already existing properties</p>\n\n<p><a href=\"http://i.stack.imgur.com/m9y8P.png\" rel=\"nofollow\">A screenshot of a test in Chrome console</a></p>\n\n<p>In conclusion, \n1. all string type value (primitive type) is immutable. \n2. The String object is mutable, but the string type value (primitive type) it contains is immutable.</p>\n" }, { "answer_id": 51652749, "author": "revelt", "author_id": 3943954, "author_profile": "https://Stackoverflow.com/users/3943954", "pm_score": 1, "selected": false, "text": "<p>It's a late post, but I didn't find a good book quote among the answers.</p>\n\n<p>Here's a definite except from a reliable book:</p>\n\n<blockquote>\n <p>Strings are immutable in ECMAScript, meaning that once they are created, their values cannot change. To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value...\n <em>—Professional JavaScript for Web Developers, 3rd Ed., p.43</em></p>\n</blockquote>\n\n<p>Now, the answer which quotes Rhino book's excerpt is right about string immutability but wrong saying \"Strings are assigned by reference, not by value.\" (probably they originally meant to put the words an opposite way).</p>\n\n<p>The \"reference/value\" misconception is clarified in the \"Professional JavaScript\", chapter named \"Primitive and Reference values\":</p>\n\n<blockquote>\n <p>The five primitive types...[are]: Undefined, Null, Boolean, Number, and String. These variables are said to be accessed by value, because you are manipulating the actual value stored in the variable.\n <em>—Professional JavaScript for Web Developers, 3rd Ed., p.85</em></p>\n</blockquote>\n\n<p>that's opposed to <em>objects</em>:</p>\n\n<blockquote>\n <p>When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference.<em>—Professional JavaScript for Web Developers, 3rd Ed., p.85</em></p>\n</blockquote>\n" }, { "answer_id": 52242541, "author": "Katinka Hesselink", "author_id": 8007395, "author_profile": "https://Stackoverflow.com/users/8007395", "pm_score": 5, "selected": false, "text": "<p>Just to clarify for simple minds like mine (from <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Mutable\" rel=\"noreferrer\">MDN</a>):</p>\n<blockquote>\n<p>Immutables are the objects whose state cannot be changed once the object is created.</p>\n<p>String and Numbers are Immutable.</p>\n</blockquote>\n<p>Immutable means that:</p>\n<blockquote>\n<p>You can make a variable name point to a new value, but the previous value is still held in memory. Hence the need for garbage collection.</p>\n<p><code>var immutableString = &quot;Hello&quot;;</code></p>\n<p>// In the above code, a new object with string value is created.</p>\n<p><code>immutableString = immutableString + &quot;World&quot;;</code></p>\n<p>// We are now appending &quot;World&quot; to the existing value.</p>\n</blockquote>\n<p>This looks like we're mutating the string 'immutableString', but we're not. Instead:</p>\n<blockquote>\n<p>On appending the &quot;immutableString&quot; with a string value, following events occur:</p>\n<ol>\n<li>Existing value of &quot;immutableString&quot; is retrieved</li>\n<li>&quot;World&quot; is appended to the existing value of &quot;immutableString&quot;</li>\n<li>The resultant value is then allocated to a new block of memory</li>\n<li>&quot;immutableString&quot; object now points to the newly created memory space</li>\n<li>Previously created memory space is now available for garbage collection.</li>\n</ol>\n</blockquote>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
Does javascript use immutable or mutable strings? Do I need a "string builder"?
They are immutable. You cannot change a character within a string with something like `var myString = "abbdef"; myString[2] = 'c'`. The string manipulation methods such as [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim), [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) return new strings. In the same way, if you have two references to the same string, modifying one doesn't affect the other ``` let a = b = "hello"; a = a + " world"; // b is not affected ``` However, I've always heard what Ash mentioned in his answer (that using Array.join is faster for concatenation) so I wanted to test out the different methods of concatenating strings and abstracting the fastest way into a StringBuilder. I wrote some tests to see if this is true (it isn't!). This was what I believed would be the fastest way, though I kept thinking that adding a method call may make it slower... ``` function StringBuilder() { this._array = []; this._index = 0; } StringBuilder.prototype.append = function (str) { this._array[this._index] = str; this._index++; } StringBuilder.prototype.toString = function () { return this._array.join(''); } ``` Here are performance speed tests. All three of them create a gigantic string made up of concatenating `"Hello diggity dog"` one hundred thousand times into an empty string. I've created three types of tests * Using `Array.push` and `Array.join` * Using Array indexing to avoid `Array.push`, then using `Array.join` * Straight string concatenation Then I created the same three tests by abstracting them into `StringBuilderConcat`, `StringBuilderArrayPush` and `StringBuilderArrayIndex` <http://jsperf.com/string-concat-without-sringbuilder/5> Please go there and run tests so we can get a nice sample. Note that I fixed a small bug, so the data for the tests got wiped, I will update the table once there's enough performance data. Go to <http://jsperf.com/string-concat-without-sringbuilder/5> for the old data table. Here are some numbers (Latest update in Ma5rch 2018), if you don't want to follow the link. The number on each test is in 1000 operations/second (**higher is better**) | Browser | Index | Push | Concat | SBIndex | SBPush | SBConcat | | --- | --- | --- | --- | --- | --- | --- | | Chrome 71.0.3578 | 988 | 1006 | 2902 | 963 | 1008 | 2902 | | Firefox 65 | 1979 | 1902 | 2197 | 1917 | 1873 | 1953 | | Edge | 593 | 373 | 952 | 361 | 415 | 444 | | Exploder 11 | 655 | 532 | 761 | 537 | 567 | 387 | | Opera 58.0.3135 | 1135 | 1200 | 4357 | 1137 | 1188 | 4294 | **Findings** * Nowadays, all evergreen browsers handle string concatenation well. `Array.join` only helps IE 11 * Overall, Opera is fastest, 4 times as fast as Array.join * Firefox is second and `Array.join` is only slightly slower in FF but considerably slower (3x) in Chrome. * Chrome is third but string concat is 3 times faster than Array.join * Creating a StringBuilder seems to not affect perfomance too much. Hope somebody else finds this useful **Different Test Case** Since @RoyTinker thought that my test was flawed, I created a new case that doesn't create a big string by concatenating the same string, it uses a different character for each iteration. String concatenation still seemed faster or just as fast. Let's get those tests running. I suggest everybody should keep thinking of other ways to test this, and feel free to add new links to different test cases below. <http://jsperf.com/string-concat-without-sringbuilder/7>
51,195
<p>I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue.</p> <p>I can get the data "Jim" out of a hash inside an array with this syntax:</p> <pre><code>print $records[$index]{'firstName'} </code></pre> <p>returns "Jim"</p> <p>but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash:</p> <pre><code> %row = $records[$index]; $row{'firstName'}; </code></pre> <p>returns "" (blank)</p> <p>Here is the full sample code showing the problem. Any help is appreciated:</p> <pre><code> my @records = ( {'id' => 1, 'firstName' => 'Jim'}, {'id' => 2, 'firstName' => 'Joe'} ); my @records2 = (); $numberOfRecords = scalar(@records); print "number of records: " . $numberOfRecords . "\n"; for(my $index=0; $index &lt; $numberOfRecords; $index++) { #works print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n"; #does NOT work %row = $records[$index]; print 'but not like this: ' . $row{'firstName'} . "\n"; } </code></pre>
[ { "answer_id": 51205, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 6, "selected": true, "text": "<p>The nested data structure contains a hash <em>reference</em>, not a hash.</p>\n\n<pre><code># Will work (the -&gt; dereferences the reference)\n$row = $records[$index];\nprint \"This will work: \", $row-&gt;{firstName}, \"\\n\";\n\n# This will also work, by promoting the hash reference into a hash\n%row = %{ $records[$index] };\nprint \"This will work: \", $row{firstName}, \"\\n\";\n</code></pre>\n\n<p>If you're ever presented with a deep Perl data structure, you may profit from printing it using <a href=\"http://search.cpan.org/perldoc?Data::Dumper\" rel=\"noreferrer\">Data::Dumper</a> to print it into human-readable (and Perl-parsable) form.</p>\n" }, { "answer_id": 51206, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 1, "selected": false, "text": "<p>what you actually have in your array is a hashref, not a hash. If you don't understand this concept, its probably worth reading the <a href=\"http://perldoc.perl.org/perlref.html\" rel=\"nofollow noreferrer\">perlref</a> documentation.</p>\n\n<p>to get the hash you need to do</p>\n\n<pre><code>my %hash = %{@records[$index]};\n</code></pre>\n\n<p>Eg.</p>\n\n<pre><code>my @records = (\n {'id' =&gt; 1, 'firstName' =&gt; 'Jim'}, \n {'id' =&gt; 2, 'firstName' =&gt; 'Joe'}\n );\n\n my %hash = %{$records[1]};\n\n print $hash{id}.\"\\n\";\n</code></pre>\n\n<p>Although. I'm not sure why you would want to do this, unless its for academic purposes. Otherwise, I'd recommend either fetchall_hashref/fetchall_arrayref in the DBI module or using something like Class::DBI.</p>\n" }, { "answer_id": 51209, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 3, "selected": false, "text": "<p>The array of hashes doesn't actually contain hashes, but rather an <em>references</em> to a hash.\nThis line: </p>\n\n<pre><code>%row = $records[$index];\n</code></pre>\n\n<p>assigns %row with one entry. The key is the <em>scalar</em>:</p>\n\n<pre><code> {'id' =&gt; 1, 'firstName' =&gt; 'Jim'},\n</code></pre>\n\n<p>Which is a reference to the hash, while the value is blank.</p>\n\n<p>What you really want to do is this:</p>\n\n<pre><code>$row = $records[$index];\n$row-&gt;{'firstName'};\n</code></pre>\n\n<p>or else:</p>\n\n<pre><code>$row = %{$records[$index];}\n$row{'firstName'};\n</code></pre>\n" }, { "answer_id": 51307, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "<p>Others have commented on hashes vs hashrefs. One other thing that I feel should be mentioned is your DBQuery function - it seems you're trying to do something that's already built into the DBI? If I understand your question correctly, you're trying to replicate something like <a href=\"http://search.cpan.org/~timb/DBI-1.607/DBI.pm#selectall_arrayref\" rel=\"nofollow noreferrer\">selectall_arrayref</a>:</p>\n\n<blockquote>\n <p>This utility method combines \"prepare\", \"execute\" and \"fetchall_arrayref\" into a single call. It returns a reference to an array containing a reference to an array (or hash, see below) for each row of data fetched.</p>\n</blockquote>\n" }, { "answer_id": 53145, "author": "theorbtwo", "author_id": 4839, "author_profile": "https://Stackoverflow.com/users/4839", "pm_score": 2, "selected": false, "text": "<p>To add to the lovely answers above, let me add that you should always, always, always (yes, three \"always\"es) use \"use warnings\" at the top of your code. If you had done so, you would have gotten the warning \"Reference found where even-sized list expected at -e line 1.\"</p>\n" }, { "answer_id": 70678, "author": "jonfm", "author_id": 6924, "author_profile": "https://Stackoverflow.com/users/6924", "pm_score": 0, "selected": false, "text": "<p>Also note a good perl idiom to use is</p>\n\n<pre>for my $rowHR ( @records ) {\n my %row = %$rowHR; \n #or whatever...\n}</pre> \n\n<p>to iterate through the list.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue. I can get the data "Jim" out of a hash inside an array with this syntax: ``` print $records[$index]{'firstName'} ``` returns "Jim" but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash: ``` %row = $records[$index]; $row{'firstName'}; ``` returns "" (blank) Here is the full sample code showing the problem. Any help is appreciated: ``` my @records = ( {'id' => 1, 'firstName' => 'Jim'}, {'id' => 2, 'firstName' => 'Joe'} ); my @records2 = (); $numberOfRecords = scalar(@records); print "number of records: " . $numberOfRecords . "\n"; for(my $index=0; $index < $numberOfRecords; $index++) { #works print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n"; #does NOT work %row = $records[$index]; print 'but not like this: ' . $row{'firstName'} . "\n"; } ```
The nested data structure contains a hash *reference*, not a hash. ``` # Will work (the -> dereferences the reference) $row = $records[$index]; print "This will work: ", $row->{firstName}, "\n"; # This will also work, by promoting the hash reference into a hash %row = %{ $records[$index] }; print "This will work: ", $row{firstName}, "\n"; ``` If you're ever presented with a deep Perl data structure, you may profit from printing it using [Data::Dumper](http://search.cpan.org/perldoc?Data::Dumper) to print it into human-readable (and Perl-parsable) form.
51,210
<p>I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.</p> <p>This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.</p> <p>Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.</p> <p>In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist?</p> <p>EDIT:</p> <p>So the code here is: </p> <pre><code># File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141 def rescue_action_without_handler(exception) log_error(exception) if logger erase_results if performed? # Let the exception alter the response if it wants. # For example, MethodNotAllowed sets the Allow header. if exception.respond_to?(:handle_response!) exception.handle_response!(response) end if consider_all_requests_local || local_request? rescue_action_locally(exception) else rescue_action_in_public(exception) end end </code></pre> <p>So our best option is to override log_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController</p> <pre><code>def log_error(exception) message = '...' if should_log_exception_as_debug?(exception) logger.debug(message) else logger.error(message) end end def should_log_exception_as_debug?(exception) return (ActionController::RoutingError === exception) end </code></pre> <p>Salt for additional logic where we want different controller logic, routes, etc.</p>
[ { "answer_id": 51378, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": false, "text": "<p>There's the method_missing method. You could implement that in your Application Controller and catch all missing actions, maybe logging those and redirecting to the index action of the relevant controller. This approach would ignore everything that can't be routed to a controller, which is pretty close to what you want. </p>\n\n<p>Alternatively, I'd just log all errors, extract the URL and sort it by # of times it occured.</p>\n" }, { "answer_id": 71601, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 2, "selected": false, "text": "<p>Nooooo!!! Don't implement method_missing on your controller! And please try to avoid action_missing as well.</p>\n\n<p>The frequently touted pattern is to add a route:</p>\n\n<pre><code>map.connect '*', :controller =&gt; 'error', :action =&gt; 'not_found'\n</code></pre>\n\n<p>Where you can show an appropriate error.</p>\n\n<p>Rails also has a mechanism called rescue_action_in_public where you can write your own error handling logic -- we really should clean it up and encourage people to use it. PDI! :-)</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266/" ]
I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path. This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that. Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them. In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist? EDIT: So the code here is: ``` # File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141 def rescue_action_without_handler(exception) log_error(exception) if logger erase_results if performed? # Let the exception alter the response if it wants. # For example, MethodNotAllowed sets the Allow header. if exception.respond_to?(:handle_response!) exception.handle_response!(response) end if consider_all_requests_local || local_request? rescue_action_locally(exception) else rescue_action_in_public(exception) end end ``` So our best option is to override log\_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController ``` def log_error(exception) message = '...' if should_log_exception_as_debug?(exception) logger.debug(message) else logger.error(message) end end def should_log_exception_as_debug?(exception) return (ActionController::RoutingError === exception) end ``` Salt for additional logic where we want different controller logic, routes, etc.
Nooooo!!! Don't implement method\_missing on your controller! And please try to avoid action\_missing as well. The frequently touted pattern is to add a route: ``` map.connect '*', :controller => 'error', :action => 'not_found' ``` Where you can show an appropriate error. Rails also has a mechanism called rescue\_action\_in\_public where you can write your own error handling logic -- we really should clean it up and encourage people to use it. PDI! :-)
51,212
<p>I am writing a little application to download files over http (as, for example, described <a href="https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776">here</a>).</p> <p>I also want to include a little download progress indicator showing the percentage of the download progress.</p> <p>Here is what I came up with:</p> <pre> sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush() </pre> <p>Output: MyFileName... 9%</p> <p>Any other ideas or recommendations to do this? </p> <p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p> <p><strong>EDIT:</strong></p> <p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p> <pre> global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush() </pre> <p>Output: MyFileName...9% </p> <p>And the cursor shows up at the END of the line. Much better.</p>
[ { "answer_id": 51214, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "<p>If you use the <code>curses</code> package, you have much greater control of the console. It also comes at a higher cost in code complexity and is probably unnecessary unless you are developing a large console-based app.</p>\n\n<p>For a simple solution, you can always put the spinning wheel at the end of the status messge (the sequence of characters <code>|, \\, -, /</code> which actually looks nice under blinking cursor.</p>\n" }, { "answer_id": 51218, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 4, "selected": false, "text": "<p>You might also try:</p>\n\n<pre><code>sys.stdout.write(\"\\r%2d%%\" % percent)\nsys.stdout.flush()\n</code></pre>\n\n<p>Using a single carriage return at the beginning of your string rather than several backspaces. Your cursor will still blink, but it'll blink after the percent sign rather than under the first digit, and with one control character instead of three you may get less flicker.</p>\n" }, { "answer_id": 51239, "author": "readonly", "author_id": 4883, "author_profile": "https://Stackoverflow.com/users/4883", "pm_score": 5, "selected": true, "text": "<p>There's a text progress bar library for python at <a href=\"http://pypi.python.org/pypi/progressbar/2.2\" rel=\"noreferrer\">http://pypi.python.org/pypi/progressbar/2.2</a> that you might find useful:</p>\n<blockquote>\n<p>This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.</p>\n<p>The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.</p>\n<p>The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.</p>\n</blockquote>\n" }, { "answer_id": 704865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For small files you may need to had this lines in order to avoid crazy percentages:</p>\n\n<p>sys.stdout.write(\"\\r%2d%%\" % percent)</p>\n\n<p>sys.stdout.flush()</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 12880543, "author": "Arnaud Aliès", "author_id": 1722117, "author_profile": "https://Stackoverflow.com/users/1722117", "pm_score": 0, "selected": false, "text": "<p>Thats how I did this could help you:\n<a href=\"https://github.com/mouuff/MouDownloader/blob/master/api/download.py\" rel=\"nofollow\">https://github.com/mouuff/MouDownloader/blob/master/api/download.py</a></p>\n" }, { "answer_id": 14123416, "author": "MichaelvdNet", "author_id": 1636835, "author_profile": "https://Stackoverflow.com/users/1636835", "pm_score": 1, "selected": false, "text": "<p>I used this code:</p>\n\n<pre><code>url = (&lt;file location&gt;)\nfile_name = url.split('/')[-1]\nu = urllib2.urlopen(url)\nf = open(file_name, 'wb')\nmeta = u.info()\nfile_size = int(meta.getheaders(\"Content-Length\")[0])\nprint \"Downloading: %s Bytes: %s\" % (file_name, file_size)\n\nfile_size_dl = 0\nblock_sz = 8192\nwhile True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n f.write(buffer)\n status = r\"%10d [%3.2f%%]\" % (file_size_dl, file_size_dl * 100. / file_size)\n status = status + chr(8)*(len(status)+1)\n print status,\n\nf.close()\n</code></pre>\n" }, { "answer_id": 28424236, "author": "mafrosis", "author_id": 425050, "author_profile": "https://Stackoverflow.com/users/425050", "pm_score": 0, "selected": false, "text": "<p>Late to the party, as usual. Here's an implementation that supports reporting progress, like the core <code>urlretrieve</code>:</p>\n\n<pre><code>import urllib2\n\ndef urlretrieve(urllib2_request, filepath, reporthook=None, chunk_size=4096):\n req = urllib2.urlopen(urllib2_request)\n\n if reporthook:\n # ensure progress method is callable\n if hasattr(reporthook, '__call__'):\n reporthook = None\n\n try:\n # get response length\n total_size = req.info().getheaders('Content-Length')[0]\n except KeyError:\n reporthook = None\n\n data = ''\n num_blocks = 0\n\n with open(filepath, 'w') as f:\n while True:\n data = req.read(chunk_size)\n num_blocks += 1\n if reporthook:\n # report progress\n reporthook(num_blocks, chunk_size, total_size)\n if not data:\n break\n f.write(data)\n\n # return downloaded length\n return len(data)\n</code></pre>\n" }, { "answer_id": 36022923, "author": "tstone2077", "author_id": 1803741, "author_profile": "https://Stackoverflow.com/users/1803741", "pm_score": 3, "selected": false, "text": "<p>For what it's worth, here's the code I used to get it working:</p>\n\n<pre><code>from urllib import urlretrieve\nfrom progressbar import ProgressBar, Percentage, Bar\n\nurl = \"http://.......\"\nfileName = \"file\"\npbar = ProgressBar(widgets=[Percentage(), Bar()])\nurlretrieve(url, fileName, reporthook=dlProgress)\n\ndef dlProgress(count, blockSize, totalSize):\n pbar.update( int(count * blockSize * 100 / totalSize) )\n</code></pre>\n" }, { "answer_id": 43475317, "author": "Paal Pedersen", "author_id": 7048431, "author_profile": "https://Stackoverflow.com/users/7048431", "pm_score": 1, "selected": false, "text": "<pre><code>def download_progress_hook(count, blockSize, totalSize):\n \"\"\"A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 5% change in download progress.\n \"\"\"\n global last_percent_reported\n percent = int(count * blockSize * 100 / totalSize)\n\n if last_percent_reported != percent:\n if percent % 5 == 0:\n sys.stdout.write(\"%s%%\" % percent)\n sys.stdout.flush()\n else:\n sys.stdout.write(\".\")\n sys.stdout.flush()\n\n last_percent_reported = percent\n\nurlretrieve(url, filename, reporthook=download_progress_hook)\n</code></pre>\n" }, { "answer_id": 70750636, "author": "Ashutosh Kumbhar", "author_id": 13547109, "author_profile": "https://Stackoverflow.com/users/13547109", "pm_score": 0, "selected": false, "text": "<p>To avoid progress values like 106% or similar, follow the below logic</p>\n<pre class=\"lang-py prettyprint-override\"><code>percent = min(int(count * blockSize * 100 / totalSize), 100)\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
I am writing a little application to download files over http (as, for example, described [here](https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776)). I also want to include a little download progress indicator showing the percentage of the download progress. Here is what I came up with: ``` sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush() ``` Output: MyFileName... 9% Any other ideas or recommendations to do this? One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor? **EDIT:** Here a better alternative using a global variable for the filename in dlProgress and the '\r' code: ``` global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush() ``` Output: MyFileName...9% And the cursor shows up at the END of the line. Much better.
There's a text progress bar library for python at <http://pypi.python.org/pypi/progressbar/2.2> that you might find useful: > > This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. > > > The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. > > > The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available. > > >
51,217
<p>I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code.</p> <p>In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc. </p>
[ { "answer_id": 51220, "author": "Eric", "author_id": 5277, "author_profile": "https://Stackoverflow.com/users/5277", "pm_score": 2, "selected": false, "text": "<p>You could use a service like www.unfuddle.com to set up a free SVN or GIT repository.</p>\n\n<p>We use Unfuddle and it's really great. There are free and paid versions (depending on your needs).</p>\n\n<p>Or, you could of course set up a local copy. There are plenty of tutorials to be found via Google for that: <a href=\"http://www.google.com/search?rlz=1C1GGLS_enUS291&amp;aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=set+up+svn\" rel=\"nofollow noreferrer\">http://www.google.com/search?rlz=1C1GGLS_enUS291&amp;aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=set+up+svn</a></p>\n" }, { "answer_id": 51223, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>As specified in <a href=\"https://stackoverflow.com/questions/49601/is-there-a-barebones-windows-version-control-system-thats-suitable-for-only-one#49722\">this thread</a>, distributed VCSs (git, Mercurial) are a better model than centralized ones, due to branch creation ease, branch merging ease, no need to setup a special server, no need to have network access to work and some other advantages. If you'll work alone the DVCS allows you to incorporate people to your projects if the need arises very easily. </p>\n\n<p>Anyhow, answering directly your question, a way to set up SVN would be to have a repository per project and, depending on if stored procedures and scripts and libraries are shared or not, create a directory on each project tree for scripts and stored procedures, or a full repository for the shared code.</p>\n" }, { "answer_id": 51234, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 3, "selected": false, "text": "<p>For subversion, there is <a href=\"http://www.assembla.com/\" rel=\"nofollow noreferrer\">Assembla</a> too which comes with <a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">Trac</a> and other useful tools. It's free or you could pay for an account if you need more space or users per project.</p>\n" }, { "answer_id": 51246, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 2, "selected": false, "text": "<p>For my company, I use svn+ssh and key-based authentication. You can do this with both windows clients and linux clients. This is real easy to use once you get your keys straight as you use an ssh key to login rather than typing a password.</p>\n\n<p><a href=\"http://svn.haxx.se/dev/archive-2004-03/0253.shtml\" rel=\"nofollow noreferrer\">Here's an article on setting up svn+ssh</a> with notes on security. If you understand all of this stuff and follow these steps, you'll be off to a good start.</p>\n\n<p><a href=\"http://svn.apache.org/repos/asf/subversion/trunk/notes/ssh-tricks\" rel=\"nofollow noreferrer\">This article</a> describes a number of ways to further secure your ssh logins for the svn accounts. </p>\n\n<p>I recommend creating accounts specifically for svn access with no other access to that server. My guess is that you would use a daily build or automated script to update your stored procs in the db. Daily builds can have their own special accounts and their own ssh keys. I don't like for my automated tools to run with the same login as a human user (so I know which tool is broken).</p>\n\n<p>If you don't understand all of the security tricks, searching google can get you some help. If you have trouble, set one up without the security tricks first. That makes it a bit simpler to troubleshoot. </p>\n\n<p>Good luck, and enjoy having the benefits of source control!</p>\n" }, { "answer_id": 51248, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 2, "selected": false, "text": "<p>One repository for your projects is probably sufficient. I like the typical approach that indexes the layout by project (see <a href=\"http://svnbook.red-bean.com/en/1.1/ch04s07.html#svn-ch-4-sect-7.1\" rel=\"nofollow noreferrer\">this section</a> from the <a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">O'Reilly Subversion book</a>):</p>\n\n<pre><code>/first-project/trunk\n/first-project/branches\n/first-project/tags\n/another-project/trunk\n/another-project/branches\n/another-project/tags\n/common-stuff/trunk\n/common-stuff/branches\n/common-stuff/tags\n</code></pre>\n\n<p>Keep in mind that you can always reorganize the repository later.</p>\n\n<p>Also, for in-house stuff, I prefer FSFS for the data-store, as opposed to Berkeley DB. FSFS is more resilient and the speed of checkouts is not much concern for small teams/projects. You can <a href=\"http://svnbook.red-bean.com/en/1.1/ch05.html#svn-ch-5-sect-1.3\" rel=\"nofollow noreferrer\">compare</a> and decide for yourself.</p>\n\n<p>Other standard parts of the recipe include <a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">Trac</a> and a minimal Linux server to host the repository on the LAN.</p>\n" }, { "answer_id": 51258, "author": "John Virgolino", "author_id": 4246, "author_profile": "https://Stackoverflow.com/users/4246", "pm_score": 4, "selected": false, "text": "<p>Setting up SVN repositories can be tricky only in the sense of how you organize them. Before we setup SVN, I actually RTFM'd the online <a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">Subversion manual</a> which discusses organizational techniques for repositories and some of the gotchas you should think about in advance, namely what you cannot do after you have created your repositories if you decide to change your mind. I suggest a pass through this manual before setup.</p>\n\n<p>For us, as consultants, we do custom and in-house software development as well as some document management through SVN. It was in our interest to create one repository for each client and one for ourselves. Within each repository, we created folders for each project (software or otherwise). This allowed us to segment security access by repository and by client and even by project within a repository. Going deeper, for each software project we created 'working', 'tags' and 'branches' folders. We generally put releases in 'tags' using 'release_w.x.y.z' as the tag for a standard.</p>\n\n<p>In your case, to keep sprocs, scripts, and other related documents in synch, you can create a project folder, then under that a 'working' folder, then under that 'code' and next to it 'scripts', etc. Then when you tag the working version for release, you end up tagging it all together.</p>\n\n<pre><code>\\Repository\n \\ProjectX\n \\Working\n \\Code \n \\Scripts\n \\Notes \n \\Tags\n \\Branches\n</code></pre>\n\n<p>As for non-code, I would suggest a straight folder layout by project or document type (manuals, policies, etc.). Generally with documents and depending on how your company operates, just having the version history/logs is enough.</p>\n\n<p>We run SVN on Windows along with <a href=\"http://websvn.tigris.org/\" rel=\"nofollow noreferrer\">WebSVN</a> which is a great open source repository viewer. We use it to give clients web access to their code and it's all driven by the underlying Subversion security. Internally, we use <a href=\"http://tortoisesvn.tigris.org/\" rel=\"nofollow noreferrer\">TortoiseSVN</a> to manage the repositories, commit, update, import, etc.</p>\n\n<p>Another thing is that training should be considered an integral part of your deployment. Users new to version control may have a hard time understanding what is going on. We found that giving them functional instructions (do this when creating a project, do this when updating, etc.) was very helpful while they learned the concepts. We created a 'sandbox' repository where users can play all they want with documents and folders to practice, you may find this useful as well to experiment on what policies to establish.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 55122, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 2, "selected": false, "text": "<p>After posting this question I spoke with a coworker who suggested I read the article:</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000968.html\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/archives/000968.html</a></p>\n\n<p>In short, it advocates that programmers be more aware of branching. It helped me to see there is no right way to go about organizing our repository. For our team we will have a trunk and two long term branches for test and development. In addition we will make seperate branches for each task do we and merged the changes from the task branches as we promote the task up to testing and production.</p>\n" }, { "answer_id": 96763, "author": "Peter Kahn", "author_id": 9950, "author_profile": "https://Stackoverflow.com/users/9950", "pm_score": 0, "selected": false, "text": "<p>I believe in following the basic pattern with a project dir with trunk,tags,branches beneath it. I usually like to setup the top level like this</p>\n\n<p>Projects holds all of the individual project or modules\nReleases holds release tags that involve multiple modules\nUsers holds private user branches\nAdmin holds my hook scripts, backup scripts etc.</p>\n\n<p>The release tags are useful if you have a product that is made up of several modules that all may be a different tags for a specific release (one ring to bind them and all that). It makes it easy for source escrow and for developments to reference what made up release 1 or 2.</p>\n" }, { "answer_id": 304046, "author": "Rob Williams", "author_id": 26682, "author_profile": "https://Stackoverflow.com/users/26682", "pm_score": 2, "selected": false, "text": "<p>I agree with using the common conventions of trunk/branches/tags. Beyond that, I think you might be looking for something like my answer at <a href=\"https://stackoverflow.com/questions/222827/how-do-you-organize-your-version-control-repository#304036\">How do you organize your version control repository?</a>.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code. In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc.
Setting up SVN repositories can be tricky only in the sense of how you organize them. Before we setup SVN, I actually RTFM'd the online [Subversion manual](http://svnbook.red-bean.com/) which discusses organizational techniques for repositories and some of the gotchas you should think about in advance, namely what you cannot do after you have created your repositories if you decide to change your mind. I suggest a pass through this manual before setup. For us, as consultants, we do custom and in-house software development as well as some document management through SVN. It was in our interest to create one repository for each client and one for ourselves. Within each repository, we created folders for each project (software or otherwise). This allowed us to segment security access by repository and by client and even by project within a repository. Going deeper, for each software project we created 'working', 'tags' and 'branches' folders. We generally put releases in 'tags' using 'release\_w.x.y.z' as the tag for a standard. In your case, to keep sprocs, scripts, and other related documents in synch, you can create a project folder, then under that a 'working' folder, then under that 'code' and next to it 'scripts', etc. Then when you tag the working version for release, you end up tagging it all together. ``` \Repository \ProjectX \Working \Code \Scripts \Notes \Tags \Branches ``` As for non-code, I would suggest a straight folder layout by project or document type (manuals, policies, etc.). Generally with documents and depending on how your company operates, just having the version history/logs is enough. We run SVN on Windows along with [WebSVN](http://websvn.tigris.org/) which is a great open source repository viewer. We use it to give clients web access to their code and it's all driven by the underlying Subversion security. Internally, we use [TortoiseSVN](http://tortoisesvn.tigris.org/) to manage the repositories, commit, update, import, etc. Another thing is that training should be considered an integral part of your deployment. Users new to version control may have a hard time understanding what is going on. We found that giving them functional instructions (do this when creating a project, do this when updating, etc.) was very helpful while they learned the concepts. We created a 'sandbox' repository where users can play all they want with documents and folders to practice, you may find this useful as well to experiment on what policies to establish. Good luck!
51,224
<p>I'm trying to write a regular expression that validates a date. The regex needs to match the following</p> <ul> <li>M/D/YYYY</li> <li>MM/DD/YYYY</li> <li>Single digit months can start with a leading zero (eg: 03/12/2008)</li> <li>Single digit days can start with a leading zero (eg: 3/02/2008)</li> <li>CANNOT include February 30 or February 31 (eg: 2/31/2008)</li> </ul> <p>So far I have </p> <pre><code>^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ </code></pre> <p>This matches properly EXCEPT it still includes 2/30/2008 &amp; 2/31/2008.</p> <p>Does anyone have a better suggestion?</p> <p><strong>Edit:</strong> I found <a href="http://regexlib.com/REDetails.aspx?regexp_id=112" rel="noreferrer">the answer</a> on RegExLib</p> <pre><code>^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ </code></pre> <p>It matches all valid months that follow the MM/DD/YYYY format.</p> <p>Thanks everyone for the help.</p>
[ { "answer_id": 51227, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 2, "selected": false, "text": "<p>Sounds like you're overextending regex for this purpose. What I would do is use a regex to match a few date formats and then use a separate function to validate the values of the date fields so extracted.</p>\n" }, { "answer_id": 51229, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<p>Regex was not meant to validate number ranges(this number must be from 1 to 5 when the number preceding it happens to be a 2 and the number preceding that happens to be below 6).\nJust look for the pattern of placement of numbers in regex. If you need to validate is qualities of a date, put it in a date object js/c#/vb, and interogate the numbers there.</p>\n" }, { "answer_id": 51231, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": true, "text": "<p>This is not an appropriate use of regular expressions. You'd be better off using</p>\n\n<pre><code>[0-9]{2}/[0-9]{2}/[0-9]{4}\n</code></pre>\n\n<p>and then checking ranges in a higher-level language.</p>\n" }, { "answer_id": 51235, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>I know this does not answer your question, but why don't you use a date handling routine to check if it's a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you'll still have the problem of accepting 29 02 on non leap years and about a single separator date format. </p>\n\n<p>The problem is not easy if you want to really validate a date, check this <a href=\"http://discuss.joelonsoftware.com/default.asp?joel.3.229443.10\" rel=\"nofollow noreferrer\">forum thread</a>. </p>\n\n<p>For an example or a better way, in C#, check <a href=\"http://www.codeguru.com/columns/dotnettips/article.php/c7547\" rel=\"nofollow noreferrer\">this link</a></p>\n\n<p>If you are using another platform/language, let us know</p>\n" }, { "answer_id": 51236, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "<p>If you're going to insist on doing this with a regular expression, I'd recommend something like:</p>\n\n<pre><code>( (0?1|0?3| &lt;...&gt; |10|11|12) / (0?1| &lt;...&gt; |30|31) |\n 0?2 / (0?1| &lt;...&gt; |28|29) ) \n/ (19|20)[0-9]{2}\n</code></pre>\n\n<p>This <em>might</em> make it possible to read and understand.</p>\n" }, { "answer_id": 60869, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "<h2>Perl expanded version</h2>\n<p>Note use of <code>/x</code> modifier.</p>\n<pre><code>/^(\n (\n ( # 31 day months\n (0[13578])\n | ([13578])\n | (1[02])\n )\n [\\/]\n (\n ([1-9])\n | ([0-2][0-9])\n | (3[01])\n )\n )\n | (\n ( # 30 day months\n (0[469])\n | ([469])\n | (11)\n )\n [\\/]\n (\n ([1-9])\n | ([0-2][0-9])\n | (30)\n )\n )\n | ( # 29 day month (Feb)\n (2|02)\n [\\/]\n (\n ([1-9])\n | ([0-2][0-9])\n )\n )\n )\n [\\/]\n # year\n \\d{4}$\n \n | ^\\d{4}$ # year only\n/x\n</code></pre>\n<p>Original</p>\n<pre><code>^((((0[13578])|([13578])|(1[02]))[\\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\\/](([1-9])|([0-2][0-9]))))[\\/]\\d{4}$|^\\d{4}$\n</code></pre>\n" }, { "answer_id": 60890, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 4, "selected": false, "text": "<h2>Maintainable Perl 5.10 version</h2>\n<pre><code>/\n (?:\n (?&lt;month&gt; (?&amp;mon_29)) [\\/] (?&lt;day&gt;(?&amp;day_29))\n | (?&lt;month&gt; (?&amp;mon_30)) [\\/] (?&lt;day&gt;(?&amp;day_30))\n | (?&lt;month&gt; (?&amp;mon_31)) [\\/] (?&lt;day&gt;(?&amp;day_31))\n )\n [\\/]\n (?&lt;year&gt; [0-9]{4})\n \n (?(DEFINE)\n (?&lt;mon_29&gt; 0?2 )\n (?&lt;mon_30&gt; 0?[469] | (11) )\n (?&lt;mon_31&gt; 0?[13578] | 1[02] )\n\n (?&lt;day_29&gt; 0?[1-9] | [1-2]?[0-9] )\n (?&lt;day_30&gt; 0?[1-9] | [1-2]?[0-9] | 30 )\n (?&lt;day_31&gt; 0?[1-9] | [1-2]?[0-9] | 3[01] )\n )\n/x\n</code></pre>\n<p>You can retrieve the elements by name in this version.</p>\n<pre><code>say &quot;Month=$+{month} Day=$+{day} Year=$+{year}&quot;;\n</code></pre>\n<p>( No attempt has been made to restrict the values for the year. )</p>\n" }, { "answer_id": 60899, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<h1>Perl 6 version</h1>\n\n\n\n<pre class=\"lang-perl6 prettyprint-override\"><code>rx{\n ^\n\n $&lt;month&gt; = (\\d ** 1..2)\n { $&lt;month&gt; &lt;= 12 or fail }\n\n '/'\n\n $&lt;day&gt; = (\\d ** 1..2)\n {\n given( +$&lt;month&gt; ){\n when 1|3|5|7|8|10|12 {\n $&lt;day&gt; &lt;= 31 or fail\n }\n when 4|6|9|11 {\n $&lt;day&gt; &lt;= 30 or fail\n }\n when 2 {\n $&lt;day&gt; &lt;= 29 or fail\n }\n default { fail }\n }\n }\n\n '/'\n\n $&lt;year&gt; = (\\d ** 4)\n\n $\n}\n</code></pre>\n\n<p>After you use this to check the input the values are available in <code>$/</code> or individually as <code>$&lt;month&gt;</code>, <code>$&lt;day&gt;</code>, <code>$&lt;year&gt;</code>. ( those are just syntax for accessing values in <code>$/</code> )</p>\n\n<p>No attempt has been made to check the year, or that it doesn't match the 29th of Feburary on non leap years.</p>\n" }, { "answer_id": 221748, "author": "Humpton", "author_id": 1444, "author_profile": "https://Stackoverflow.com/users/1444", "pm_score": -1, "selected": false, "text": "<p>A slightly different approach that may or may not be useful for you.</p>\n\n<p>I'm in php.</p>\n\n<p>The project this relates to will never have a date prior to the 1st of January 2008. So, I take the 'date' inputed and use strtotime(). If the answer is >= 1199167200 then I have a date that is useful to me. If something that doesn't look like a date is entered -1 is returned. If null is entered it does return today's date number so you do need a check for a non-null entry first.</p>\n\n<p>Works for my situation, perhaps yours too? </p>\n" }, { "answer_id": 8768241, "author": "Varun Achar", "author_id": 652895, "author_profile": "https://Stackoverflow.com/users/652895", "pm_score": 6, "selected": false, "text": "<p>Here is the Reg ex that matches all valid dates including leap years. Formats accepted mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy format</p>\n\n<p><code>^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.)31)\\1|(?:(?:0?[1,3-9]|1[0-2])(\\/|-|\\.)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$</code></p>\n\n<p><em>courtesy <a href=\"http://www.advancedqtp.com/forums/index.php?topic=4394.0\">Asiq Ahamed</a></em></p>\n" }, { "answer_id": 8949462, "author": "chuck akers", "author_id": 1148562, "author_profile": "https://Stackoverflow.com/users/1148562", "pm_score": 2, "selected": false, "text": "<p>if you didn't get those above suggestions working, I use this, as it gets any date I ran this expression through 50 links, and it got all the dates on each page. </p>\n\n<pre><code>^20\\d\\d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(0[1-9]|[1-2][0-9]|3[01])$ \n</code></pre>\n" }, { "answer_id": 13533903, "author": "ALinnD", "author_id": 1848216, "author_profile": "https://Stackoverflow.com/users/1848216", "pm_score": 2, "selected": false, "text": "<pre><code> var dtRegex = new RegExp(/[1-9\\-]{4}[0-9\\-]{2}[0-9\\-]{2}/);\n if(dtRegex.test(date) == true){\n var evalDate = date.split('-');\n if(evalDate[0] != '0000' &amp;&amp; evalDate[1] != '00' &amp;&amp; evalDate[2] != '00'){\n return true;\n }\n }\n</code></pre>\n" }, { "answer_id": 15968019, "author": "Okipa", "author_id": 2273711, "author_profile": "https://Stackoverflow.com/users/2273711", "pm_score": 3, "selected": false, "text": "<p>To control a date validity under the following format :</p>\n\n<blockquote>\n <p>YYYY/MM/DD or YYYY-MM-DD</p>\n</blockquote>\n\n<p>I would recommand you tu use the following regular expression :</p>\n\n<pre><code>(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[4678]|1[02])[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[1359]|11)[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))\n</code></pre>\n\n<p>Matches </p>\n\n<blockquote>\n <p>2016-02-29 | 2012-04-30 | 2019/09/31</p>\n</blockquote>\n\n<p>Non-Matches </p>\n\n<blockquote>\n <p>2016-02-30 | 2012-04-31 | 2019/09/35</p>\n</blockquote>\n\n<p>You can customise it if you wants to allow only '/' or '-' separators.\nThis RegEx strictly controls the validity of the date and verify 28,30 and 31 days months, even leap years with 29/02 month.</p>\n\n<p>Try it, it works very well and prevent your code from lot of bugs !</p>\n\n<p>FYI : I made a variant for the SQL datetime. You'll find it there (look for my name) : <a href=\"https://stackoverflow.com/questions/1057716/regular-expression-to-validate-a-timestamp\">Regular Expression to validate a timestamp</a></p>\n\n<p>Feedback are welcomed :)</p>\n" }, { "answer_id": 16285136, "author": "Enrique", "author_id": 2333144, "author_profile": "https://Stackoverflow.com/users/2333144", "pm_score": 2, "selected": false, "text": "<p>This regex validates dates between 01-01-2000 and 12-31-2099 with matching separators.</p>\n\n<pre><code>^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])\\2(19|20)\\d\\d$\n</code></pre>\n" }, { "answer_id": 40309602, "author": "Bob", "author_id": 177055, "author_profile": "https://Stackoverflow.com/users/177055", "pm_score": 5, "selected": false, "text": "<p>I landed here because the title of this question is broad and I was looking for a regex that I could use to match on a specific date format (like the OP). But I then discovered, as many of the answers and comments have comprehensively highlighted, there are many pitfalls that make constructing an effective pattern very tricky when extracting dates that are mixed-in with poor quality or non-structured source data. </p>\n\n<p>In my exploration of the issues, I have come up with a system that enables you to build a regular expression by arranging together four simpler sub-expressions that match on the delimiter, and valid ranges for the year, month and day fields in the order you require. </p>\n\n<p>These are :-</p>\n\n<p><strong>Delimeters</strong></p>\n\n<pre><code>[^\\w\\d\\r\\n:] \n</code></pre>\n\n<p>This will match anything that is not a word character, digit character, carriage return, new line or colon. The colon has to be there to prevent matching on times that look like dates (see my test Data) </p>\n\n<p>You can optimise this part of the pattern to speed up matching, but this is a good foundation that detects most valid delimiters. </p>\n\n<p>Note however; It will match a string with mixed delimiters like this 2/12-73 that may not actually be a valid date. </p>\n\n<p><strong>Year Values</strong></p>\n\n<pre><code>(\\d{4}|\\d{2})\n</code></pre>\n\n<p>This matches a group of two or 4 digits, in most cases this is acceptable, but if you're dealing with data from the years 0-999 or beyond 9999 you need to decide how to handle that because in most cases a 1, 3 or >4 digit year is garbage.</p>\n\n<p><strong>Month Values</strong></p>\n\n<pre><code>(0?[1-9]|1[0-2])\n</code></pre>\n\n<p>Matches any number between 1 and 12 with or without a leading zero - note: 0 and 00 is not matched.</p>\n\n<p><strong>Date Values</strong></p>\n\n<pre><code>(0?[1-9]|[12]\\d|30|31)\n</code></pre>\n\n<p>Matches any number between 1 and 31 with or without a leading zero - note: 0 and 00 is not matched.</p>\n\n<p><strong>This expression matches Date, Month, Year formatted dates</strong></p>\n\n<pre><code>(0?[1-9]|[12]\\d|30|31)[^\\w\\d\\r\\n:](0?[1-9]|1[0-2])[^\\w\\d\\r\\n:](\\d{4}|\\d{2})\n</code></pre>\n\n<p>But it will also match some of the Year, Month Date ones. It should also be bookended with the boundary operators to ensure the whole date string is selected and prevent valid sub-dates being extracted from data that is not well-formed i.e. without boundary tags 20/12/194 matches as 20/12/19 and 101/12/1974 matches as 01/12/1974 </p>\n\n<p>Compare the results of the next expression to the one above with the test data in the nonsense section (below)</p>\n\n<pre><code>\\b(0?[1-9]|[12]\\d|30|31)[^\\w\\d\\r\\n:](0?[1-9]|1[0-2])[^\\w\\d\\r\\n:](\\d{4}|\\d{2})\\b\n</code></pre>\n\n<p>There's no validation in this regex so a well-formed but invalid date such as 31/02/2001 would be matched. That is a data quality issue, and as others have said, your regex shouldn't need to validate the data. </p>\n\n<p>Because you (as a developer) can't guarantee the quality of the source data you do need to perform and handle additional validation in your code, if you try to match <strong>and</strong> validate the data in the RegEx it gets very messy and becomes difficult to support without <strong>very</strong> concise documentation.</p>\n\n<p>Garbage in, garbage out.</p>\n\n<p>Having said that, if you do have mixed formats where the date values vary, and you have to extract as much as you can; You can combine a couple of expressions together like so;</p>\n\n<p><strong>This (disastrous) expression matches DMY and YMD dates</strong> </p>\n\n<pre><code>(\\b(0?[1-9]|[12]\\d|30|31)[^\\w\\d\\r\\n:](0?[1-9]|1[0-2])[^\\w\\d\\r\\n:](\\d{4}|\\d{2})\\b)|(\\b(0?[1-9]|1[0-2])[^\\w\\d\\r\\n:](0?[1-9]|[12]\\d|30|31)[^\\w\\d\\r\\n:](\\d{4}|\\d{2})\\b)\n</code></pre>\n\n<p>BUT you won't be able to tell if dates like 6/9/1973 are the 6th of September or the 9th of June. I'm struggling to think of a scenario where that is not going to cause a problem somewhere down the line, it's bad practice and you shouldn't have to deal with it like that - find the data owner and hit them with the governance hammer.</p>\n\n<p>Finally, if you want to match a YYYYMMDD string with no delimiters you can take some of the uncertainty out and the expression looks like this</p>\n\n<pre><code>\\b(\\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\\d|30|31)\\b\n</code></pre>\n\n<p>But note again, it will match on well-formed but invalid values like 20010231 (31th Feb!) :)</p>\n\n<p><strong>Test data</strong></p>\n\n<p>In experimenting with the solutions in this thread I ended up with a test data set that includes a variety of valid and non-valid dates and some tricky situations where you may or may not want to match i.e. Times that could match as dates and dates on multiple lines. </p>\n\n<p>I hope this is useful to someone.</p>\n\n<pre><code>Valid Dates in various formats\n\nDay, month, year\n2/11/73\n02/11/1973\n2/1/73\n02/01/73\n31/1/1973\n02/1/1973\n31.1.2011\n31-1-2001\n29/2/1973\n29/02/1976 \n03/06/2010\n12/6/90\n\nmonth, day, year\n02/24/1975 \n06/19/66 \n03.31.1991\n2.29.2003\n02-29-55\n03-13-55\n03-13-1955\n12\\24\\1974\n12\\30\\1974\n1\\31\\1974\n03/31/2001\n01/21/2001\n12/13/2001\n\nMatch both DMY and MDY\n12/12/1978\n6/6/78\n06/6/1978\n6/06/1978\n\nusing whitespace as a delimiter\n\n13 11 2001\n11 13 2001\n11 13 01 \n13 11 01\n1 1 01\n1 1 2001\n\nYear Month Day order\n76/02/02\n1976/02/29\n1976/2/13\n76/09/31\n\nYYYYMMDD sortable format\n19741213\n19750101\n\nValid dates before Epoch\n12/1/10\n12/01/660\n12/01/00\n12/01/0000\n\nValid date after 2038\n\n01/01/2039\n01/01/39\n\nValid date beyond the year 9999\n\n01/01/10000\n\nDates with leading or trailing characters\n\n12/31/21/\n31/12/1921AD\n31/12/1921.10:55\n12/10/2016 8:26:00.39\nwfuwdf12/11/74iuhwf\nfwefew13/11/1974\n01/12/1974vdwdfwe\n01/01/99werwer\n12321301/01/99\n\nTimes that look like dates\n\n12:13:56\n13:12:01\n1:12:01PM\n1:12:01 AM\n\nDates that runs across two lines\n\n1/12/19\n74\n\n01/12/19\n74/13/1946\n\n31/12/20\n08:13\n\nInvalid, corrupted or nonsense dates\n\n0/1/2001\n1/0/2001\n00/01/2100\n01/0/2001\n0101/2001\n01/131/2001\n31/31/2001\n101/12/1974\n56/56/56\n00/00/0000\n0/0/1999\n12/01/0\n12/10/-100\n74/2/29\n12/32/45\n20/12/194\n\n2/12-73\n</code></pre>\n" }, { "answer_id": 69140085, "author": "Pankkaj", "author_id": 5689392, "author_profile": "https://Stackoverflow.com/users/5689392", "pm_score": 0, "selected": false, "text": "<p><code>/(([1-9]{1}|0[1-9]|1[0-2])\\/(0[1-9]|[1-9]{1}|[12]\\d|3[01])\\/[12]\\d{3})/</code></p>\n<p>This would validate for following -</p>\n<ul>\n<li>Single and 2 digit day with range from 1 to 31. Eg, 1, 01, 11, 31.</li>\n<li>Single and 2 digit month with range from 1 to 12. Eg. 1, 01, 12.</li>\n<li>4 digit year. Eg. 2021, 1980.</li>\n</ul>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
I'm trying to write a regular expression that validates a date. The regex needs to match the following * M/D/YYYY * MM/DD/YYYY * Single digit months can start with a leading zero (eg: 03/12/2008) * Single digit days can start with a leading zero (eg: 3/02/2008) * CANNOT include February 30 or February 31 (eg: 2/31/2008) So far I have ``` ^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ ``` This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008. Does anyone have a better suggestion? **Edit:** I found [the answer](http://regexlib.com/REDetails.aspx?regexp_id=112) on RegExLib ``` ^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ ``` It matches all valid months that follow the MM/DD/YYYY format. Thanks everyone for the help.
This is not an appropriate use of regular expressions. You'd be better off using ``` [0-9]{2}/[0-9]{2}/[0-9]{4} ``` and then checking ranges in a higher-level language.
51,233
<p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
[ { "answer_id": 51240, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": true, "text": "<p>I'll always use <a href=\"http://lxml.de/\" rel=\"nofollow noreferrer\">lxml</a> for such tasks. You could use <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">beautifulsoup</a> as well.</p>\n<pre><code>import lxml.html\nt = lxml.html.parse(url)\nprint(t.find(&quot;.//title&quot;).text)\n</code></pre>\n<p>EDIT based on comment:</p>\n<pre><code>from urllib2 import urlopen\nfrom lxml.html import parse\n\nurl = &quot;https://www.google.com&quot;\npage = urlopen(url)\np = parse(page)\nprint(p.find(&quot;.//title&quot;).text)\n</code></pre>\n" }, { "answer_id": 51242, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>This is probably overkill for such a simple task, but if you plan to do more than that, then it's saner to start from these tools (mechanize, BeautifulSoup) because they are much easier to use than the alternatives (urllib to get content and regexen or some other parser to parse html)</p>\n<p>Links:\n<a href=\"http://crummy.com/software/BeautifulSoup\" rel=\"nofollow noreferrer\">BeautifulSoup</a>\n<a href=\"http://wwwsearch.sourceforge.net/mechanize/\" rel=\"nofollow noreferrer\">mechanize</a></p>\n<pre><code>#!/usr/bin/env python\n#coding:utf-8\n\nfrom bs4 import BeautifulSoup\nfrom mechanize import Browser\n\n#This retrieves the webpage content\nbr = Browser()\nres = br.open(&quot;https://www.google.com/&quot;)\ndata = res.get_data() \n\n#This parses the content\nsoup = BeautifulSoup(data)\ntitle = soup.find('title')\n\n#This outputs the content :)\nprint title.renderContents()\n</code></pre>\n" }, { "answer_id": 51263, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 4, "selected": false, "text": "<p>The mechanize Browser object has a title() method. So the code from <a href=\"https://stackoverflow.com/questions/51233/how-can-i-retrieve-the-page-title-of-a-webpage-using-python#51242\">this post</a> can be rewritten as:</p>\n\n<pre><code>from mechanize import Browser\nbr = Browser()\nbr.open(\"http://www.google.com/\")\nprint br.title()\n</code></pre>\n" }, { "answer_id": 51550, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "<p>Here's a simplified version of <a href=\"https://stackoverflow.com/a/51242/4279\">@Vinko Vrsalovic's answer</a>:</p>\n\n<pre><code>import urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(urllib2.urlopen(\"https://www.google.com\"))\nprint soup.title.string\n</code></pre>\n\n<p>NOTE:</p>\n\n<ul>\n<li><p><em>soup.title</em> finds the first <em>title</em> element <strong>anywhere</strong> in the html document</p></li>\n<li><p><em>title.string</em> assumes it has only <strong>one</strong> child node, and that child node is a <strong>string</strong></p></li>\n</ul>\n\n<p>For <a href=\"http://www.crummy.com/software/BeautifulSoup/bs4/doc/\" rel=\"noreferrer\">beautifulsoup 4.x</a>, use different import:</p>\n\n<pre><code>from bs4 import BeautifulSoup\n</code></pre>\n" }, { "answer_id": 17123979, "author": "Sai Kiriti Badam", "author_id": 2182787, "author_profile": "https://Stackoverflow.com/users/2182787", "pm_score": 2, "selected": false, "text": "<p><code>soup.title.string</code> actually returns a unicode string.\nTo convert that into normal string, you need to do\n<code>string=string.encode('ascii','ignore')</code></p>\n" }, { "answer_id": 36650753, "author": "Finn", "author_id": 4248511, "author_profile": "https://Stackoverflow.com/users/4248511", "pm_score": 4, "selected": false, "text": "<p>Using <a href=\"https://docs.python.org/3.4/library/html.parser.html\" rel=\"noreferrer\">HTMLParser</a>:</p>\n<pre><code>from urllib.request import urlopen\nfrom html.parser import HTMLParser\n\n\nclass TitleParser(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.match = False\n self.title = ''\n\n def handle_starttag(self, tag, attributes):\n self.match = tag == 'title'\n\n def handle_data(self, data):\n if self.match:\n self.title = data\n self.match = False\n\nurl = &quot;http://example.com/&quot;\nhtml_string = str(urlopen(url).read())\n\nparser = TitleParser()\nparser.feed(html_string)\nprint(parser.title) # prints: Example Domain\n</code></pre>\n" }, { "answer_id": 41958005, "author": "Rahul Chawla", "author_id": 6775799, "author_profile": "https://Stackoverflow.com/users/6775799", "pm_score": 5, "selected": false, "text": "<p>No need to import other libraries. Request has this functionality in-built.</p>\n\n<pre><code>&gt;&gt; hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}\n&gt;&gt;&gt; n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)\n&gt;&gt;&gt; al = n.text\n&gt;&gt;&gt; al[al.find('&lt;title&gt;') + 7 : al.find('&lt;/title&gt;')]\nu'Friends (TV Series 1994\\u20132004) - IMDb' \n</code></pre>\n" }, { "answer_id": 44697410, "author": "Finn", "author_id": 4248511, "author_profile": "https://Stackoverflow.com/users/4248511", "pm_score": 3, "selected": false, "text": "<p>Using regular expressions</p>\n\n<pre><code>import re\nmatch = re.search('&lt;title&gt;(.*?)&lt;/title&gt;', raw_html)\ntitle = match.group(1) if match else 'No title'\n</code></pre>\n" }, { "answer_id": 47880739, "author": "Ricky Wilson", "author_id": 2433063, "author_profile": "https://Stackoverflow.com/users/2433063", "pm_score": 2, "selected": false, "text": "<p>Here is a fault tolerant <code>HTMLParser</code> implementation.<br>\nYou can throw pretty much anything at <code>get_title()</code> without it breaking, If anything unexpected happens\n<code>get_title()</code> will return <code>None</code>.<br>\nWhen <code>Parser()</code> downloads the page it encodes it to <code>ASCII</code>\nregardless of the charset used in the page ignoring any errors.\nIt would be trivial to change <code>to_ascii()</code> to convert the data into <code>UTF-8</code> or any other encoding. Just add an encoding argument and rename the function to something like <code>to_encoding()</code>.<br>\nBy default <code>HTMLParser()</code> will break on broken html, it will even break on trivial things like mismatched tags. To prevent this behavior I replaced <code>HTMLParser()</code>'s error method with a function that will ignore the errors.</p>\n\n<pre><code>#-*-coding:utf8;-*-\n#qpy:3\n#qpy:console\n\n''' \nExtract the title from a web page using\nthe standard lib.\n'''\n\nfrom html.parser import HTMLParser\nfrom urllib.request import urlopen\nimport urllib\n\ndef error_callback(*_, **__):\n pass\n\ndef is_string(data):\n return isinstance(data, str)\n\ndef is_bytes(data):\n return isinstance(data, bytes)\n\ndef to_ascii(data):\n if is_string(data):\n data = data.encode('ascii', errors='ignore')\n elif is_bytes(data):\n data = data.decode('ascii', errors='ignore')\n else:\n data = str(data).encode('ascii', errors='ignore')\n return data\n\n\nclass Parser(HTMLParser):\n def __init__(self, url):\n self.title = None\n self.rec = False\n HTMLParser.__init__(self)\n try:\n self.feed(to_ascii(urlopen(url).read()))\n except urllib.error.HTTPError:\n return\n except urllib.error.URLError:\n return\n except ValueError:\n return\n\n self.rec = False\n self.error = error_callback\n\n def handle_starttag(self, tag, attrs):\n if tag == 'title':\n self.rec = True\n\n def handle_data(self, data):\n if self.rec:\n self.title = data\n\n def handle_endtag(self, tag):\n if tag == 'title':\n self.rec = False\n\n\ndef get_title(url):\n return Parser(url).title\n\nprint(get_title('http://www.google.com'))\n</code></pre>\n" }, { "answer_id": 55968979, "author": "markling", "author_id": 2455413, "author_profile": "https://Stackoverflow.com/users/2455413", "pm_score": 0, "selected": false, "text": "<p>Using lxml...</p>\n\n<p>Getting it from page meta tagged according to the Facebook opengraph protocol:</p>\n\n<pre><code>import lxml.html.parse\nhtml_doc = lxml.html.parse(some_url)\n\nt = html_doc.xpath('//meta[@property=\"og:title\"]/@content')[0]\n</code></pre>\n\n<p>or using .xpath with lxml:</p>\n\n<pre><code>t = html_doc.xpath(\".//title\")[0].text\n</code></pre>\n" }, { "answer_id": 56416767, "author": "QHarr", "author_id": 6241235, "author_profile": "https://Stackoverflow.com/users/6241235", "pm_score": 3, "selected": false, "text": "<p>Use soup.select_one to target title tag</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup as bs\n\nr = requests.get('url')\nsoup = bs(r.content, 'lxml')\nprint(soup.select_one('title').text)\n</code></pre>\n" }, { "answer_id": 66234986, "author": "S Habeeb Ullah", "author_id": 12282050, "author_profile": "https://Stackoverflow.com/users/12282050", "pm_score": 2, "selected": false, "text": "<p>In Python3, we can call method <code>urlopen</code> from <code>urllib.request</code> and <code>BeautifulSoup</code> from <code>bs4</code> library to fetch the page title.</p>\n<pre><code>from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nhtml = urlopen(&quot;https://www.google.com&quot;)\nsoup = BeautifulSoup(html, 'lxml')\nprint(soup.title.string)\n</code></pre>\n<p>Here we are using the most efficient parser 'lxml'.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
How can I retrieve the page title of a webpage (title html tag) using Python?
I'll always use [lxml](http://lxml.de/) for such tasks. You could use [beautifulsoup](http://www.crummy.com/software/BeautifulSoup/) as well. ``` import lxml.html t = lxml.html.parse(url) print(t.find(".//title").text) ``` EDIT based on comment: ``` from urllib2 import urlopen from lxml.html import parse url = "https://www.google.com" page = urlopen(url) p = parse(page) print(p.find(".//title").text) ```
51,238
<p>I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.</p> <p>Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?</p>
[ { "answer_id": 51257, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>It's not clear what conditions you're talking about. If you want to set column to default value, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx\" rel=\"nofollow noreferrer\">DbNull.Value</a>;</p>\n\n<pre><code>command.AddWithValue(\"@param\", DbNull.Value);\n\nor\n\ncommand.Parameters.Add(\"@param\", &lt;data type&gt;).Value = DBNull.Value;\n</code></pre>\n" }, { "answer_id": 58277, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 3, "selected": true, "text": "<p>The problem was DBNull, doing:</p>\n\n<pre><code>command.Parameters.AddWithValue(\"@parameter\", null);\n</code></pre>\n\n<p>compiles OK.</p>\n" }, { "answer_id": 4249329, "author": "JYelton", "author_id": 161052, "author_profile": "https://Stackoverflow.com/users/161052", "pm_score": 0, "selected": false, "text": "<p>I usually set values that are intended to be default/blank to null in code, then before executing the query, run the following loop:</p>\n\n<pre><code>foreach(MySqlParameter param in cmd.Parameters)\n if (param.Value == null) param.Value = DBNull.Value;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249/" ]
I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value. Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?
The problem was DBNull, doing: ``` command.Parameters.AddWithValue("@parameter", null); ``` compiles OK.
51,262
<p>How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is.</p>
[ { "answer_id": 52121, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT ELAPSED_TIME_MIN,SUBSTR(AUTHID,1,10) AS AUTH_ID, \nAGENT_ID, APPL_STATUS,SUBSTR(STMT_TEXT,1,20) AS SQL_TEXT\nFROM SYSIBMADM.LONG_RUNNING_SQL\nWHERE ELAPSED_TIME_MIN &gt; 0\nORDER BY ELAPSED_TIME_MIN DESC\n</code></pre>\n\n<p>Credit: <a href=\"http://it.toolbox.com/blogs/db2luw/sql-to-view-long-running-queries-13577\" rel=\"nofollow noreferrer\">SQL to View Long Running Queries </a></p>\n" }, { "answer_id": 80471, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 1, "selected": false, "text": "<p>That's because the suggested answer is for DB2, not Informix.</p>\n\n<p>The sysmaster database (a virtual relational database of Informix shared memory) will probably contain the information you seek. These pages might help you get started:</p>\n\n<ul>\n<li><a href=\"http://docs.rinet.ru/InforSmes/ch22/ch22.htm\" rel=\"nofollow noreferrer\">http://docs.rinet.ru/InforSmes/ch22/ch22.htm</a></li>\n<li><a href=\"http://www.informix.com.ua/articles/sysmast/sysmast.htm\" rel=\"nofollow noreferrer\">http://www.informix.com.ua/articles/sysmast/sysmast.htm</a></li>\n</ul>\n" }, { "answer_id": 117079, "author": "DL Redden", "author_id": 20610, "author_profile": "https://Stackoverflow.com/users/20610", "pm_score": 3, "selected": false, "text": "<p>If the query is currently running watch the <strong>onstat -g act -r 1</strong> output and look for items with an <strong><em>rstcb</em></strong> that is not 0</p>\n\n<pre><code>Running threads:\n tid tcb rstcb prty status vp-class name\n 106 c0000000d4860950 0 2 running 107soc soctcppoll\n 107 c0000000d4881950 0 2 running 108soc soctcppoll\n 564457 c0000000d7f28250 c0000000d7afcf20 2 running 1cpu CDRD_10\n</code></pre>\n\n<p>In this example the third row is what is currently running. If you have multiple rows with non-zero rstcb values then watch for a bit looking for the one that is always or almost always there. That is most likely the session that your looking for.</p>\n\n<p><strong>c0000000d7afcf20</strong> is the address that we're interested in for this example.</p>\n\n<p>Use <strong>onstat -u | grep c0000000d7afcf20</strong> to find the session</p>\n\n<pre><code>c0000000d7afcf20 Y--P--- 22887 informix - c0000000d5b0abd0 0 5 14060 3811\n</code></pre>\n\n<p>This gives you the session id which in our example is <strong>22887</strong>. Use <strong>onstat -g ses 22887</strong>\nto list info about that session. In my example it's a system session so there's nothing to see in the onstat -g ses output.</p>\n" }, { "answer_id": 130694, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 1, "selected": false, "text": "<p>Okay it took me a bit to work out how to connect to sysmaster. The JDBC connection string is:</p>\n\n<blockquote>\n <p>jdbc:informix-sqli://dbserver.local:1526/sysmaster:INFORMIXSERVER=mydatabase</p>\n</blockquote>\n\n<p>Where the port number is the same as when you are connecting to the actual database. That is if your connection string is:</p>\n\n<blockquote>\n <p>jdbc:informix-sqli://database:1541/crm:INFORMIXSERVER=crmlive</p>\n</blockquote>\n\n<p>Then the sysmaster connection string is:</p>\n\n<blockquote>\n <p>jdbc:informix-sqli://database:1541/sysmaster:INFORMIXSERVER=crmlive</p>\n</blockquote>\n\n<p>Also found <a href=\"http://www.informixfaq.com/wiki/doku.php/wiki:sysmaster\" rel=\"nofollow noreferrer\">this wiki page</a> that contains a number of SQL queries for operating on the sysmaster tables.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is.
If the query is currently running watch the **onstat -g act -r 1** output and look for items with an ***rstcb*** that is not 0 ``` Running threads: tid tcb rstcb prty status vp-class name 106 c0000000d4860950 0 2 running 107soc soctcppoll 107 c0000000d4881950 0 2 running 108soc soctcppoll 564457 c0000000d7f28250 c0000000d7afcf20 2 running 1cpu CDRD_10 ``` In this example the third row is what is currently running. If you have multiple rows with non-zero rstcb values then watch for a bit looking for the one that is always or almost always there. That is most likely the session that your looking for. **c0000000d7afcf20** is the address that we're interested in for this example. Use **onstat -u | grep c0000000d7afcf20** to find the session ``` c0000000d7afcf20 Y--P--- 22887 informix - c0000000d5b0abd0 0 5 14060 3811 ``` This gives you the session id which in our example is **22887**. Use **onstat -g ses 22887** to list info about that session. In my example it's a system session so there's nothing to see in the onstat -g ses output.
51,264
<p>What object do you query against to select all the table names in a schema in Oracle?</p>
[ { "answer_id": 51265, "author": "jatanp", "author_id": 959, "author_profile": "https://Stackoverflow.com/users/959", "pm_score": -1, "selected": false, "text": "<p>You may use:</p>\n\n<pre><code>select tabname from tabs \n</code></pre>\n\n<p>to get the name of tables present in schema.</p>\n" }, { "answer_id": 51267, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 1, "selected": false, "text": "<p>you're looking for:</p>\n\n<pre>\nselect table_name from user_tables;\n</pre>\n" }, { "answer_id": 51285, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 4, "selected": true, "text": "<p>To see all the tables you have access to</p>\n\n<pre><code>select table_name from all_tables where owner='&lt;SCHEMA&gt;';\n</code></pre>\n\n<p>To select all tables for the current logged in schema (eg, your tables)</p>\n\n<pre><code>select table_name from user_tables;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
What object do you query against to select all the table names in a schema in Oracle?
To see all the tables you have access to ``` select table_name from all_tables where owner='<SCHEMA>'; ``` To select all tables for the current logged in schema (eg, your tables) ``` select table_name from user_tables; ```
51,269
<p>I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class</p> <pre><code>public class UserInfo { [Category("change me!")] public int Age { get; set; } [Category("change me!")] public string Name { get; set; } } </code></pre> <p>This is a class that is provided by a third party vendor and <strong>I can't change the code</strong>. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.</p> <p>May I know how to do this?</p>
[ { "answer_id": 51278, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 0, "selected": false, "text": "<p>I really don't think so, unless there's some funky reflection that can pull it off. The property decorations are set at compile time and to my knowledge are fixed</p>\n" }, { "answer_id": 51282, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 5, "selected": false, "text": "<p>Well you learn something new every day, apparently I lied:</p>\n\n<blockquote>\n <p>What isn’t generally realised is that\n you can change attribute <strong>instance</strong> values fairly\n easily at runtime. The reason is, of\n course, that the instances of the\n attribute classes that are created are\n perfectly normal objects and can be\n used without restriction. For example,\n we can get the object:</p>\n\n<pre><code>ASCII[] attrs1=(ASCII[])\n typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);\n</code></pre>\n \n <p>…change the value of its public variable and show that it has changed:</p>\n\n<pre><code>attrs1[0].MyData=\"A New String\";\nMessageBox.Show(attrs1[0].MyData);\n</code></pre>\n \n <p>…and finally create another instance\n and show that its value is unchanged:</p>\n\n<pre><code>ASCII[] attrs3=(ASCII[])\n typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);\n MessageBox.Show(attrs3[0].MyData);\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://www.vsj.co.uk/articles/display.asp?id=713\" rel=\"noreferrer\">http://www.vsj.co.uk/articles/display.asp?id=713</a></p>\n" }, { "answer_id": 276135, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 2, "selected": false, "text": "<p>Did you solve the problem?</p>\n\n<p>Here are possible steps to achieve an acceptable solution. </p>\n\n<ol>\n<li>Try to create a child class, redefine all of the properties that you need to change the <code>[Category]</code> attribute (mark them with <code>new</code>). Example:</li>\n</ol>\n\n<blockquote>\n<pre><code>public class UserInfo\n{\n [Category(\"Must change\")]\n public string Name { get; set; }\n}\n\npublic class NewUserInfo : UserInfo\n{\n public NewUserInfo(UserInfo user)\n {\n // transfer all the properties from user to current object\n }\n\n [Category(\"Changed\")]\n public new string Name {\nget {return base.Name; }\nset { base.Name = value; }\n }\n\npublic static NewUserInfo GetNewUser(UserInfo user)\n{\nreturn NewUserInfo(user);\n}\n}\n\nvoid YourProgram()\n{\nUserInfo user = new UserInfo();\n...\n\n// Bind propertygrid to object\n\ngrid.DataObject = NewUserInfo.GetNewUser(user);\n\n...\n\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Later Edit:</strong> <em>This part of the solution is not workable if you have a large number of properties that you might need to rewrite the attributes. This is where part two comes into place:</em></p>\n\n<ol start=\"2\">\n<li>Of course, this won't help if the class is not inheritable, or if you have a lot of objects (and properties). You would need to create a full automatic proxy class that gets your class and creates a dynamic class, applies attributes and of course makes a connection between the two classes.. This is a little more complicated, but also achievable. Just use reflection and you're on the right road.</li>\n</ol>\n" }, { "answer_id": 1152895, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>In the mean time I've come to a partial solution, derived from the following articles:</p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163816.aspx\" rel=\"nofollow noreferrer\">ICustomTypeDescriptor, Part 1</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163804.aspx\" rel=\"nofollow noreferrer\">ICustomTypeDescriptor, Part 2</a></li>\n<li><a href=\"http://www.codeproject.com/KB/tabs/Dynamic_Propertygrid.aspx\" rel=\"nofollow noreferrer\">Add (Remove) Items to (from) PropertyGrid at Runtime</a></li>\n</ol>\n\n<p>Basically you would create a generic class <code>CustomTypeDescriptorWithResources&lt;T&gt;</code>, that would get the properties through reflection and load <code>Description</code> and <code>Category</code> from a file (I suppose you need to display localized text so you could use a resources file (<code>.resx</code>))</p>\n" }, { "answer_id": 1839628, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>You can subclass most of the common attributes quite easily to provide this extensibility:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nclass MyCategoryAttribute : CategoryAttribute {\n public MyCategoryAttribute(string categoryKey) : base(categoryKey) { }\n\n protected override string GetLocalizedString(string value) {\n return \"Whad'ya know? \" + value;\n }\n}\n\nclass Person {\n [MyCategory(\"Personal\"), DisplayName(\"Date of Birth\")]\n public DateTime DateOfBirth { get; set; }\n}\n\nstatic class Program {\n [STAThread]\n static void Main() {\n Application.EnableVisualStyles();\n Application.Run(new Form { Controls = {\n new PropertyGrid { Dock = DockStyle.Fill,\n SelectedObject = new Person { DateOfBirth = DateTime.Today}\n }}});\n }\n}\n</code></pre>\n\n<p>There are more complex options that involve writing custom <code>PropertyDescriptor</code>s, exposed via <code>TypeConverter</code>, <code>ICustomTypeDescriptor</code> or <code>TypeDescriptionProvider</code> - but that is usually overkill.</p>\n" }, { "answer_id": 2114049, "author": "Jules", "author_id": 120399, "author_profile": "https://Stackoverflow.com/users/120399", "pm_score": 3, "selected": false, "text": "<p>In case anyone else walks down this avenue, the answer is you can do it, with reflection, except you can't because there's a bug in the framework. Here's how you would do it:</p>\n\n<pre><code>Dim prop As PropertyDescriptor = TypeDescriptor.GetProperties(GetType(UserInfo))(\"Age\")\nDim att As CategoryAttribute = DirectCast(prop.Attributes(GetType(CategoryAttribute)), CategoryAttribute)\nDim cat As FieldInfo = att.GetType.GetField(\"categoryValue\", BindingFlags.NonPublic Or BindingFlags.Instance)\ncat.SetValue(att, \"A better description\")\n</code></pre>\n\n<p>All well and good, except that the category attribute is changed for all the properties, not just 'Age'.</p>\n" }, { "answer_id": 10541471, "author": "David MacDermot", "author_id": 1388044, "author_profile": "https://Stackoverflow.com/users/1388044", "pm_score": 1, "selected": false, "text": "<p>Given that the PropertyGrid's selected item is \"Age\":</p>\n\n<pre><code>SetCategoryLabelViaReflection(MyPropertyGrid.SelectedGridItem.Parent,\n MyPropertyGrid.SelectedGridItem.Parent.Label, \"New Category Label\");\n</code></pre>\n\n<p>Where <code>SetCategoryLabelViaReflection()</code> is defined as follows:</p>\n\n<pre><code>private void SetCategoryLabelViaReflection(GridItem category,\n string oldCategoryName,\n string newCategoryName)\n{\n try\n {\n Type t = category.GetType();\n FieldInfo f = t.GetField(\"name\",\n BindingFlags.NonPublic | BindingFlags.Instance);\n if (f.GetValue(category).Equals(oldCategoryName))\n {\n f.SetValue(category, newCategoryName);\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Trace.Write(\"Failed Renaming Category: \" + ex.ToString());\n }\n}\n</code></pre>\n\n<p>As far as programatically setting the selected item, the parent category of which you wish to change; there are a number of simple solutions. Google \"Set Focus to a specific PropertyGrid property\".</p>\n" }, { "answer_id": 19787957, "author": "mmm", "author_id": 2922477, "author_profile": "https://Stackoverflow.com/users/2922477", "pm_score": -1, "selected": false, "text": "<p>You can change Attribute values at runtime at Class level (not object):</p>\n\n<pre><code>var attr = TypeDescriptor.GetProperties(typeof(UserContact))[\"UserName\"].Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;\nattr.GetType().GetField(\"isReadOnly\", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(attr, username_readonly);\n</code></pre>\n" }, { "answer_id": 25254059, "author": "Darien Pardinas", "author_id": 1416294, "author_profile": "https://Stackoverflow.com/users/1416294", "pm_score": 2, "selected": false, "text": "<p>Unfortunately attributes are not meant to change at runtime. You basically have two options:</p>\n\n<ol>\n<li><p>Recreate a similar type on the fly using <code>System.Reflection.Emit</code> as shown below.</p></li>\n<li><p>Ask your vendor to add this functionality. If you are using Xceed.WpfToolkit.Extended you can download the source code from <a href=\"https://wpftoolkit.codeplex.com/SourceControl/latest\" rel=\"nofollow\">here</a> and easily implement an interface like <code>IResolveCategoryName</code> that would resolve the attribute at runtime. I did a bit more than that, it was pretty easy to add more functionality like limits when editing a numeric value in a <code>DoubleUpDown</code> inside the <code>PropertyGrid</code>, etc.</p>\n\n<pre><code>namespace Xceed.Wpf.Toolkit.PropertyGrid\n{\n public interface IPropertyDescription\n {\n double MinimumFor(string propertyName);\n double MaximumFor(string propertyName);\n double IncrementFor(string propertyName);\n int DisplayOrderFor(string propertyName);\n string DisplayNameFor(string propertyName);\n string DescriptionFor(string propertyName);\n bool IsReadOnlyFor(string propertyName);\n }\n}\n</code></pre></li>\n</ol>\n\n<p>For first option: This however lack of proper property binding to reflect the result back to the actual object being edited.</p>\n\n<pre><code> private static void CreatePropertyAttribute(PropertyBuilder propertyBuilder, Type attributeType, Array parameterValues)\n {\n var parameterTypes = (from object t in parameterValues select t.GetType()).ToArray();\n ConstructorInfo propertyAttributeInfo = typeof(RangeAttribute).GetConstructor(parameterTypes);\n if (propertyAttributeInfo != null)\n {\n var customAttributeBuilder = new CustomAttributeBuilder(propertyAttributeInfo,\n parameterValues.Cast&lt;object&gt;().ToArray());\n propertyBuilder.SetCustomAttribute(customAttributeBuilder);\n }\n }\n private static PropertyBuilder CreateAutomaticProperty(TypeBuilder typeBuilder, PropertyInfo propertyInfo)\n {\n string propertyName = propertyInfo.Name;\n Type propertyType = propertyInfo.PropertyType;\n\n // Generate a private field\n FieldBuilder field = typeBuilder.DefineField(\"_\" + propertyName, propertyType, FieldAttributes.Private);\n\n // Generate a public property\n PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType,\n null);\n\n // The property set and property get methods require a special set of attributes:\n const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;\n\n // Define the \"get\" accessor method for current private field.\n MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod(\"get_\" + propertyName, getSetAttr, propertyType, Type.EmptyTypes);\n\n // Intermediate Language stuff...\n ILGenerator currGetIl = currGetPropMthdBldr.GetILGenerator();\n currGetIl.Emit(OpCodes.Ldarg_0);\n currGetIl.Emit(OpCodes.Ldfld, field);\n currGetIl.Emit(OpCodes.Ret);\n\n // Define the \"set\" accessor method for current private field.\n MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod(\"set_\" + propertyName, getSetAttr, null, new[] { propertyType });\n\n // Again some Intermediate Language stuff...\n ILGenerator currSetIl = currSetPropMthdBldr.GetILGenerator();\n currSetIl.Emit(OpCodes.Ldarg_0);\n currSetIl.Emit(OpCodes.Ldarg_1);\n currSetIl.Emit(OpCodes.Stfld, field);\n currSetIl.Emit(OpCodes.Ret);\n\n // Last, we must map the two methods created above to our PropertyBuilder to \n // their corresponding behaviors, \"get\" and \"set\" respectively. \n property.SetGetMethod(currGetPropMthdBldr);\n property.SetSetMethod(currSetPropMthdBldr);\n\n return property;\n\n }\n\n public static object EditingObject(object obj)\n {\n // Create the typeBuilder\n AssemblyName assembly = new AssemblyName(\"EditingWrapper\");\n AppDomain appDomain = System.Threading.Thread.GetDomain();\n AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);\n ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assembly.Name);\n\n // Create the class\n TypeBuilder typeBuilder = moduleBuilder.DefineType(\"EditingWrapper\",\n TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass |\n TypeAttributes.BeforeFieldInit, typeof(System.Object));\n\n Type objType = obj.GetType();\n foreach (var propertyInfo in objType.GetProperties())\n {\n string propertyName = propertyInfo.Name;\n Type propertyType = propertyInfo.PropertyType;\n\n // Create an automatic property\n PropertyBuilder propertyBuilder = CreateAutomaticProperty(typeBuilder, propertyInfo);\n\n // Set Range attribute\n CreatePropertyAttribute(propertyBuilder, typeof(Category), new[]{\"My new category value\"});\n\n }\n\n // Generate our type\n Type generetedType = typeBuilder.CreateType();\n\n // Now we have our type. Let's create an instance from it:\n object generetedObject = Activator.CreateInstance(generetedType);\n\n return generetedObject;\n }\n}\n</code></pre>\n" }, { "answer_id": 41679916, "author": "mbomb007", "author_id": 2415524, "author_profile": "https://Stackoverflow.com/users/2415524", "pm_score": 1, "selected": false, "text": "<p>Here's a \"cheaty\" way to do it: </p>\n\n<p>If you have a fixed number of constant potential values for the attribute parameter, you can define a separate property for each potential value of the parameter (and give each property that slightly different attribute), then switch which property you reference dynamically.</p>\n\n<p>In VB.NET, it might look like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Property Time As Date\n\n&lt;Display(Name:=\"Month\")&gt;\nReadOnly Property TimeMonthly As Date\n Get\n Return Time\n End Get\nEnd Property\n\n&lt;Display(Name:=\"Quarter\")&gt;\nReadOnly Property TimeQuarterly As Date\n Get\n Return Time\n End Get\nEnd Property\n\n&lt;Display(Name:=\"Year\")&gt;\nReadOnly Property TimeYearly As Date\n Get\n Return Time\n End Get\nEnd Property\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class ``` public class UserInfo { [Category("change me!")] public int Age { get; set; } [Category("change me!")] public string Name { get; set; } } ``` This is a class that is provided by a third party vendor and **I can't change the code**. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid. May I know how to do this?
Well you learn something new every day, apparently I lied: > > What isn’t generally realised is that > you can change attribute **instance** values fairly > easily at runtime. The reason is, of > course, that the instances of the > attribute classes that are created are > perfectly normal objects and can be > used without restriction. For example, > we can get the object: > > > > ``` > ASCII[] attrs1=(ASCII[]) > typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); > > ``` > > …change the value of its public variable and show that it has changed: > > > > ``` > attrs1[0].MyData="A New String"; > MessageBox.Show(attrs1[0].MyData); > > ``` > > …and finally create another instance > and show that its value is unchanged: > > > > ``` > ASCII[] attrs3=(ASCII[]) > typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); > MessageBox.Show(attrs3[0].MyData); > > ``` > > <http://www.vsj.co.uk/articles/display.asp?id=713>
51,320
<p>For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.</p> <p>I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).</p> <p>Any help?</p> <p><strong>EDIT:</strong> I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.</p>
[ { "answer_id": 51327, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": -1, "selected": false, "text": "<p>Of course there is a <code>PATH</code> environment variable <a href=\"http://en.wikipedia.org/wiki/Environment_variable#System_path_variables\" rel=\"nofollow noreferrer\">in Windows</a>.</p>\n\n<blockquote>\n <blockquote>\n <p><code>%PATH%</code>\n This variable contains a semicolon-delimited list of directories in which the command interpreter will search for executable files. Equivalent to the UNIX $PATH variable.</p>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 51330, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>Windows does indeed have a PATH environment variable. It has a different syntax from the Unix one because it uses semicolon (;) as a separator instead of colon (:) and you have to watch for quoted strings that might contain spaces. But, it's there.</p>\n\n<p>If this other program's installer adds its own directory to the PATH environment variable, then you could rely on that. However, as you mention, Windows installers typically do not need to add the application path to the PATH because they install a start menu shortcut or something else instead.</p>\n\n<p>For drive letters in Java, one approach would be to try them all, there are only going to be at most 24 (C through Z) that are of any use. Or, you could shell out and run \"net use\" and parse the results, though that is a bit messier.</p>\n" }, { "answer_id": 51331, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()\" rel=\"noreferrer\">http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()</a></p>\n\n<pre><code>File[] roots = File.listRoots();\nfor(int i = 0; i &lt; roots.length ; i++)\n System.out.println(\"Root[\"+i+\"]:\" + roots[i]);\n</code></pre>\n\n<p>google: list drives java, first hit:-)</p>\n" }, { "answer_id": 255980, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 2, "selected": false, "text": "<p>Looking \"everywhere\" can be very messy.</p>\n\n<p>Look at a CD-rom drive, and it spins up. That can be very noisy.</p>\n\n<p>Look at a network drive, and it may be very slow. Maybe the server is down, and you may need to wait for minutes until it times out.</p>\n\n<p>Maybe (for Windows-machines) you should just look in the start-menu. If nothing there points at OOo, it's probably not installed. If it is, the user is probably an advanced user, that will have no problems pointing out the location manually.</p>\n" }, { "answer_id": 2092379, "author": "Defd", "author_id": 250777, "author_profile": "https://Stackoverflow.com/users/250777", "pm_score": -1, "selected": false, "text": "<p>Use JNI.\nThis is perfect for c++ code. \nNot only you can list all drives but also get the corresponding drive type (removable,local disk, or cd-rom,dvd-rom...etc)</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018/" ]
For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows. I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it). Any help? **EDIT:** I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.
<http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()> ``` File[] roots = File.listRoots(); for(int i = 0; i < roots.length ; i++) System.out.println("Root["+i+"]:" + roots[i]); ``` google: list drives java, first hit:-)
51,339
<p>I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:</p> <pre><code>SELECT f.* FROM Foo f WHERE f.FooId IN ( SELECT fb.FooId FROM FooBar fb WHERE fb.BarId = 1000 ) </code></pre> <p>Any help would be gratefully received.</p>
[ { "answer_id": 51345, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>Try using two separate steps:</p>\n\n<pre><code>// create a Dictionary / Set / Collection fids first\nvar fids = (from fb in FooBar\n where fb.BarID = 1000\n select new { fooID = fb.FooID, barID = fb.BarID })\n .ToDictionary(x =&gt; x.fooID, x =&gt; x.barID);\n\nfrom f in Foo\nwhere fids.HasKey(f.FooId)\nselect f\n</code></pre>\n" }, { "answer_id": 51346, "author": "NakedBrunch", "author_id": 3742, "author_profile": "https://Stackoverflow.com/users/3742", "pm_score": 2, "selected": false, "text": "<pre><code>from f in Foo\n where f.FooID ==\n (\n FROM fb in FooBar\n WHERE fb.BarID == 1000\n select fb.FooID\n\n )\n select f;\n</code></pre>\n" }, { "answer_id": 51354, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>var fooids = from fb in foobar where fb.BarId=1000 select fb.fooID\nvar ff = from f in foo where f.FooID = fooids select f\n</code></pre>\n" }, { "answer_id": 51400, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 7, "selected": true, "text": "<p>Have a look at <a href=\"http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql\" rel=\"noreferrer\">this article</a>. Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating:</p>\n\n<pre><code>var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;\nvar result = from f in Foo where innerQuery.Contains(f.FooId) select f;</code></pre>\n" }, { "answer_id": 51417, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<h1>General way to implement IN in LINQ to SQL</h1>\n\n<pre><code>var q = from t1 in table1\n let t2s = from t2 in table2\n where &lt;Conditions for table2&gt;\n select t2.KeyField\n where t2s.Contains(t1.KeyField)\n select t1;\n</code></pre>\n\n<h1>General way to implement EXISTS in LINQ to SQL</h1>\n\n<pre><code>var q = from t1 in table1\n let t2s = from t2 in table2\n where &lt;Conditions for table2&gt;\n select t2.KeyField\n where t2s.Any(t1.KeyField)\n select t1;\n</code></pre>\n" }, { "answer_id": 65218, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<pre><code>var foos = Foo.Where&lt;br&gt;\n( f =&gt; FooBar.Where(fb.BarId == 1000).Select(fb =&gt; fb.FooId).Contains(f.FooId));\n</code></pre>\n" }, { "answer_id": 1088069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>// create a Dictionary / Set / Collection fids first</p>\n\n<p><a href=\"http://www.doyouknow.in/How.aspx\" rel=\"nofollow noreferrer\">Find Other Artilces</a></p>\n\n<pre><code>var fids = (from fb in FooBar\n where fb.BarID = 1000\n select new { fooID = fb.FooID, barID = fb.BarID })\n .ToDictionary(x =&gt; x.fooID, x =&gt; x.barID);\n\nfrom f in Foo\nwhere fids.HasKey(f.FooId)\nselect f\n</code></pre>\n" }, { "answer_id": 1088178, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>// create a Dictionary / Set / Collection fids first</p>\n\n<p><a href=\"http://www.doyouknow.in/DoYouKnow/How.aspx\" rel=\"nofollow noreferrer\">Find Other Artilces</a></p>\n\n<pre><code>var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x =&gt; x.fooID, x =&gt; x.barID);\n\nfrom f in Foo where fids.HasKey(f.FooId) select f\n</code></pre>\n" }, { "answer_id": 8968391, "author": "Mox Shah", "author_id": 1107638, "author_profile": "https://Stackoverflow.com/users/1107638", "pm_score": 0, "selected": false, "text": "<pre><code>from f in foo\nwhere f.FooID equals model.FooBar.SingleOrDefault(fBar =&gt; fBar.barID = 1000).FooID\nselect new\n{\nf.Columns\n};\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1904/" ]
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL: ``` SELECT f.* FROM Foo f WHERE f.FooId IN ( SELECT fb.FooId FROM FooBar fb WHERE fb.BarId = 1000 ) ``` Any help would be gratefully received.
Have a look at [this article](http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql). Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating: ``` var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId; var result = from f in Foo where innerQuery.Contains(f.FooId) select f; ```
51,352
<p>I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.</p> <p>What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this. </p> <p>I've been doing this via JavaScript, which works so far, using the following code</p> <pre><code>document.getElementById('chart').src = '/charts/10.png'; </code></pre> <p>The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.</p> <p>What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it. </p> <p>I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image. </p> <p>A good suggestion I've had is to use the following</p> <pre><code>&lt;img src="/charts/10.png" lowsrc="/spinner.gif"/&gt; </code></pre> <p>Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.</p> <p>Any other ideas?</p>
[ { "answer_id": 51360, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 1, "selected": false, "text": "<p>put the spinner in a div the same size as the chart, you know the height and width so you can use relative positioning to center it correctly.</p>\n" }, { "answer_id": 51368, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": false, "text": "<p>Use the power of the setTimeout() function (<a href=\"http://www.w3schools.com/js/js_timing.asp\" rel=\"nofollow noreferrer\">More info</a>) - this allows you set a timer to trigger a function call in the future, and calling it <strong>won't</strong> block execution of the current / other functions (async.).</p>\n\n<p>Position a div containing the spinner above the chart image, with it's css display attribute set to none:</p>\n\n<pre><code>&lt;div&gt;&amp;nbsp;&lt;img src=\"spinner.gif\" id=\"spinnerImg\" style=\"display: none;\" /&gt;&lt;/div&gt;\n</code></pre>\n\n<p><em>The nbsp stop the div collapsing when the spinner is hidden. Without it, when you toggle display of the spinner, your layout will \"twitch\"</em></p>\n\n<pre><code>function chartOnClick() {\n //How long to show the spinner for in ms (eg 3 seconds)\n var spinnerShowTime = 3000\n\n //Show the spinner\n document.getElementById('spinnerImg').style.display = \"\";\n\n //Change the chart src\n document.getElementById('chart').src = '/charts/10.png';\n\n //Set the timeout on the spinner\n setTimeout(\"hideSpinner()\", spinnerShowTime);\n}\n\nfunction hideSpinner() {\n document.getElementById('spinnerImg').style.display = \"none\";\n}\n</code></pre>\n" }, { "answer_id": 51384, "author": "Chris Roberts", "author_id": 475, "author_profile": "https://Stackoverflow.com/users/475", "pm_score": -1, "selected": false, "text": "<p>@iAn's solution looks good to me. The only thing I'd change is instead of using setTimeout, I'd try and hook into the images 'Load' event. This way, if the image takes longer than 3 seconds to download, you'll still get the spinner.</p>\n\n<p>On the other hand, if it takes less time to download, you'll get the spinner for less than 3 seconds.</p>\n" }, { "answer_id": 52597, "author": "Ed Haber", "author_id": 2926, "author_profile": "https://Stackoverflow.com/users/2926", "pm_score": 6, "selected": true, "text": "<p>I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.</p>\n\n<pre><code>function PreloadImage(imgSrc, callback){\n var objImagePreloader = new Image();\n\n objImagePreloader.src = imgSrc;\n if(objImagePreloader.complete){\n callback();\n objImagePreloader.onload=function(){};\n }\n else{\n objImagePreloader.onload = function() {\n callback();\n // clear onLoad, IE behaves irratically with animated gifs otherwise\n objImagePreloader.onload=function(){};\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 52605, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "<p>You could show a static image that gives the <a href=\"http://www.ritsumei.ac.jp/~akitaoka/saishin-e.html\" rel=\"noreferrer\">optical illusion of a spinny-wheel, like these</a>.</p>\n" }, { "answer_id": 55265, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 1, "selected": false, "text": "<p>Aside from the lowsrc option, I've also used a <code>background-image</code> on the <code>img</code>'s container.</p>\n" }, { "answer_id": 1459989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Use CSS to set the loading animation as a centered background-image for the image's container.</p>\n\n<p>Then when loading the new large image, first set the src to a preloaded transparent 1 pixel gif.</p>\n\n<p>e.g.</p>\n\n<pre>\ndocument.getElementById('mainimg').src = '/images/1pix.gif';\ndocument.getElementById('mainimg').src = '/images/large_image.jpg';\n</pre>\n\n<p>While the large_image.jpg is loading, the background will show through the 1pix transparent gif.</p>\n" }, { "answer_id": 1674311, "author": "Svetoslav Marinov", "author_id": 86771, "author_profile": "https://Stackoverflow.com/users/86771", "pm_score": -1, "selected": false, "text": "<p>I would add some random digits to avoid the browser cache.</p>\n" }, { "answer_id": 2902494, "author": "4AM", "author_id": 206552, "author_profile": "https://Stackoverflow.com/users/206552", "pm_score": 2, "selected": false, "text": "<p>Building on Ed's answer, I would prefer to see something like:</p>\n\n<pre><code>function PreLoadImage( srcURL, callback, errorCallback ) {\n var thePic = new Image();\n\n thePic.onload = function() {\n callback();\n thePic.onload = function(){};\n }\n\n thePic.onerror = function() {\n errorCallback();\n }\n thePic.src = srcURL;\n}\n</code></pre>\n\n<p>Your callback can display the image in its proper place and dispose/hide of a spinner, and the errorCallback prevents your page from \"beachballing\". All event driven, no timers or polling, plus you don't have to add the additional if statements to check if the image completed loading while you where setting up your events - since they're set up beforehand they'll trigger regardless of how quickly the images loads.</p>\n" }, { "answer_id": 3083558, "author": "Christoph", "author_id": 372034, "author_profile": "https://Stackoverflow.com/users/372034", "pm_score": 1, "selected": false, "text": "<p>Be aware that the callback function is also called if the image src doesn't exist (http 404 error). To avoid this you can check the width of the image, like:</p>\n\n<pre><code>if(this.width == 0) return false;\n</code></pre>\n" }, { "answer_id": 5994193, "author": "crispy", "author_id": 231529, "author_profile": "https://Stackoverflow.com/users/231529", "pm_score": 4, "selected": false, "text": "<p>Using the <strong>load()</strong> method of <strong>jQuery</strong>, it is easily possible to do something as soon as an image is loaded:</p>\n\n<pre><code>$('img.example').load(function() {\n $('#spinner').fadeOut();\n});\n</code></pre>\n\n<p>See: <a href=\"http://api.jquery.com/load-event/\" rel=\"noreferrer\">http://api.jquery.com/load-event/</a></p>\n" }, { "answer_id": 7624654, "author": "BC.", "author_id": 54838, "author_profile": "https://Stackoverflow.com/users/54838", "pm_score": 2, "selected": false, "text": "<p>I like @duddle's jquery method but find that load() isn't always called (such as when the image is retrieved from cache in IE). I use this version instead:</p>\n<pre><code>$('img.example').one('load', function() {\n $('#spinner').remove();\n}).each(function() {\n if(this.complete) {\n $(this).trigger('load');\n }\n});\n</code></pre>\n<p>This calls load at most one time and immediately if it's already completed loading.</p>\n" }, { "answer_id": 13538873, "author": "denysonique", "author_id": 569061, "author_profile": "https://Stackoverflow.com/users/569061", "pm_score": 2, "selected": false, "text": "<p>Some time ago I have written a jQuery plugin which handles displaying a spinner automatically <a href=\"http://denysonique.github.com/imgPreload/\" rel=\"nofollow\">http://denysonique.github.com/imgPreload/</a></p>\n\n<p>Looking in to its source code should help you with detecting when to display the spinner and with displaying it in the centre of the loaded image.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3847/" ]
I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page. What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this. I've been doing this via JavaScript, which works so far, using the following code ``` document.getElementById('chart').src = '/charts/10.png'; ``` The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond. What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it. I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image. A good suggestion I've had is to use the following ``` <img src="/charts/10.png" lowsrc="/spinner.gif"/> ``` Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed. Any other ideas?
I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback. ``` function PreloadImage(imgSrc, callback){ var objImagePreloader = new Image(); objImagePreloader.src = imgSrc; if(objImagePreloader.complete){ callback(); objImagePreloader.onload=function(){}; } else{ objImagePreloader.onload = function() { callback(); // clear onLoad, IE behaves irratically with animated gifs otherwise objImagePreloader.onload=function(){}; } } } ```
51,407
<p>I want to load a desktop application, via reflection, as a Control inside another application.</p> <p>The application I'm reflecting is a legacy one - I can't make changes to it.</p> <p>I can dynamically access the Form, but can't load it as a Control.</p> <p>In .Net Form expands on Control, and I can assign the reflected Form as a Control, but it throws a run-time exception.</p> <p>Forms cannot be loaded as controls.</p> <p>Is there any way to convert the form to a control? </p>
[ { "answer_id": 51428, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 1, "selected": false, "text": "<p>You should be able to add the form to the controls collection of your parent form...</p>\n\n<p>See here: \n<a href=\"http://vbcity.com/forums/topic.asp?tid=30539\" rel=\"nofollow noreferrer\"><a href=\"http://vbcity.com/forums/topic.asp?tid=30539\" rel=\"nofollow noreferrer\">http://vbcity.com/forums/topic.asp?tid=30539</a></a></p>\n\n<p>If that fails, try using the adapter pattern to create a container with your legacy form inside it, then load it in an MDI maybe?</p>\n" }, { "answer_id": 51433, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 4, "selected": true, "text": "<p>Yes, this works just fine. I'm working on a .NET app right now that loads forms into a panel on a host form.</p>\n\n<p>The relevant snippet:</p>\n\n<pre><code>// setup the new form\nform.TopLevel = false;\nform.FormBorderStyle = FormBorderStyle.None;\nform.Dock = DockStyle.Fill;\nform.Show ( );\n\n// add to the panel's list of child controls\npanelFormHost.Controls.Add ( form );\n</code></pre>\n" }, { "answer_id": 51437, "author": "dan gibson", "author_id": 4495, "author_profile": "https://Stackoverflow.com/users/4495", "pm_score": 1, "selected": false, "text": "<p>What is the exception you get? Is it possible that the control itself is giving the exception (vs the framework)? Perhaps something is called in the original applications Main function that is not being called?</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
I want to load a desktop application, via reflection, as a Control inside another application. The application I'm reflecting is a legacy one - I can't make changes to it. I can dynamically access the Form, but can't load it as a Control. In .Net Form expands on Control, and I can assign the reflected Form as a Control, but it throws a run-time exception. Forms cannot be loaded as controls. Is there any way to convert the form to a control?
Yes, this works just fine. I'm working on a .NET app right now that loads forms into a panel on a host form. The relevant snippet: ``` // setup the new form form.TopLevel = false; form.FormBorderStyle = FormBorderStyle.None; form.Dock = DockStyle.Fill; form.Show ( ); // add to the panel's list of child controls panelFormHost.Controls.Add ( form ); ```
51,412
<p>Say I have the following methods:</p> <pre><code>def methodA(arg, **kwargs): pass def methodB(arg, *args, **kwargs): pass </code></pre> <p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p> <pre><code>def methodA(arg, **kwargs): methodB("argvalue", kwargs) </code></pre> <p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
[ { "answer_id": 51414, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 1, "selected": false, "text": "<p>Some experimentation and I figured this one out:</p>\n\n<p>def methodA(arg, **kwargs):\n methodB(\"argvalue\", **kwargs)</p>\n\n<p>Seems obvious now...</p>\n" }, { "answer_id": 51415, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 6, "selected": true, "text": "<p>Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.</p>\n\n<pre><code>methodB(\"argvalue\", **kwargs)\n</code></pre>\n" }, { "answer_id": 63943, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 2, "selected": false, "text": "<p>As an aside: When using functions instead of methods, you could also use functools.partial:</p>\n\n<pre><code>import functools\n\ndef foo(arg, **kwargs):\n ...\n\nbar = functools.partial(foo, \"argvalue\")\n</code></pre>\n\n<p>The last line will define a function \"bar\" that, when called, will call foo with the first argument set to \"argvalue\" and all other functions just passed on:</p>\n\n<pre><code>bar(5, myarg=\"value\")\n</code></pre>\n\n<p>will call</p>\n\n<pre><code>foo(\"argvalue\", 5, myarg=\"value\")\n</code></pre>\n\n<p>Unfortunately that will not work with methods.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
Say I have the following methods: ``` def methodA(arg, **kwargs): pass def methodB(arg, *args, **kwargs): pass ``` In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define `methodA` as follows, the second argument will be passed on as positional rather than named variable arguments. ``` def methodA(arg, **kwargs): methodB("argvalue", kwargs) ``` How do I make sure that the \*\*kwargs in methodA gets passed as \*\*kwargs to methodB?
Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments. ``` methodB("argvalue", **kwargs) ```
51,420
<p>I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.</p> <p>What is the easiest way to get the base 10 logarithm of a Fixnum?</p>
[ { "answer_id": 51423, "author": "Wes Oldenbeuving", "author_id": 4187, "author_profile": "https://Stackoverflow.com/users/4187", "pm_score": 2, "selected": false, "text": "<p>Reading the documentation for module Math the answer is really obvious:</p>\n\n<pre><code>Math::log10(n) \n</code></pre>\n\n<p>This gives the base 10 logarithm of n.</p>\n" }, { "answer_id": 51424, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.ruby-doc.org/core-1.8.7/classes/Math.html#M001197\" rel=\"nofollow noreferrer\">Math.log10</a>(numeric) => float\nreturns base 10 log</p>\n" }, { "answer_id": 51426, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 4, "selected": true, "text": "<p>There is </p>\n\n<pre><code>Math::log10 (n)\n</code></pre>\n\n<p>And there is also a property of logarithms that <code>logx(y) = log(y)/log(x)</code></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4187/" ]
I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10. What is the easiest way to get the base 10 logarithm of a Fixnum?
There is ``` Math::log10 (n) ``` And there is also a property of logarithms that `logx(y) = log(y)/log(x)`
51,429
<p>Can anyone give me some pointers on how to display the results of an XPath query in a textbox using code (C#)? My datascource <i>seems</i> to (re)bind correctly once the XPath query has been applied, but I cannot find how to get at the resulting data.<br /><br /> Any help would be greatly appreciated.</p>
[ { "answer_id": 51490, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 0, "selected": false, "text": "<p>Some more information would be nice to have to be able to give you a decent answer. Do you have any existing code snippets you could publish here?</p>\n\n<p>The general idea is to use the XmlDataSource.XPath property as a filter on the XmlDataSource.Data property. Did you try displaying the contents of the Data prop in your textbox?</p>\n" }, { "answer_id": 51514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Based on a slection in a DropDownList, when the SelectedIndexChanged event fires, the XPath for an XMLDataSource object is updated:</p>\n\n<pre><code>protected void ddl_SelectedIndexChanged(object sender, EventArgs e)\n{\n XMLds.XPath = \"/controls/control[@id='AuthorityType']/item[@text='\" + ddl.SelectedValue + \"']/linkedValue\";\n XMLds.DataBind();\n}\n</code></pre>\n\n<p>The XPath string is fine, I can output and test that it is working correctly and resolving to the correct nodes. What I am having problems with, is getting at the data that is supposedly stored in the XmlDataSource; specifically, getting the data and outputting it in a TextBox. I'd like to be able to do this as part of the function above, i.e.<br /></p>\n\n<pre><code>protected void ddl_SelectedIndexChanged(object sender, EventArgs e)\n{\n XMLds.XPath = \"/controls/control[@id='AuthorityType']/item[@text='\" + ddl.SelectedValue + \"']/linkedValue\";\n XMLds.DataBind();\n myTextBox.Text = &lt;FieldFromXMLDataSource&gt;;\n}\n</code></pre>\n\n<p>Thank you for your time.</p>\n" }, { "answer_id": 51698, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 1, "selected": false, "text": "<p>XMLDataSource is designed to be used with data-bound controls. ASP.NET's TextBox is not a data-bound control. So to accomplish what you want you either have to find a textbox control with data binding or display the result in some other way. </p>\n\n<p>For example, you could use a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx\" rel=\"nofollow noreferrer\">Repeater control</a> and create your own rendering template for it. </p>\n\n<pre><code>&lt;asp:Repeater id=\"Repeater1\" runat=\"server\" datasource=\"XMLds\"&gt;\n &lt;ItemTemplate&gt;\n &lt;input type=\"text\" value=\"&lt;%# XPath(\"&lt;path to display field&gt;\")%&gt;\" /&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can anyone give me some pointers on how to display the results of an XPath query in a textbox using code (C#)? My datascource *seems* to (re)bind correctly once the XPath query has been applied, but I cannot find how to get at the resulting data. Any help would be greatly appreciated.
XMLDataSource is designed to be used with data-bound controls. ASP.NET's TextBox is not a data-bound control. So to accomplish what you want you either have to find a textbox control with data binding or display the result in some other way. For example, you could use a [Repeater control](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx) and create your own rendering template for it. ``` <asp:Repeater id="Repeater1" runat="server" datasource="XMLds"> <ItemTemplate> <input type="text" value="<%# XPath("<path to display field>")%>" /> </ItemTemplate> </asp:Repeater> ```
51,470
<p>In <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a>, I can do something like this:</p> <pre><code>ALTER SEQUENCE serial RESTART WITH 0; </code></pre> <p>Is there an Oracle equivalent?</p>
[ { "answer_id": 51482, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 7, "selected": false, "text": "<p>A true restart is not possible <a href=\"http://en.wiktionary.org/wiki/AFAIK\" rel=\"noreferrer\">AFAIK</a>. (Please correct me if I'm wrong!).</p>\n\n<p>However, if you want to set it to 0, you can just delete and recreate it.</p>\n\n<p>If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.</p>\n\n<p>That is, if your sequence is at 500, you can set it to 100 via</p>\n\n<pre><code>ALTER SEQUENCE serial INCREMENT BY -400;\nSELECT serial.NEXTVAL FROM dual;\nALTER SEQUENCE serial INCREMENT BY 1;\n</code></pre>\n" }, { "answer_id": 63855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Altering the sequence's INCREMENT value, incrementing it, and then altering it back is pretty painless, plus you have the added benefit of not having to re-establish all of the grants as you would had you dropped/recreated the sequence.</p>\n" }, { "answer_id": 93633, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 8, "selected": true, "text": "<p>Here is a good procedure for resetting any sequence to 0 from Oracle guru <a href=\"http://asktom.oracle.com\" rel=\"noreferrer\">Tom Kyte</a>. Great discussion on the pros and cons in the links below too.</p>\n\n<pre><code>[email protected]&gt; \ncreate or replace\nprocedure reset_seq( p_seq_name in varchar2 )\nis\n l_val number;\nbegin\n execute immediate\n 'select ' || p_seq_name || '.nextval from dual' INTO l_val;\n\n execute immediate\n 'alter sequence ' || p_seq_name || ' increment by -' || l_val || \n ' minvalue 0';\n\n execute immediate\n 'select ' || p_seq_name || '.nextval from dual' INTO l_val;\n\n execute immediate\n 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';\nend;\n/\n</code></pre>\n\n<p>From this page: <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592\" rel=\"noreferrer\">Dynamic SQL to reset sequence value</a><br>\nAnother good discussion is also here: <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597\" rel=\"noreferrer\">How to reset sequences?</a></p>\n" }, { "answer_id": 1201816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This <a href=\"http://en.wikipedia.org/wiki/Stored_procedure\" rel=\"noreferrer\">stored procedure</a> restarts my sequence:</p>\n\n<pre><code>Create or Replace Procedure Reset_Sequence \n is\n SeqNbr Number;\nbegin\n /* Reset Sequence 'seqXRef_RowID' to 0 */\n Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;\n Execute Immediate 'Alter sequence seqXRef increment by - ' || TO_CHAR(SeqNbr) ;\n Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;\n Execute Immediate 'Alter sequence seqXRef increment by 1';\nEND;\n</code></pre>\n\n<p>/</p>\n" }, { "answer_id": 1885714, "author": "Vipin Vij", "author_id": 229348, "author_profile": "https://Stackoverflow.com/users/229348", "pm_score": 2, "selected": false, "text": "<p>1) Suppose you create a SEQUENCE like shown below:</p>\n\n<pre><code>CREATE SEQUENCE TESTSEQ\nINCREMENT BY 1\nMINVALUE 1\nMAXVALUE 500\nNOCACHE\nNOCYCLE\nNOORDER\n</code></pre>\n\n<p>2) Now you fetch values from SEQUENCE. Lets say I have fetched four times as shown below.</p>\n\n<pre><code>SELECT TESTSEQ.NEXTVAL FROM dual\nSELECT TESTSEQ.NEXTVAL FROM dual\nSELECT TESTSEQ.NEXTVAL FROM dual\nSELECT TESTSEQ.NEXTVAL FROM dual\n</code></pre>\n\n<p>3) After executing above four commands the value of the SEQUENCE will be 4. Now suppose I have reset the value of the SEQUENCE to 1 again. The follow the following steps. Follow all the steps in the same order as shown below:</p>\n\n<ol>\n<li><code>ALTER SEQUENCE TESTSEQ INCREMENT BY -3;</code></li>\n<li><code>SELECT TESTSEQ.NEXTVAL FROM dual</code></li>\n<li><code>ALTER SEQUENCE TESTSEQ INCREMENT BY 1;</code></li>\n<li><code>SELECT TESTSEQ.NEXTVAL FROM dual</code></li>\n</ol>\n" }, { "answer_id": 2866665, "author": "Gina", "author_id": 345203, "author_profile": "https://Stackoverflow.com/users/345203", "pm_score": 6, "selected": false, "text": "<p>This is my approach:</p>\n\n<ol>\n<li>drop the sequence</li>\n<li>recreate it</li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>--Drop sequence\n\nDROP SEQUENCE MY_SEQ;\n\n-- Create sequence \n\ncreate sequence MY_SEQ\nminvalue 1\nmaxvalue 999999999999999999999\nstart with 1\nincrement by 1\ncache 20;\n</code></pre>\n" }, { "answer_id": 4100161, "author": "Navin", "author_id": 497595, "author_profile": "https://Stackoverflow.com/users/497595", "pm_score": 3, "selected": false, "text": "<p>The following script set the sequence to a desired value:</p>\n\n<p>Given a freshly created sequence named PCS_PROJ_KEY_SEQ and table PCS_PROJ:</p>\n\n<pre><code>BEGIN\n DECLARE\n PROJ_KEY_MAX NUMBER := 0;\n PROJ_KEY_CURRVAL NUMBER := 0;\n BEGIN\n\n SELECT MAX (PROJ_KEY) INTO PROJ_KEY_MAX FROM PCS_PROJ;\n EXECUTE IMMEDIATE 'ALTER SEQUENCE PCS_PROJ_KEY_SEQ INCREMENT BY ' || PROJ_KEY_MAX;\n SELECT PCS_PROJ_KEY_SEQ.NEXTVAL INTO PROJ_KEY_CURRVAL FROM DUAL;\n EXECUTE IMMEDIATE 'ALTER SEQUENCE PCS_PROJ_KEY_SEQ INCREMENT BY 1';\n\nEND;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 6062586, "author": "Allbite", "author_id": 290091, "author_profile": "https://Stackoverflow.com/users/290091", "pm_score": 5, "selected": false, "text": "<p>My approach is a teensy extension to <a href=\"https://stackoverflow.com/questions/51470/how-do-i-reset-a-sequence-in-oracle/93633#93633\">Dougman's example</a>.</p>\n\n<p>Extensions are...</p>\n\n<p>Pass in the seed value as a parameter. Why? I like to call the thing resetting the sequence back to <em>the max ID used in some table</em>. I end up calling this proc from another script which executes multiple calls for a whole bunch of sequences, resetting nextval back down to some level which is high enough to not cause primary key violations where I'm using the sequence's value for a unique identifier.</p>\n\n<p>It also honors the previous <em>minvalue</em>. It may in fact <em>push the next value ever higher</em> if the desired <strong>p_val</strong> or <em>existing minvalue</em> are higher than the current or calculated next value.</p>\n\n<p>Best of all, it can be called to reset to a specified value, and just wait until you see the wrapper \"fix all my sequences\" procedure at the end.</p>\n\n<pre><code>create or replace\nprocedure Reset_Sequence( p_seq_name in varchar2, p_val in number default 0)\nis\n l_current number := 0;\n l_difference number := 0;\n l_minvalue user_sequences.min_value%type := 0;\n\nbegin\n\n select min_value\n into l_minvalue\n from user_sequences\n where sequence_name = p_seq_name;\n\n execute immediate\n 'select ' || p_seq_name || '.nextval from dual' INTO l_current;\n\n if p_Val &lt; l_minvalue then\n l_difference := l_minvalue - l_current;\n else\n l_difference := p_Val - l_current;\n end if;\n\n if l_difference = 0 then\n return;\n end if;\n\n execute immediate\n 'alter sequence ' || p_seq_name || ' increment by ' || l_difference || \n ' minvalue ' || l_minvalue;\n\n execute immediate\n 'select ' || p_seq_name || '.nextval from dual' INTO l_difference;\n\n execute immediate\n 'alter sequence ' || p_seq_name || ' increment by 1 minvalue ' || l_minvalue;\nend Reset_Sequence;\n</code></pre>\n\n<p>That procedure is useful all by itself, but now let's add another one which calls it and specifies everything programmatically with a sequence naming convention and looking for the maximum value used in an existing table/field...</p>\n\n<pre><code>create or replace\nprocedure Reset_Sequence_to_Data(\n p_TableName varchar2,\n p_FieldName varchar2\n)\nis\n l_MaxUsed NUMBER;\nBEGIN\n\n execute immediate\n 'select coalesce(max(' || p_FieldName || '),0) from '|| p_TableName into l_MaxUsed;\n\n Reset_Sequence( p_TableName || '_' || p_Fieldname || '_SEQ', l_MaxUsed );\n\nEND Reset_Sequence_to_Data;\n</code></pre>\n\n<p>Now we're cooking with gas! </p>\n\n<p>The procedure above will check for a field's max value in a table, builds a sequence name from the table/field pair and invokes <em>\"Reset_Sequence\"</em> with that sensed max value.</p>\n\n<p>The final piece in this puzzle and the icing on the cake comes next...</p>\n\n<pre><code>create or replace\nprocedure Reset_All_Sequences\nis\nBEGIN\n\n Reset_Sequence_to_Data( 'ACTIVITYLOG', 'LOGID' );\n Reset_Sequence_to_Data( 'JOBSTATE', 'JOBID' );\n Reset_Sequence_to_Data( 'BATCH', 'BATCHID' );\n\nEND Reset_All_Sequences;\n</code></pre>\n\n<p>In my actual database there are around one hundred other sequences being reset through this mechanism, so there are 97 more calls to <em>Reset_Sequence_to_Data</em> in that procedure above.</p>\n\n<p>Love it? Hate it? Indifferent?</p>\n" }, { "answer_id": 14800260, "author": "Chris Saxon", "author_id": 1485955, "author_profile": "https://Stackoverflow.com/users/1485955", "pm_score": 3, "selected": false, "text": "<p>There is another way to reset a sequence in Oracle: set the <code>maxvalue</code> and <code>cycle</code> properties. When the <code>nextval</code> of the sequence hits the <code>maxvalue</code>, if the <code>cycle</code> property is set then it will begin again from the <code>minvalue</code> of the sequence.</p>\n\n<p>The advantage of this method compared to setting a negative <code>increment by</code> is the sequence can continue to be used while the reset process runs, reducing the chance you need to take some form of outage to do the reset.</p>\n\n<p>The value for <code>maxvalue</code> has to be greater than the current <code>nextval</code>, so the procedure below includes an optional parameter allowing a buffer in case the sequence is accessed again between selecting the <code>nextval</code> in the procedure and setting the <code>cycle</code> property.</p>\n\n<pre><code>create sequence s start with 1 increment by 1;\n\nselect s.nextval from dual\nconnect by level &lt;= 20;\n\n NEXTVAL\n----------\n 1 \n...\n 20\n\ncreate or replace procedure reset_sequence ( i_buffer in pls_integer default 0)\nas\n maxval pls_integer;\nbegin\n\n maxval := s.nextval + greatest(i_buffer, 0); --ensure we don't go backwards!\n execute immediate 'alter sequence s cycle minvalue 0 maxvalue ' || maxval;\n maxval := s.nextval;\n execute immediate 'alter sequence s nocycle maxvalue 99999999999999';\n\nend;\n/\nshow errors\n\nexec reset_sequence;\n\nselect s.nextval from dual;\n\n NEXTVAL\n----------\n 1 \n</code></pre>\n\n<p>The procedure as stands still allows the possibility that another session will fetch the value 0, which may or may not be an issue for you. If it is, you could always:</p>\n\n<ul>\n<li>Set <code>minvalue 1</code> in the first alter</li>\n<li>Exclude the second <code>nextval</code> fetch </li>\n<li>Move the statement to set the <code>nocycle</code> property into another procedure, to be run at a later date (assuming you want to do this).</li>\n</ul>\n" }, { "answer_id": 19673327, "author": "Jon Heller", "author_id": 409172, "author_profile": "https://Stackoverflow.com/users/409172", "pm_score": 6, "selected": false, "text": "<p>For regular sequences:</p>\n<pre><code>alter sequence serial restart start with 1;\n</code></pre>\n<p>For system-generated sequences used for identity columns:</p>\n<pre><code>alter table table_name modify id generated by default on null as identity(start with 1);\n</code></pre>\n<hr />\n<p>This feature was officially added in 18c but is unofficially available since 12.1.</p>\n<p>It is arguably safe to use this undocumented feature in 12.1. Even though the syntax is <em>not</em> included in the <a href=\"http://docs.oracle.com/database/121/SQLRF/statements_2014.htm#SQLRF00817\" rel=\"nofollow noreferrer\">official documentation</a>, it is generated by the Oracle package <a href=\"http://docs.oracle.com/database/121/ARPLS/d_metadiff.htm#ARPLS354\" rel=\"nofollow noreferrer\">DBMS_METADATA_DIFF</a>. I've used it several times on production systems. However, I created an Oracle Service request and they verified that it's not a documentation bug, the feature is truly unsupported.</p>\n<p>In 18c, the feature does not appear in the SQL Language Syntax, but is included in the <a href=\"https://docs.oracle.com/en/database/oracle/oracle-database/18/admin/managing-views-sequences-and-synonyms.html\" rel=\"nofollow noreferrer\">Database Administrator's Guide</a>.</p>\n" }, { "answer_id": 22639704, "author": "justincohler", "author_id": 1133062, "author_profile": "https://Stackoverflow.com/users/1133062", "pm_score": 2, "selected": false, "text": "<p>You can use the CYCLE option, shown below:</p>\n\n<pre><code>CREATE SEQUENCE test_seq\nMINVALUE 0\nMAXVALUE 100\nSTART WITH 0\nINCREMENT BY 1\nCYCLE;\n</code></pre>\n\n<p>In this case, when the sequence reaches MAXVALUE (100), it will recycle to the MINVALUE (0).</p>\n\n<p>In the case of a decremented sequence, the sequence would recycle to the MAXVALUE.</p>\n" }, { "answer_id": 30652117, "author": "Wendel", "author_id": 2057463, "author_profile": "https://Stackoverflow.com/users/2057463", "pm_score": 2, "selected": false, "text": "<p>I create a block to reset all my sequences:</p>\n\n<pre><code>DECLARE\n I_val number;\nBEGIN\n FOR US IN\n (SELECT US.SEQUENCE_NAME FROM USER_SEQUENCES US)\n LOOP\n execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;\n execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by -' || l_val || ' minvalue 0';\n execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;\n execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by 1 minvalue 0';\n END LOOP;\nEND;\n</code></pre>\n" }, { "answer_id": 32017463, "author": "Sentinel", "author_id": 4687355, "author_profile": "https://Stackoverflow.com/users/4687355", "pm_score": 2, "selected": false, "text": "<p>Here's a more robust procedure for altering the next value returned by a sequence, plus a whole lot more.</p>\n\n<ul>\n<li>First off it protects against SQL injection attacks since none of the strings passed in are used to directly create any of the dynamic SQL statements,</li>\n<li>Second it prevents the next sequence value from being set outside the bounds of the min or max sequence values. The <code>next_value</code> will be != <code>min_value</code> and between <code>min_value</code> and <code>max_value</code>.</li>\n<li>Third it takes the current (or proposed) <code>increment_by</code> setting as well as all the other sequence settings into account when cleaning up.</li>\n<li>Fourth all parameters except the first are optional and unless specified take on the current sequence setting as defaults. If no optional parameters are specified no action is taken.</li>\n<li>Finally if you try altering a sequence that doesn't exist (or is not owned by the current user) it will raise an <code>ORA-01403: no data found</code> error.</li>\n</ul>\n\n<p>Here's the code:</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE alter_sequence(\n seq_name user_sequences.sequence_name%TYPE\n , next_value user_sequences.last_number%TYPE := null\n , increment_by user_sequences.increment_by%TYPE := null\n , min_value user_sequences.min_value%TYPE := null\n , max_value user_sequences.max_value%TYPE := null\n , cycle_flag user_sequences.cycle_flag%TYPE := null\n , cache_size user_sequences.cache_size%TYPE := null\n , order_flag user_sequences.order_flag%TYPE := null)\n AUTHID CURRENT_USER\nAS\n l_seq user_sequences%rowtype;\n l_old_cache user_sequences.cache_size%TYPE;\n l_next user_sequences.min_value%TYPE;\nBEGIN\n -- Get current sequence settings as defaults\n SELECT * INTO l_seq FROM user_sequences WHERE sequence_name = seq_name;\n\n -- Update target settings\n l_old_cache := l_seq.cache_size;\n l_seq.increment_by := nvl(increment_by, l_seq.increment_by);\n l_seq.min_value := nvl(min_value, l_seq.min_value);\n l_seq.max_value := nvl(max_value, l_seq.max_value);\n l_seq.cycle_flag := nvl(cycle_flag, l_seq.cycle_flag);\n l_seq.cache_size := nvl(cache_size, l_seq.cache_size);\n l_seq.order_flag := nvl(order_flag, l_seq.order_flag);\n\n IF next_value is NOT NULL THEN\n -- Determine next value without exceeding limits\n l_next := LEAST(GREATEST(next_value, l_seq.min_value+1),l_seq.max_value);\n\n -- Grab the actual latest seq number\n EXECUTE IMMEDIATE\n 'ALTER SEQUENCE '||l_seq.sequence_name\n || ' INCREMENT BY 1'\n || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number-l_old_cache)\n || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)\n || ' NOCACHE'\n || ' ORDER';\n EXECUTE IMMEDIATE \n 'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'\n INTO l_seq.last_number;\n\n l_next := l_next-l_seq.last_number-1;\n\n -- Reset the sequence number\n IF l_next &lt;&gt; 0 THEN\n EXECUTE IMMEDIATE \n 'ALTER SEQUENCE '||l_seq.sequence_name\n || ' INCREMENT BY '||l_next\n || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number)\n || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)\n || ' NOCACHE'\n || ' ORDER';\n EXECUTE IMMEDIATE \n 'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'\n INTO l_next;\n END IF;\n END IF;\n\n -- Prepare Sequence for next use.\n IF COALESCE( cycle_flag\n , next_value\n , increment_by\n , min_value\n , max_value\n , cache_size\n , order_flag) IS NOT NULL\n THEN\n EXECUTE IMMEDIATE \n 'ALTER SEQUENCE '||l_seq.sequence_name\n || ' INCREMENT BY '||l_seq.increment_by\n || ' MINVALUE '||l_seq.min_value\n || ' MAXVALUE '||l_seq.max_value\n || CASE l_seq.cycle_flag\n WHEN 'Y' THEN ' CYCLE' ELSE ' NOCYCLE' END\n || CASE l_seq.cache_size\n WHEN 0 THEN ' NOCACHE'\n ELSE ' CACHE '||l_seq.cache_size END\n || CASE l_seq.order_flag\n WHEN 'Y' THEN ' ORDER' ELSE ' NOORDER' END;\n END IF;\nEND;\n</code></pre>\n" }, { "answer_id": 32836249, "author": "Rakesh", "author_id": 1902897, "author_profile": "https://Stackoverflow.com/users/1902897", "pm_score": 2, "selected": false, "text": "<p>In my project, once it happened that someone manually entered the records without using sequence, hence I have to reset sequence value manually, for which I wrote below sql code snippet:</p>\n\n<pre><code>declare\nmax_db_value number(10,0);\ncur_seq_value number(10,0);\ncounter number(10,0);\ndifference number(10,0);\ndummy_number number(10);\n\nbegin\n\n-- enter table name here\nselect max(id) into max_db_value from persons;\n-- enter sequence name here\nselect last_number into cur_seq_value from user_sequences where sequence_name = 'SEQ_PERSONS';\n\ndifference := max_db_value - cur_seq_value;\n\n for counter in 1..difference\n loop\n -- change sequence name here as well\n select SEQ_PERSONS.nextval into dummy_number from dual;\n end loop;\nend;\n</code></pre>\n\n<p>Please note, the above code will work if the sequence is lagging. </p>\n" }, { "answer_id": 36924500, "author": "Bruno Freitas", "author_id": 1322804, "author_profile": "https://Stackoverflow.com/users/1322804", "pm_score": 1, "selected": false, "text": "<p>I make an alternative that the user don’t need to know the values, the system get and use variables to update.</p>\n\n<pre><code>--Atualizando sequence da tabela SIGA_TRANSACAO, pois está desatualizada\nDECLARE\n actual_sequence_number INTEGER;\n max_number_from_table INTEGER;\n difference INTEGER;\nBEGIN\n SELECT [nome_da_sequence].nextval INTO actual_sequence_number FROM DUAL;\n SELECT MAX([nome_da_coluna]) INTO max_number_from_table FROM [nome_da_tabela];\n SELECT (max_number_from_table-actual_sequence_number) INTO difference FROM DUAL;\nIF difference &gt; 0 then\n EXECUTE IMMEDIATE CONCAT('alter sequence [nome_da_sequence] increment by ', difference);\n --aqui ele puxa o próximo valor usando o incremento necessário\n SELECT [nome_da_sequence].nextval INTO actual_sequence_number from dual;\n--aqui volta o incremento para 1, para que futuras inserções funcionem normalmente\n EXECUTE IMMEDIATE 'ALTER SEQUENCE [nome_da_sequence] INCREMENT by 1';\n DBMS_OUTPUT.put_line ('A sequence [nome_da_sequence] foi atualizada.');\nELSE\n DBMS_OUTPUT.put_line ('A sequence [nome_da_sequence] NÃO foi atualizada, já estava OK!');\nEND IF;\nEND;\n</code></pre>\n" }, { "answer_id": 41534389, "author": "user46748", "author_id": 5439593, "author_profile": "https://Stackoverflow.com/users/5439593", "pm_score": 1, "selected": false, "text": "<p>Here's how to make all auto-increment sequences match actual data:</p>\n\n<ol>\n<li><p>Create a procedure to enforce next value as was already described in this thread:</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE Reset_Sequence(\n P_Seq_Name IN VARCHAR2,\n P_Val IN NUMBER DEFAULT 0)\nIS\n L_Current NUMBER := 0;\n L_Difference NUMBER := 0;\n L_Minvalue User_Sequences.Min_Value%Type := 0;\nBEGIN\n SELECT Min_Value\n INTO L_Minvalue\n FROM User_Sequences\n WHERE Sequence_Name = P_Seq_Name;\n EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Current;\n IF P_Val &lt; L_Minvalue THEN\n L_Difference := L_Minvalue - L_Current;\n ELSE\n L_Difference := P_Val - L_Current;\n END IF;\n IF L_Difference = 0 THEN\n RETURN;\n END IF;\n EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by ' || L_Difference || ' minvalue ' || L_Minvalue;\n EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Difference;\n EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by 1 minvalue ' || L_Minvalue;\nEND Reset_Sequence;\n</code></pre></li>\n<li><p>Create another procedure to reconcile all sequences with actual content:</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE RESET_USER_SEQUENCES_TO_DATA\nIS\n STMT CLOB;\nBEGIN\n SELECT 'select ''BEGIN'' || chr(10) || x || chr(10) || ''END;'' FROM (select listagg(x, chr(10)) within group (order by null) x FROM ('\n || X\n || '))'\n INTO STMT\n FROM\n (SELECT LISTAGG(X, ' union ') WITHIN GROUP (\n ORDER BY NULL) X\n FROM\n (SELECT CHR(10)\n || 'select ''Reset_Sequence('''''\n || SEQ_NAME\n || ''''','' || coalesce(max('\n || COL_NAME\n || '), 0) || '');'' x from '\n || TABLE_NAME X\n FROM\n (SELECT TABLE_NAME,\n REGEXP_SUBSTR(WTEXT, 'NEW\\.(\\S*) IS NULL',1,1,'i',1) COL_NAME,\n REGEXP_SUBSTR(BTEXT, '(\\.|\\s)([a-z_]*)\\.nextval',1,1,'i',2) SEQ_NAME\n FROM USER_TRIGGERS\n LEFT JOIN\n (SELECT NAME BNAME,\n TEXT BTEXT\n FROM USER_SOURCE\n WHERE TYPE = 'TRIGGER'\n AND UPPER(TEXT) LIKE '%NEXTVAL%'\n )\n ON BNAME = TRIGGER_NAME\n LEFT JOIN\n (SELECT NAME WNAME,\n TEXT WTEXT\n FROM USER_SOURCE\n WHERE TYPE = 'TRIGGER'\n AND UPPER(TEXT) LIKE '%IS NULL%'\n )\n ON WNAME = TRIGGER_NAME\n WHERE TRIGGER_TYPE = 'BEFORE EACH ROW'\n AND TRIGGERING_EVENT = 'INSERT'\n )\n )\n ) ;\n EXECUTE IMMEDIATE STMT INTO STMT;\n --dbms_output.put_line(stmt);\n EXECUTE IMMEDIATE STMT;\nEND RESET_USER_SEQUENCES_TO_DATA;\n</code></pre></li>\n</ol>\n\n<p>NOTES:</p>\n\n<ol>\n<li>Procedure extracts names from trigger code and does not depend on naming conventions</li>\n<li>To check generated code before execution, switch comments on last two lines</li>\n</ol>\n" }, { "answer_id": 43614527, "author": "Lawrence", "author_id": 1435079, "author_profile": "https://Stackoverflow.com/users/1435079", "pm_score": 2, "selected": false, "text": "<p>Jezus, all this programming for just an index restart...\nPerhaps I'm an idiot, but for pre-oracle 12 (which has a restart feature), what is wrong with a simpel:</p>\n\n<pre><code>drop sequence blah;\ncreate sequence blah \n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 58923589, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": -1, "selected": false, "text": "<p>Stored procedure that worked for me</p>\n\n<pre><code>create or replace\nprocedure reset_sequence( p_seq_name in varchar2, tablename in varchar2 )\nis\n l_val number;\n maxvalueid number;\nbegin\n execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val;\n execute immediate 'select max(id) from ' || tablename INTO maxvalueid;\n execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0';\n execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val;\n execute immediate 'alter sequence ' || p_seq_name || ' increment by '|| maxvalueid ||' minvalue 0'; \n execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val;\n execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';\nend;\n</code></pre>\n\n<p>How to use the stored procedure:</p>\n\n<pre><code>execute reset_sequence('company_sequence','company');\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917/" ]
In [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL), I can do something like this: ``` ALTER SEQUENCE serial RESTART WITH 0; ``` Is there an Oracle equivalent?
Here is a good procedure for resetting any sequence to 0 from Oracle guru [Tom Kyte](http://asktom.oracle.com). Great discussion on the pros and cons in the links below too. ``` [email protected]> create or replace procedure reset_seq( p_seq_name in varchar2 ) is l_val number; begin execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0'; end; / ``` From this page: [Dynamic SQL to reset sequence value](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592) Another good discussion is also here: [How to reset sequences?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597)
51,492
<p>For me <strong>usable</strong> means that:</p> <ul> <li>it's being used in real-wold</li> <li>it has tools support. (at least some simple editor)</li> <li>it has human readable syntax (no angle brackets please) </li> </ul> <p>Also I want it to be as close to XML as possible, i.e. there must be support for attributes as well as for properties. So, no <a href="http://en.wikipedia.org/wiki/YAML" rel="noreferrer">YAML</a> please. Currently, only one matching language comes to my mind - <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a>. Do you know any other alternatives?</p>
[ { "answer_id": 51494, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a> is a very good alternative, and there are tools for it in multiple languages. And it's really easy to use in web clients, as it is native javascript.</p>\n" }, { "answer_id": 51496, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>I would recommend JSON ... but since you already mentioned it maybe you should take a look at <a href=\"http://google-opensource.blogspot.com/2008/07/protocol-buffers-googles-data.html\" rel=\"nofollow noreferrer\">Google protocol buffers</a>.</p>\n\n<p>Edit: Protocol buffers are made to be used programatically (there are bindings for c++, java, python ...) so they may not be suited for your purpose.</p>\n" }, { "answer_id": 51498, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": "<p>I think <a href=\"http://www.clearsilver.net/\" rel=\"nofollow noreferrer\">Clearsilver</a> is a very good alternative. They even have a comparison page <a href=\"http://www.clearsilver.net/docs/compare_w_xmlxslt.hdf\" rel=\"nofollow noreferrer\">here</a> and a list of <a href=\"http://www.clearsilver.net/examples.hdf\" rel=\"nofollow noreferrer\">projects</a> that use it</p>\n" }, { "answer_id": 51517, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 3, "selected": false, "text": "<p>Jeff wrote about this <a href=\"http://www.codinghorror.com/blog/archives/001114.html\" rel=\"noreferrer\">here</a> and <a href=\"http://www.codinghorror.com/blog/archives/001139.html\" rel=\"noreferrer\">here</a>. That should help you get started.</p>\n" }, { "answer_id": 51521, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "<p>You're demands are a bit impossible.. You want something close to XML, but reject probably the closest equivalent that doesn't have angle-bracket (YAML).</p>\n\n<p>As much as I dislike it, why not just use XML? You shouldn't ever have to actually read XML (aside from debugging, I suppose), there are an absurd amount of tools about for it.</p>\n\n<p>Pretty much anything that isn't XML isn't going to be as widely used, thus there will be less tool support.</p>\n\n<p>JSON is probably about equivalent, but it's pretty much equally unreadable.. but again, you shouldn't ever have to actually read it (load it into whatever language you are using, and it should be transformed into native arrays/dicts/variables/whatever). </p>\n\n<p>Oh, I do find JSON <em>far</em> nicer to parse than XML: I've used it in Javascript, and the simplejson Python module - about one command and it's nicely transformed into a native Python dict, or a Javascript object (thus the name!)</p>\n" }, { "answer_id": 51562, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 1, "selected": false, "text": "<p>If you're allergic to angle brackets, then JSON, <a href=\"http://www.clearsilver.net/docs/man_hdf.hdf\" rel=\"nofollow noreferrer\">HDF</a> (ClearSilver), and <a href=\"http://ogdl.sourceforge.net/\" rel=\"nofollow noreferrer\">OGDL</a> are the only ones I know offhand.</p>\n\n<p>After a bit of googling, I also found a list of alternatives here:<br/>\n<a href=\"http://web.archive.org/web/20060325012720/www.pault.com/xmlalternatives.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20060325012720/www.pault.com/xmlalternatives.html</a></p>\n" }, { "answer_id": 51580, "author": "rjmunro", "author_id": 3408, "author_profile": "https://Stackoverflow.com/users/3408", "pm_score": 0, "selected": false, "text": "<p>AFAIK, JSON and YAML are exactly equivalent in data structure terms. YAML just has less brackets and quotes and stuff. So I don't see how you are rejecting one and keeping the other.</p>\n\n<p>Also, I don't see how XML's angle brackets are less \"human readable\" than JSON's square brackets, curly brackets and quotes.</p>\n" }, { "answer_id": 2567924, "author": "Ari", "author_id": 307804, "author_profile": "https://Stackoverflow.com/users/307804", "pm_score": 7, "selected": true, "text": "<p>YAML is a 100% superset of JSON, so it doesn't make sense to reject YAML and then consider JSON instead. YAML does everything JSON does, but YAML gives so much more too (like references).</p>\n\n<p>I can't think of anything XML can do that YAML can't, except to validate a document with a DTD, which in my experience has never been worth the overhead. But YAML is so much faster and easier to type and read than XML.</p>\n\n<p>As for attributes or properties, if you think about it, they don't truly \"add\" anything... it's just a notational shortcut to write something as an attribute of the node instead of putting it in its own child node. But if you like that convenience, you can often emulate it with YAML's inline lists/hashes. Eg:</p>\n\n<pre><code>&lt;!-- XML --&gt;\n&lt;Director name=\"Spielberg\"&gt;\n &lt;Movies&gt;\n &lt;Movie title=\"Jaws\" year=\"1975\"/&gt;\n &lt;Movie title=\"E.T.\" year=\"1982\"/&gt;\n &lt;/Movies&gt;\n&lt;/Director&gt;\n\n\n# YAML\nDirector: \n name: Spielberg\n Movies:\n - Movie: {title: E.T., year: 1975}\n - Movie: {title: Jaws, year: 1982}\n</code></pre>\n\n<p>For me, the luxury of not having to write each node tag twice, combined with the freedom from all the angle-bracket litter makes YAML a preferred choice. I also actually like the lack of formal tag attributes, as that always seemed to me like a gray area of XML that needlessly introduced two sets of syntax (both when writing and traversing) for essentially the same concept. YAML does away with that confusion altogether.</p>\n" }, { "answer_id": 5623293, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "<p>I have found <a href=\"http://en.wikipedia.org/wiki/S-expression\" rel=\"noreferrer\">S-Expressions</a> to be a great way to represent structured data. It's a very simple format which is easy to generate and parse. It doesn't support attributes, but like YAML &amp; JSON, it doesn't need to. Attributes are simply a way for XML to limit verbosity. Simpler, cleaner formats just don't need them.</p>\n" }, { "answer_id": 6908397, "author": "Martin Vahi", "author_id": 855783, "author_profile": "https://Stackoverflow.com/users/855783", "pm_score": 0, "selected": false, "text": "<p>There are truly plenty of alternatives to XML, but the main problem with many of them seems to be that libraries might not be available for every language of choice and the libraries are relatively laborious to implement. </p>\n\n<p>Parsing a tree structure itself might not be that pleasant, if compared to key-value pairs, e.g. hash tables. If a hash table instance meets the requirement that all of its keys are strings and all of its values are strings, then it's relatively non-laborous to implement hashtable2string() and string2hashtable().</p>\n\n<p>I've been using the hash table serialization in AJAX between PHP and JavaScript and the format that I've developed, is called ProgFTE (Programmer Friendly text Exchange) and is described at:</p>\n\n<p><a href=\"http://martin.softf1.com/g/n//a2/doc/progfte/index.html\" rel=\"nofollow\">http://martin.softf1.com/g/n//a2/doc/progfte/index.html</a></p>\n\n<p>One can find a Ruby version of the ProgFTE implementation as part of the Kibuvits Ruby Library:\n<a href=\"http://rubyforge.org/projects/kibuvits/\" rel=\"nofollow\">http://rubyforge.org/projects/kibuvits/</a></p>\n" }, { "answer_id": 15808838, "author": "gtd", "author_id": 8376, "author_profile": "https://Stackoverflow.com/users/8376", "pm_score": 2, "selected": false, "text": "<p>YAML is extremely fully-featured and generally human-readable format, but it's Achilles heal is complexity as demonstrated by the Rails vulnerabilities we saw this winter. Due to its ubiquity in Ruby as a config language Tom Preston-Werner of Github fame stepped up to create a sane alternative dubbed TOML. It gained massive traction immediately and has great tool support. I highly recommend anyone looking at YAML check it out:</p>\n\n<p><a href=\"https://github.com/mojombo/toml\" rel=\"nofollow\">https://github.com/mojombo/toml</a></p>\n" }, { "answer_id": 20362887, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 2, "selected": false, "text": "<p>For storing code-like data, <a href=\"http://loyc.net/les/\" rel=\"nofollow noreferrer\">LES</a> (Loyc Expression Syntax) is a budding alternative. I've noticed a lot of people use XML for code-like constructs, such as build systems which support conditionals, command invocations, sometimes even loops. These sorts of things look natural in LES:</p>\n\n<pre><code>// LES code has no built-in meaning. This just shows what it looks like.\n[DelayedWrite]\nOutput(\n if version &gt; 4.0 {\n $ProjectDir/Src/Foo;\n } else {\n $ProjectDir/Foo;\n }\n);\n</code></pre>\n\n<p>It doesn't have great tool support yet, though; currently the only LES library is for C#. Currently only one app is known to use LES: <a href=\"http://www.codeproject.com/Articles/664785/A-New-Parser-Generator-for-Csharp\" rel=\"nofollow noreferrer\">LLLPG</a>. It supports \"attributes\" but they are like C# attributes or Java annotations, not XML attributes.</p>\n\n<p>In theory you could use LES for data or markup, but there are no standards for how to do that:</p>\n\n<pre><code>body {\n '''Click here to use the World's '''\n a href=\"http://google.com\" {\n strong \"most popular\"; \" search engine!\"\n };\n};\n\npoint = (2, -3);\ntasteMap = { \"lemon\" -&gt; sour; \"sugar\" -&gt; sweet; \"grape\" -&gt; yummy };\n</code></pre>\n" }, { "answer_id": 30144859, "author": "intellimath", "author_id": 4743644, "author_profile": "https://Stackoverflow.com/users/4743644", "pm_score": 2, "selected": false, "text": "<p>There is <a href=\"http://intellimath.bitbucket.org/axon\" rel=\"nofollow noreferrer\">AXON</a> that cover the best of XML and JSON. Let's explain that in several examples.</p>\n\n<p><strong>AXON could be considered as shorter form of XML data.</strong> </p>\n\n<p>XML</p>\n\n<pre><code>&lt;person&gt;\n &lt;name&gt;Frank Martin&lt;/name&gt;\n &lt;age&gt;32&lt;/age&gt;\n &lt;/person&gt;\n</code></pre>\n\n<p>AXON</p>\n\n<pre><code>person{\n name{\"Frank Martin\"}\n age{32}}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>person\n name:\n \"Frank Martin\"\n age:\n 32\n</code></pre>\n\n<p>XML</p>\n\n<pre><code>&lt;person name=\"Frank Martin\" age=\"32\" /&gt;\n</code></pre>\n\n<p>AXON</p>\n\n<pre><code>person{name:\"Frank Martin\" age:32}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>person\n name: \"Frank Martin\"\n age: 32\n</code></pre>\n\n<p><strong>AXON contains some form of JSON.</strong></p>\n\n<p>JSON</p>\n\n<pre><code>{\"name\":\"Frank Martin\" \"age\":32 \"birth\":\"1965-12-24\"}\n</code></pre>\n\n<p>AXON</p>\n\n<pre><code>{name:\"Frank Martin\" age:32 birth:1965-12-24}\n</code></pre>\n\n<p><strong>AXON can represent combination of XML-like and JSON-like data.</strong></p>\n\n<p>AXON</p>\n\n<pre><code>table {\n fields {\n (\"id\" \"int\") (\"val1\" \"double\") (\"val2\" \"int\") (\"val3\" \"double\")\n }\n rows {\n (1 3.2 123 -3.4)\n (2 3.5 303 2.4)\n (3 2.3 235 -1.2)\n }\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>table\n fields\n (\"id\" \"int\")\n (\"val1\" \"double\")\n (\"val2\" \"int\") \n (\"val3\" \"double\")\n rows\n (1 3.2 123 -3.4)\n (2 3.5 303 2.4)\n (3 2.3 235 -1.2)\n</code></pre>\n\n<p>There is available the python library <a href=\"http://pypi.python.org/pypi/pyaxon\" rel=\"nofollow noreferrer\">pyaxon</a> now.</p>\n" }, { "answer_id": 39035417, "author": "wvxvw", "author_id": 5691066, "author_profile": "https://Stackoverflow.com/users/5691066", "pm_score": 3, "selected": false, "text": "<h1>TL;DR</h1>\n<p>Prolog wasn't mentioned here, but it is the best format I know of for representing data. Prolog programs, essentially, describe databases, with complex relationships between entities. Prolog is dead-simple to parse, whose probably only rival is S-expressions in this domain.</p>\n<h1>Full version</h1>\n<p>Programmers often &quot;forget&quot; what XML actually consists of. Usually referring to a very small subset of what it is. XML is a very complex format, with at least these parts: <a href=\"https://www.w3.org/TR/xmlschema-1/\" rel=\"noreferrer\">DTD schema language</a>, <a href=\"https://www.w3.org/TR/xmlschema11-1/\" rel=\"noreferrer\">XSD schema language</a>, <a href=\"https://www.w3.org/TR/xslt20/\" rel=\"noreferrer\">XSLT transformation language</a>, <a href=\"https://www.oasis-open.org/committees/relax-ng/spec-20011203.html\" rel=\"noreferrer\">RNG schema language</a> and <a href=\"https://www.w3.org/TR/xpath-31/\" rel=\"noreferrer\">XPath</a> (plus XQuery) languages - they all are part and parcel of XML standard. Plus, there are some apocrypha like <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST-WITHDRAWN/Ecma-357.pdf\" rel=\"noreferrer\">E4X</a>. Each and every one of them having their own versions, quite a bit of overlap, incompatibilities etc. Very few XML parsers in the wild implement all of them. Not to mention the multiple quirks and bugs of the popular parses, some leading to notable security issues like <a href=\"https://en.wikipedia.org/wiki/XML_external_entity_attack\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/XML_external_entity_attack</a> .</p>\n<p>Therefore, looking for an XML <em>alternative</em> is not a very good idea. You probably don't want to deal with the likes of XML at all.</p>\n<p>YAML is, probably, the second worst option. It's not as big as XML, but it was also designed in an attempt to cover all bases... more than ten times each... in different and unique ways nobody could ever conceive of. I'm yet to hear about a properly working YAML parser. Ruby, the language that uses YAML a lot, had famously <a href=\"https://www.sitepoint.com/anatomy-of-an-exploit-an-in-depth-look-at-the-rails-yaml-vulnerability/\" rel=\"noreferrer\">screwed up</a> because of it. All YAML parsers I've seen to date are copies of <a href=\"https://bitbucket.org/xi/libyaml\" rel=\"noreferrer\">libyaml</a>, which is itself a hand-written (not a generated from a formal description) kind of parser, with a code which is very difficult to verify for correctness (functions that span hundreds of lines with convoluted control flow). As was already mentioned, it completely contains JSON in it... on top of a handful of Unicode coding techniques... inside the same document, and probably a bunch of other stuff you don't want to hear about.</p>\n<p>JSON, on the other hand, is completely unlike the other two. You can probably write a JSON parser while waiting for downloading JSON parser artefact from your Maven Nexus. It can do very little, but at least you know what it's capable of. No surprises. (Except some discrepancies related to character escaping in strings and doubles encoding). No covert exploits. You cannot write comments in it. Multiline strings look bad. Whatever you mean by distinction between properties and attributes you can implement by more nested dictionaries.</p>\n<p>Suppose, though you wanted to right what XML wronged... well, then the popular stuff like YAML or JSON won't do it. Somehow fashion and rational thinking parted ways in programming some time in the mid seventies. So, you'll have to go back to where it all began with McCarthy, Hoare, Codd and Kowalski, figure out what is it you are trying to represent, and then see what's the best representation technique there is for whatever is that you are trying to represent :)</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
For me **usable** means that: * it's being used in real-wold * it has tools support. (at least some simple editor) * it has human readable syntax (no angle brackets please) Also I want it to be as close to XML as possible, i.e. there must be support for attributes as well as for properties. So, no [YAML](http://en.wikipedia.org/wiki/YAML) please. Currently, only one matching language comes to my mind - [JSON](http://en.wikipedia.org/wiki/JSON). Do you know any other alternatives?
YAML is a 100% superset of JSON, so it doesn't make sense to reject YAML and then consider JSON instead. YAML does everything JSON does, but YAML gives so much more too (like references). I can't think of anything XML can do that YAML can't, except to validate a document with a DTD, which in my experience has never been worth the overhead. But YAML is so much faster and easier to type and read than XML. As for attributes or properties, if you think about it, they don't truly "add" anything... it's just a notational shortcut to write something as an attribute of the node instead of putting it in its own child node. But if you like that convenience, you can often emulate it with YAML's inline lists/hashes. Eg: ``` <!-- XML --> <Director name="Spielberg"> <Movies> <Movie title="Jaws" year="1975"/> <Movie title="E.T." year="1982"/> </Movies> </Director> # YAML Director: name: Spielberg Movies: - Movie: {title: E.T., year: 1975} - Movie: {title: Jaws, year: 1982} ``` For me, the luxury of not having to write each node tag twice, combined with the freedom from all the angle-bracket litter makes YAML a preferred choice. I also actually like the lack of formal tag attributes, as that always seemed to me like a gray area of XML that needlessly introduced two sets of syntax (both when writing and traversing) for essentially the same concept. YAML does away with that confusion altogether.
51,502
<p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p> <p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p> <p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p> <pre><code>if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() </code></pre> <p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p> <pre><code>if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() </code></pre> <p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
[ { "answer_id": 51505, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 3, "selected": false, "text": "<p>You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea.</p>\n" }, { "answer_id": 51531, "author": "sherbang", "author_id": 5026, "author_profile": "https://Stackoverflow.com/users/5026", "pm_score": 2, "selected": false, "text": "<p>Perhaps the best thing would be to turn on \"show whitespace\" in your editor. Then you would have a visual indication of how far in each line is tabbed (usually a bunch of dots), and it will be more apparent when that changes.</p>\n" }, { "answer_id": 51551, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 4, "selected": false, "text": "<p>I like to put blank lines around blocks to make control flow more obvious. For example:</p>\n\n<pre><code>if foo:\n bar = baz\n\n while bar not biz:\n bar = i_am_going_to_find_you_biz_i_swear_on_my_life()\n\ndid_i_not_warn_you_biz()\nmy_father_is_avenged()\n</code></pre>\n" }, { "answer_id": 51570, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 3, "selected": false, "text": "<p>Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more.</p>\n\n<p>If you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes.</p>\n" }, { "answer_id": 52090, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 6, "selected": true, "text": "<p>Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.</p>\n" }, { "answer_id": 52111, "author": "elarson", "author_id": 5434, "author_profile": "https://Stackoverflow.com/users/5434", "pm_score": -1, "selected": false, "text": "<p>I would look in to understanding more details about Python syntax. Often times if a piece of code looks odd, there usually is a better way to write it. For example, in the above example:</p>\n\n<pre><code>bar = foo if baz else None\nwhile bar not biz:\n bar = i_am_going_to_find_you_biz_i_swear_on_my_life()\n\ndid_i_not_warn_you_biz()\nmy_father_is_avenged()\n</code></pre>\n\n<p>While it is a small change, it might help the readability. Also, in all honesty, I've never used a while loop, so there is a good change you would end up with a nice concise list comprehension or for loop instead. ;)</p>\n" }, { "answer_id": 3054853, "author": "Lloeki", "author_id": 368409, "author_profile": "https://Stackoverflow.com/users/368409", "pm_score": 0, "selected": false, "text": "<pre><code>from __future__ import braces\n</code></pre>\n\n<p>Need I say more? :)</p>\n\n<p>Seriously, <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, 'Blank lines', §4 is the official way to do it.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342/" ]
I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects. However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read. For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing): ``` if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() ``` The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this: ``` if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() ``` And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.
Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.
51,520
<p>Given a path such as <code>&quot;mydir/myfile.txt&quot;</code>, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:</p> <pre><code>&quot;C:/example/cwd/mydir/myfile.txt&quot; </code></pre>
[ { "answer_id": 51523, "author": "sherbang", "author_id": 5026, "author_profile": "https://Stackoverflow.com/users/5026", "pm_score": 11, "selected": true, "text": "<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.abspath(\"mydir/myfile.txt\")\n'C:/example/cwd/mydir/myfile.txt'\n</code></pre>\n\n<p>Also works if it is already an absolute path:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.abspath(\"C:/example/cwd/mydir/myfile.txt\")\n'C:/example/cwd/mydir/myfile.txt'\n</code></pre>\n" }, { "answer_id": 58417, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 5, "selected": false, "text": "<p>Install a third-party <a href=\"https://github.com/jaraco/path\" rel=\"noreferrer\">path module</a> (found on <a href=\"https://pypi.org/project/path/\" rel=\"noreferrer\"><code>PyPI</code></a>), it wraps all the <code>os.path</code> functions and other related functions into methods on an object that can be used wherever strings are used:</p>\n<pre><code>&gt;&gt;&gt; from path import path\n&gt;&gt;&gt; path('mydir/myfile.txt').abspath()\n'C:\\\\example\\\\cwd\\\\mydir\\\\myfile.txt'\n</code></pre>\n" }, { "answer_id": 15325066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Today you can also use the <code>unipath</code> package which was based on <code>path.py</code>: <a href=\"http://sluggo.scrapping.cc/python/unipath/\" rel=\"noreferrer\">http://sluggo.scrapping.cc/python/unipath/</a></p>\n\n<pre><code>&gt;&gt;&gt; from unipath import Path\n&gt;&gt;&gt; absolute_path = Path('mydir/myfile.txt').absolute()\nPath('C:\\\\example\\\\cwd\\\\mydir\\\\myfile.txt')\n&gt;&gt;&gt; str(absolute_path)\nC:\\\\example\\\\cwd\\\\mydir\\\\myfile.txt\n&gt;&gt;&gt;\n</code></pre>\n\n<p>I would recommend using this package as it offers <a href=\"http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html\" rel=\"noreferrer\">a clean interface to common os.path utilities</a>.</p>\n" }, { "answer_id": 26539947, "author": "twasbrillig", "author_id": 2213647, "author_profile": "https://Stackoverflow.com/users/2213647", "pm_score": 7, "selected": false, "text": "<p>You could use the new Python 3.4 library <code>pathlib</code>. (You can also get it for Python 2.6 or 2.7 using <code>pip install pathlib</code>.) The authors <a href=\"http://www.python.org/dev/peps/pep-0428/#abstract\">wrote</a>: \"The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.\"</p>\n\n<p>To get an absolute path in Windows:</p>\n\n<pre><code>&gt;&gt;&gt; from pathlib import Path\n&gt;&gt;&gt; p = Path(\"pythonw.exe\").resolve()\n&gt;&gt;&gt; p\nWindowsPath('C:/Python27/pythonw.exe')\n&gt;&gt;&gt; str(p)\n'C:\\\\Python27\\\\pythonw.exe'\n</code></pre>\n\n<p>Or on UNIX:</p>\n\n<pre><code>&gt;&gt;&gt; from pathlib import Path\n&gt;&gt;&gt; p = Path(\"python3.4\").resolve()\n&gt;&gt;&gt; p\nPosixPath('/opt/python3/bin/python3.4')\n&gt;&gt;&gt; str(p)\n'/opt/python3/bin/python3.4'\n</code></pre>\n\n<p>Docs are here: <a href=\"https://docs.python.org/3/library/pathlib.html\">https://docs.python.org/3/library/pathlib.html</a></p>\n" }, { "answer_id": 49639219, "author": "chikwapuro", "author_id": 4954966, "author_profile": "https://Stackoverflow.com/users/4954966", "pm_score": 2, "selected": false, "text": "<p>if you are on a mac </p>\n\n<pre><code>import os\nupload_folder = os.path.abspath(\"static/img/users\")\n</code></pre>\n\n<p>this will give you a full path:</p>\n\n<pre><code>print(upload_folder)\n</code></pre>\n\n<p>will show the following path:</p>\n\n<pre><code>&gt;&gt;&gt;/Users/myUsername/PycharmProjects/OBS/static/img/user\n</code></pre>\n" }, { "answer_id": 51179697, "author": "BND", "author_id": 4088081, "author_profile": "https://Stackoverflow.com/users/4088081", "pm_score": 0, "selected": false, "text": "<p>In case someone is using python and linux and looking for full path to file:</p>\n\n<pre><code>&gt;&gt;&gt; path=os.popen(\"readlink -f file\").read()\n&gt;&gt;&gt; print path\nabs/path/to/file\n</code></pre>\n" }, { "answer_id": 53950650, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 5, "selected": false, "text": "<p>Update for Python 3.4+ <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code></a> that actually answers the question:</p>\n\n<pre><code>from pathlib import Path\n\nrelative = Path(\"mydir/myfile.txt\")\nabsolute = relative.absolute() # absolute is a Path object\n</code></pre>\n\n<p>If you only need a temporary string, keep in mind that you can use <code>Path</code> objects with all the relevant functions in <a href=\"https://docs.python.org/3/library/os.path.html\" rel=\"noreferrer\"><code>os.path</code></a>, including of course <a href=\"https://docs.python.org/3/library/os.path.html#os.path.abspath\" rel=\"noreferrer\"><code>abspath</code></a>:</p>\n\n<pre><code>from os.path import abspath\n\nabsolute = abspath(relative) # absolute is a str object\n</code></pre>\n" }, { "answer_id": 54929069, "author": "Lucas Azevedo", "author_id": 4075155, "author_profile": "https://Stackoverflow.com/users/4075155", "pm_score": 4, "selected": false, "text": "<p>This <strong>always</strong> gets the right filename of the current script, even when it is called from within another script. It is especially useful when using <code>subprocess</code>.</p>\n\n<pre><code>import sys,os\n\nfilename = sys.argv[0]\n</code></pre>\n\n<p>from there, you can get the script's full path with:</p>\n\n<pre><code>&gt;&gt;&gt; os.path.abspath(filename)\n'/foo/bar/script.py'\n</code></pre>\n\n<p>It also makes easier to navigate folders by just appending <code>/..</code> as many times as you want to go 'up' in the directories' hierarchy. </p>\n\n<p>To get the cwd:</p>\n\n<pre><code>&gt;&gt;&gt; os.path.abspath(filename+\"/..\")\n'/foo/bar'\n</code></pre>\n\n<p>For the parent path:</p>\n\n<pre><code>&gt;&gt;&gt; os.path.abspath(filename+\"/../..\")\n'/foo'\n</code></pre>\n\n<p>By combining <code>\"/..\"</code> with other filenames, you can access any file in the system.</p>\n" }, { "answer_id": 55034470, "author": "benjimin", "author_id": 5104777, "author_profile": "https://Stackoverflow.com/users/5104777", "pm_score": 5, "selected": false, "text": "<pre><code>import os\nos.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))\n</code></pre>\n\n<p>Note that <code>expanduser</code> is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading <code>~/</code>(the tilde refers to the user's home directory), and <code>expandvars</code> takes care of any other environment variables (like <code>$HOME</code>).</p>\n" }, { "answer_id": 68986016, "author": "Dhiaa Shalabi", "author_id": 11795918, "author_profile": "https://Stackoverflow.com/users/11795918", "pm_score": 3, "selected": false, "text": "<p>You can use this to get absolute path of a specific file.</p>\n<pre><code>from pathlib import Path\n\nfpath = Path('myfile.txt').absolute()\n\nprint(fpath)\n</code></pre>\n" }, { "answer_id": 71029352, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>Given a path such as <code>mydir/myfile.txt</code>, how do I find the file's absolute path relative to the current working directory in Python?</p>\n</blockquote>\n<p>I would do it like this,</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os.path\nos.path.join( os.getcwd(), 'mydir/myfile.txt' )\n</code></pre>\n<p>That returns <code>'/home/ecarroll/mydir/myfile.txt'</code></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
Given a path such as `"mydir/myfile.txt"`, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with: ``` "C:/example/cwd/mydir/myfile.txt" ```
``` >>> import os >>> os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' ``` Also works if it is already an absolute path: ``` >>> import os >>> os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' ```
51,526
<p>I have a list of structs and I want to change one element. For example :</p> <pre><code>MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter"); </code></pre> <p>Now I want to change one element:</p> <pre><code>MyList[1].Name = "bob" </code></pre> <p>However, whenever I try and do this I get the following error:</p> <blockquote> <p>Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable</p> </blockquote> <p>If I use a list of classes, the problem doesn't occur.</p> <p>I guess the answer has to do with structs being a value type.</p> <p>So, if I have a list of structs should I treat them as <em>read-only</em>? If I need to change elements in a list then I should use classes and not structs?</p>
[ { "answer_id": 51537, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 6, "selected": true, "text": "<pre><code>MyList[1] = new MyStruct(\"bob\");\n</code></pre>\n\n<p>structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).</p>\n\n<p>In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.</p>\n" }, { "answer_id": 51585, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": false, "text": "<p>Not quite. Designing a type as class or struct shouldn't be driven by your need to store it in collections :) You should look at the 'semantics' needed</p>\n\n<p>The problem you're seeing is due to value type semantics. Each value type variable/reference is a new instance. When you say\n</p>\n\n<pre><code>Struct obItem = MyList[1];\n</code></pre>\n\n<p>what happens is that a new instance of the struct is created and all members are copied one by one. So that you have a clone of MyList[1] i.e. 2 instances.\nNow if you modify obItem, it doesn't affect the original.</p>\n\n<pre><code>obItem.Name = \"Gishu\"; // MyList[1].Name still remains \"peter\"\n</code></pre>\n\n<p>Now bear with me for 2 mins here (This takes a while to gulp down.. it did for me :)\nIf you really need structs to be stored in a collection and modified like you indicated in your question, you'll have to make your struct expose an interface (<em>However this will result in boxing</em>). You can then modify the actual struct via an interface reference, which refers to the boxed object. </p>\n\n<p>The following code snippet illustrates what I just said above</p>\n\n<pre><code>public interface IMyStructModifier\n{\n String Name { set; }\n}\npublic struct MyStruct : IMyStructModifier ...\n\nList&lt;Object&gt; obList = new List&lt;object&gt;();\nobList.Add(new MyStruct(\"ABC\"));\nobList.Add(new MyStruct(\"DEF\"));\n\nMyStruct temp = (MyStruct)obList[1];\ntemp.Name = \"Gishu\";\nforeach (MyStruct s in obList) // =&gt; \"ABC\", \"DEF\"\n{\n Console.WriteLine(s.Name);\n}\n\nIMyStructModifier temp2 = obList[1] as IMyStructModifier;\ntemp2.Name = \"Now Gishu\";\nforeach (MyStruct s in obList) // =&gt; \"ABC\", \"Now Gishu\"\n{\n Console.WriteLine(s.Name);\n}\n</code></pre>\n\n<p>HTH. Good Question.<br>\n<strong>Update:</strong> @Hath - you had me running to check if I overlooked something that simple. (It would be inconsistent if setter properties dont and methods did - the .Net universe is still balanced :)<br>\n<em>Setter method doesn't work</em><br>\nobList2[1] returns a copy whose state would be modified. Original struct in list stays unmodified. So Set-via-Interface seems to be only way to do it.</p>\n\n<pre><code>List&lt;MyStruct&gt; obList2 = new List&lt;MyStruct&gt;();\nobList2.Add(new MyStruct(\"ABC\"));\nobList2.Add(new MyStruct(\"DEF\"));\nobList2[1].SetName(\"WTH\");\nforeach (MyStruct s in obList2) // =&gt; \"ABC\", \"DEF\"\n{\n Console.WriteLine(s.Name);\n}\n</code></pre>\n" }, { "answer_id": 53038, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 4, "selected": false, "text": "<p>It's not so much that structs are \"immutable.\" </p>\n\n<p>The real underlying issue is that structs are a Value type, not a Reference type. So when you pull out a \"reference\" to the struct from the list, it is creating a new copy of the entire struct. So any changes you make on it are changing the copy, not the original version in the list. </p>\n\n<p>Like Andrew states, you have to replace the entire struct. As that point though I think you have to ask yourself why you are using a struct in the first place (instead of a class). Make sure you aren't doing it around premature optimization concerns.</p>\n" }, { "answer_id": 8558544, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "<p>There is nothing wrong with structs that have exposed fields, or that allow mutation via property setters. Structs which mutate themselves in response to methods or property getters, however, are dangerous because the system will allow methods or property getters to be called on temporary struct instances; if the methods or getters make changes to the struct, those changes will end up getting discarded.</p>\n\n<p>Unfortunately, as you note, the collections built into .net are really feeble at exposing value-type objects contained therein. Your best bet is usually to do something like:</p>\n\n<pre>\n MyStruct temp = myList[1];\n temp.Name = \"Albert\";\n myList[1] = temp;\n</pre>\n\n<p>Somewhat annoying, and not at all threadsafe. Still an improvement over a List of a class type, where doing the same thing might require:</p>\n\n<pre>\n myList[1].Name = \"Albert\";\n</pre>\n\n<p>but it might also require:</p>\n\n<pre>\n myList[1] = myList[1].Withname(\"Albert\");\n</pre>\n\n<p>or maybe</p>\n\n<pre>\n myClass temp = (myClass)myList[1].Clone();\n temp.Name = \"Albert\";\n myList[1] = temp;\n</pre>\n\n<p>or maybe some other variation. One really wouldn't be able to know unless one examined myClass as well as the other code that put things in the list. It's entirely possible that one might not be able to know whether the first form is safe without examining code in assemblies to which one does not have access. By contrast, if Name is an exposed field of MyStruct, the method I gave for updating it will work, regardless of what else MyStruct contains, or regardless of what other things may have done with myList before the code executes or what they may expect to do with it after.</p>\n" }, { "answer_id": 56895908, "author": "David Klempfner", "author_id": 2063755, "author_profile": "https://Stackoverflow.com/users/2063755", "pm_score": 2, "selected": false, "text": "<p>In addition to the other answers, I thought it could be helpful to explain why the compiler complains.</p>\n\n<p>When you call <code>MyList[1].Name</code>, unlike an array, the <code>MyList[1]</code> actually calls the indexer method behind the scenes. </p>\n\n<p>Any time a method returns an instance of a struct, you're getting a copy of that struct (unless you use ref/out).</p>\n\n<p>So you're getting a copy and setting the <code>Name</code> property on a copy, which is about to be discarded since the copy wasn't stored in a variable anywhere.</p>\n\n<p><a href=\"http://reinventingthewheel.azurewebsites.net/ModifyStruct.aspx\" rel=\"nofollow noreferrer\">This</a> tutorial describes what's going on in more detail (including the generated CIL code).</p>\n" }, { "answer_id": 68538262, "author": "Bob Bryan", "author_id": 643828, "author_profile": "https://Stackoverflow.com/users/643828", "pm_score": 0, "selected": false, "text": "<p>As of C#9, I am not aware of any way to pull a struct by reference out of a generic container, including <code>List&lt;T&gt;</code>. As Jason Olson's answer said:</p>\n<p><em>The real underlying issue is that structs are a Value type, not a Reference type. So when you pull out a &quot;reference&quot; to the struct from the list, it is creating a new copy of the entire struct. So any changes you make on it are changing the copy, not the original version in the list.</em></p>\n<p>So, this can be pretty inefficient. SuperCat's answer, even though it is correct, compounds that inefficiency by copying the updated struct back into the list.</p>\n<p>If you are interested in maximizing the performance of structs, then use an array instead of <code>List&lt;T&gt;</code>. The indexer in an array returns a reference to the struct and does not copy the entire struct out like the <code>List&lt;T&gt;</code> indexer. Also, an array is more efficient than <code>List&lt;T&gt;</code>.</p>\n<p>If you need to grow the array over time, then create a generic class that works like <code>List&lt;T&gt;</code>, but uses arrays underneath.</p>\n<p>There is an alternative solution. Create a class that incorporates the structure and create public methods to call the methods of that structure for the required functionality. Use a <code>List&lt;T&gt;</code> and specify the class for T. The structure may also be returned via a ref returns method or ref property that returns a reference to the structure.</p>\n<p>The advantage of this approach is that it can be used with any generic data structure, like <code>Dictionary&lt;TKey, TValue&gt;</code>. When pulling a struct out of a <code>Dictionary&lt;TKey, TValue&gt;</code>, it also copies the struct to a new instance, just like <code>List&lt;T&gt;</code>. I suspect that this is true for all C# generic containers.</p>\n<p>Code example:</p>\n<pre><code>public struct Mutable\n{\n private int _x;\n\n public Mutable(int x)\n {\n _x = x;\n }\n\n public int X =&gt; _x; // Property\n\n public void IncrementX() { _x++; }\n}\n\npublic class MutClass\n{\n public Mutable Mut;\n //\n public MutClass()\n {\n Mut = new Mutable(2);\n }\n\n public MutClass(int x)\n {\n Mut = new Mutable(x);\n }\n\n public ref Mutable MutRef =&gt; ref Mut; // Property\n\n public ref Mutable GetMutStruct()\n {\n return ref Mut;\n }\n}\n\nprivate static void TestClassList()\n{\n // This test method shows that a list of a class that holds a struct\n // may be used to efficiently obtain the struct by reference.\n //\n var mcList = new List&lt;MutClass&gt;();\n var mClass = new MutClass(1);\n mcList.Add(mClass);\n ref Mutable mutRef = ref mcList[0].MutRef;\n // Increment the x value defined in the struct.\n mutRef.IncrementX();\n // Now verify that the X values match.\n if (mutRef.X != mClass.Mut.X)\n Console.Error.WriteLine(&quot;TestClassList: Error - the X values do not match.&quot;);\n else\n Console.Error.WriteLine(&quot;TestClassList: Success - the X values match!&quot;);\n}\n</code></pre>\n<p>Output on console window:</p>\n<pre><code>TestClassList: Success - the X values match!\n</code></pre>\n<p>For the following line:</p>\n<pre><code>ref Mutable mutRef = ref mcList[0].MutRef;\n</code></pre>\n<p>I initially and inadvertently left out the ref after the equal sign. The compiler didn't complain, but it did produce a copy of the struct and the test failed when it ran. After adding the ref, it ran correctly.</p>\n" }, { "answer_id": 72507955, "author": "DaemonFire", "author_id": 11522147, "author_profile": "https://Stackoverflow.com/users/11522147", "pm_score": 2, "selected": false, "text": "<p>In .Net 5.0, you can use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.collectionsmarshal.asspan?view=net-5.0\" rel=\"nofollow noreferrer\"><code>CollectionsMarshal.AsSpan()</code></a> (<a href=\"https://source.dot.net/#System.Private.CoreLib/CollectionsMarshal.cs,b48f5c98e43560f8\" rel=\"nofollow noreferrer\">source</a>, <a href=\"https://github.com/dotnet/runtime/issues/27061\" rel=\"nofollow noreferrer\">GitHub issue</a>) to get the underlying array of a <code>List&lt;T&gt;</code> as a <code>Span&lt;T&gt;</code>.</p>\n<pre><code>var listOfStructs = new List&lt;MyStruct&gt; { new MyStruct() };\nSpan&lt;MyStruct&gt; spanOfStructs = CollectionsMarshal.AsSpan(listOfStructs);\nspanOfStructs[0].Value = 42;\nAssert.Equal(42, spanOfStructs[0].Value);\n\nstruct MyStruct { public int Value { get; set; } }\n</code></pre>\n<p>This works because the <code>Span&lt;T&gt;</code> indexer uses a C# 7.0 feature called ref returns. The indexer is declared with a <code>ref T</code> return type, which provides semantics like that of indexing into arrays, returning a reference to the actual storage location.</p>\n<p>In comparison the <code>List&lt;T&gt;</code> indexer is not ref returning instead returning a copy of what lives at that location.</p>\n<p>Keep in mind that this is still unsafe: if the <code>List&lt;T&gt;</code> reallocates the array, the <code>Span&lt;T&gt;</code> previously returned by <code>CollectionsMarshal.AsSpan</code> won't reflect any further changes to the <code>List&lt;T&gt;</code>. (Which is why the method is hidden in the <code>System.Runtime.InteropServices.CollectionsMarshal</code> class.)</p>\n<p><a href=\"https://stackoverflow.com/a/60514418/11522147\">Source</a></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3989/" ]
I have a list of structs and I want to change one element. For example : ``` MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter"); ``` Now I want to change one element: ``` MyList[1].Name = "bob" ``` However, whenever I try and do this I get the following error: > > Cannot modify the return value of > System.Collections.Generic.List.this[int]‘ because it is not > a variable > > > If I use a list of classes, the problem doesn't occur. I guess the answer has to do with structs being a value type. So, if I have a list of structs should I treat them as *read-only*? If I need to change elements in a list then I should use classes and not structs?
``` MyList[1] = new MyStruct("bob"); ``` structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created). In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.
51,553
<p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p> <pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples; </code></pre> <p>Is this normal behaviour when using a SQL database?</p> <p>The schema (the table holds responses to a survey):</p> <pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer); \copy tuples from '350,000 responses.csv' delimiter as ',' </code></pre> <p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p> <pre><code>java 1.5 threads ~ 7 ms java 1.5 ~ 10 ms python 2.5 numpy ~ 18 ms python 2.5 ~ 370 ms </code></pre> <p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p> <p>Tunings i've tried without success include (blindly following some web advice):</p> <pre><code>increased the shared memory available to Postgres to 256MB increased the working memory to 2MB disabled connection and statement logging used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL </code></pre> <p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p> <p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p> <hr> <p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p> <p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p> <p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p> <p>The Postgres query doesn't change timing on subsequent runs.</p> <p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
[ { "answer_id": 51668, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>I don't think that your results are all that surprising -- if anything it is that Postgres is so fast.</p>\n\n<p>Does the Postgres query run faster a second time once it has had a chance to cache the data? To be a little fairer your test for Java and Python should cover the cost of acquiring the data in the first place (ideally loading it off disk).</p>\n\n<p>If this performance level is a problem for your application in practice but you need a RDBMS for other reasons then you could look at <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noreferrer\">memcached</a>. You would then have faster cached access to raw data and could do the calculations in code.</p>\n" }, { "answer_id": 51745, "author": "Hanno Fietz", "author_id": 2077, "author_profile": "https://Stackoverflow.com/users/2077", "pm_score": 4, "selected": false, "text": "<p>I would say your test scheme is not really useful. To fulfill the db query, the db server goes through several steps:</p>\n\n<ol>\n<li>parse the SQL</li>\n<li>work up a query plan, i. e. decide on which indices to use (if any), optimize etc.</li>\n<li>if an index is used, search it for the pointers to the actual data, then go to the appropriate location in the data or</li>\n<li>if no index is used, scan <i>the whole table</i> to determine which rows are needed</li>\n<li>load the data from disk into a temporary location (hopefully, but not necessarily, memory)</li>\n<li>perform the count() and avg() calculations</li>\n</ol>\n\n<p>So, creating an array in Python and getting the average basically skips all these steps save the last one. As disk I/O is among the most expensive operations a program has to perform, this is a major flaw in the test (see also the answers to <a href=\"https://stackoverflow.com/questions/26021/how-is-data-compression-more-effective-than-indexing-for-search-performance\">this question</a> I asked here before). Even if you read the data from disk in your other test, the process is completely different and it's hard to tell how relevant the results are.</p>\n\n<p>To obtain more information about where Postgres spends its time, I would suggest the following tests:</p>\n\n<ul>\n<li>Compare the execution time of your query to a SELECT without the aggregating functions (i. e. cut step 5)</li>\n<li>If you find that the aggregation leads to a significant slowdown, try if Python does it faster, obtaining the raw data through the plain SELECT from the comparison.</li>\n</ul>\n\n<p>To speed up your query, reduce disk access first. I doubt very much that it's the aggregation that takes the time.</p>\n\n<p>There's several ways to do that:</p>\n\n<ul>\n<li>Cache data (in memory!) for subsequent access, either via the db engine's own capabilities or with tools like memcached</li>\n<li>Reduce the size of your stored data</li>\n<li>Optimize the use of indices. Sometimes this can mean to skip index use altogether (after all, it's disk access, too). For MySQL, I seem to remember that it's recommended to skip indices if you assume that the query fetches more than 10% of all the data in the table.</li>\n<li>If your query makes good use of indices, I know that for MySQL databases it helps to put indices and data on separate physical disks. However, I don't know whether that's applicable for Postgres.</li>\n<li>There also might be more sophisticated problems such as swapping rows to disk if for some reason the result set can't be completely processed in memory. But I would leave that kind of research until I run into serious performance problems that I can't find another way to fix, as it requires knowledge about a lot of little under-the-hood details in your process.</li>\n</ul>\n\n<p><b>Update:</b></p>\n\n<p><i>I just realized that you seem to have no use for indices for the above query and most likely aren't using any, too, so my advice on indices probably wasn't helpful. Sorry. Still, I'd say that the aggregation is not the problem but disk access is. I'll leave the index stuff in, anyway, it might still have some use.</i></p>\n" }, { "answer_id": 51817, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 1, "selected": false, "text": "<p>One other thing that an RDBMS generally does for you is to provide concurrency by protecting you from simultaneous access by another process. This is done by placing locks, and there's some overhead from that.</p>\n\n<p>If you're dealing with entirely static data that never changes, and especially if you're in a basically \"single user\" scenario, then using a relational database doesn't necessarily gain you much benefit.</p>\n" }, { "answer_id": 51933, "author": "Jacob Rigby", "author_id": 5357, "author_profile": "https://Stackoverflow.com/users/5357", "pm_score": 2, "selected": false, "text": "<p>Those are very detailed answers, but they mostly beg the question, how do I get these benefits without leaving Postgres given that the data easily fits into memory, requires concurrent reads but no writes and is queried with the same query over and over again.</p>\n\n<p>Is it possible to precompile the query and optimization plan? I would have thought the stored procedure would do this, but it doesn't really help.</p>\n\n<p>To avoid disk access it's necessary to cache the whole table in memory, can I force Postgres to do that? I think it's already doing this though, since the query executes in just 200 ms after repeated runs.</p>\n\n<p>Can I tell Postgres that the table is read only, so it can optimize any locking code?</p>\n\n<p>I think it's possible to estimate the query construction costs with an empty table (timings range from 20-60 ms) </p>\n\n<p>I still can't see why the Java/Python tests are invalid. Postgres just isn't doing that much more work (though I still haven't addressed the concurrency aspect, just the caching and query construction)</p>\n\n<p>UPDATE: \nI don't think it's fair to compare the SELECTS as suggested by pulling 350,000 through the driver and serialization steps into Python to run the aggregation, nor even to omit the aggregation as the overhead in formatting and displaying is hard to separate from the timing. If both engines are operating on in memory data, it should be an apples to apples comparison, I'm not sure how to guarantee that's already happening though.</p>\n\n<p>I can't figure out how to add comments, maybe i don't have enough reputation?</p>\n" }, { "answer_id": 51976, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>You need to increase postgres' caches to the point where the whole working set fits into memory before you can expect to see perfomance comparable to doing it in-memory with a program.</p>\n" }, { "answer_id": 52006, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 5, "selected": true, "text": "<p>Postgres is doing a lot more than it looks like (maintaining data consistency for a start!)</p>\n\n<p>If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up.</p>\n\n<p>(Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation).</p>\n\n<p><a href=\"http://jonathangardner.net/tech/w/PostgreSQL/Materialized_Views\" rel=\"noreferrer\">Materialized Views</a></p>\n\n<p>Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back.</p>\n\n<p>I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk.</p>\n\n<p>The real question is, is 200ms fast enough?</p>\n\n<p>-------------- More --------------------</p>\n\n<p>I was interested in solving this using materialized views, since I've never really played with them. This is in oracle.</p>\n\n<p>First I created a MV which refreshes every minute.</p>\n\n<pre><code>create materialized view mv_so_x \nbuild immediate \nrefresh complete \nSTART WITH SYSDATE NEXT SYSDATE + 1/24/60\n as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;\n</code></pre>\n\n<p>While its refreshing, there is no rows returned</p>\n\n<pre><code>SQL&gt; select * from mv_so_x;\n\nno rows selected\n\nElapsed: 00:00:00.00\n</code></pre>\n\n<p>Once it refreshes, its MUCH faster than doing the raw query</p>\n\n<pre><code>SQL&gt; select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;\n\n COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)\n---------- ---------- ---------- ---------- ----------\n 1899459 7495.38839 22.2905454 5.00276131 2.13432836\n\nElapsed: 00:00:05.74\nSQL&gt; select * from mv_so_x;\n\n COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)\n---------- ---------- ---------- ---------- ----------\n 1899459 7495.38839 22.2905454 5.00276131 2.13432836\n\nElapsed: 00:00:00.00\nSQL&gt; \n</code></pre>\n\n<p>If we insert into the base table, the result is not immediately viewable view the MV.</p>\n\n<pre><code>SQL&gt; insert into so_x values (1,2,3,4,5);\n\n1 row created.\n\nElapsed: 00:00:00.00\nSQL&gt; commit;\n\nCommit complete.\n\nElapsed: 00:00:00.00\nSQL&gt; select * from mv_so_x;\n\n COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)\n---------- ---------- ---------- ---------- ----------\n 1899459 7495.38839 22.2905454 5.00276131 2.13432836\n\nElapsed: 00:00:00.00\nSQL&gt; \n</code></pre>\n\n<p>But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want.</p>\n\n<pre><code>SQL&gt; /\n\n COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)\n---------- ---------- ---------- ---------- ----------\n 1899460 7495.35823 22.2905352 5.00276078 2.17647059\n\nElapsed: 00:00:00.00\nSQL&gt; \n</code></pre>\n\n<p>This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate.</p>\n" }, { "answer_id": 52179, "author": "Jacob Rigby", "author_id": 5357, "author_profile": "https://Stackoverflow.com/users/5357", "pm_score": 0, "selected": false, "text": "<p>Thanks for the Oracle timings, that's the kind of stuff I'm looking for (disappointing though :-)</p>\n\n<p>Materialized views are probably worth considering as I think I can precompute the most interesting forms of this query for most users.</p>\n\n<p>I don't think query round trip time should be very high as i'm running the the queries on the same machine that runs Postgres, so it can't add much latency?</p>\n\n<p>I've also done some checking into the cache sizes, and it seems Postgres relies on the OS to handle caching, they specifically mention BSD as the ideal OS for this, so I thinking Mac OS ought to be pretty smart about bringing the table into memory. Unless someone has more specific params in mind I think more specific caching is out of my control.</p>\n\n<p>In the end I can probably put up with 200 ms response times, but knowing that 7 ms is a possible target makes me feel unsatisfied, as even 20-50 ms times would enable more users to have more up to date queries and get rid of a lots of caching and precomputed hacks.</p>\n\n<p>I just checked the timings using MySQL 5 and they are slightly worse than Postgres. So barring some major caching breakthroughs, I guess this is what I can expect going the relational db route.</p>\n\n<p>I wish I could up vote some of your answers, but I don't have enough points yet.</p>\n" }, { "answer_id": 53303, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>I'm a MS-SQL guy myself, and we'd use <a href=\"http://msdn.microsoft.com/en-us/library/ms178015.aspx\" rel=\"nofollow noreferrer\">DBCC PINTABLE</a> to keep a table cached, and <a href=\"http://msdn.microsoft.com/en-us/library/ms184361.aspx\" rel=\"nofollow noreferrer\">SET STATISTICS IO</a> to see that it's reading from cache, and not disk. </p>\n\n<p>I can't find anything on Postgres to mimic PINTABLE, but <a href=\"http://www.postgresql.org/docs/current/static/pgbuffercache.html\" rel=\"nofollow noreferrer\">pg_buffercache</a> seems to give details on what is in the cache - you may want to check that, and see if your table is actually being cached.</p>\n\n<p>A quick back of the envelope calculation makes me suspect that you're paging from disk. Assuming Postgres uses 4-byte integers, you have (6 * 4) bytes per row, so your table is a minimum of (24 * 350,000) bytes ~ 8.4MB. Assuming 40 MB/s sustained throughput on your HDD, you're looking at right around 200ms to read the data (which, <a href=\"https://stackoverflow.com/questions/51553/why-are-sql-aggregate-functions-so-much-slower-than-python-and-java-or-poor-man#51668\">as pointed out</a>, should be where almost all of the time is being spent). </p>\n\n<p>Unless I screwed up my math somewhere, I don't see how it's possible that you are able to read 8MB into your Java app and process it in the times you're showing - unless that file is already cached by either the drive or your OS.</p>\n" }, { "answer_id": 53333, "author": "Jacob Rigby", "author_id": 5357, "author_profile": "https://Stackoverflow.com/users/5357", "pm_score": 3, "selected": false, "text": "<p>I retested with MySQL specifying ENGINE = MEMORY and it doesn't change a thing (still 200 ms). Sqlite3 using an in-memory db gives similar timings as well (250 ms).</p>\n\n<p>The math <a href=\"https://stackoverflow.com/questions/51553/why-are-sql-aggregate-functions-so-much-slower-than-python-and-java-or-poor-man#53303\">here</a> looks correct (at least the size, as that's how big the sqlite db is :-)</p>\n\n<p>I'm just not buying the disk-causes-slowness argument as there is every indication the tables are in memory (the postgres guys all warn against trying too hard to pin tables to memory as they swear the OS will do it better than the programmer)</p>\n\n<p>To clarify the timings, the Java code is not reading from disk, making it a totally unfair comparison if Postgres is reading from the disk and calculating a complicated query, but that's really besides the point, the DB should be smart enough to bring a small table into memory and precompile a stored procedure IMHO.</p>\n\n<p>UPDATE (in response to the first comment below):</p>\n\n<p><em>I'm not sure how I'd test the query without using an aggregation function in a way that would be fair, since if i select all of the rows it'll spend tons of time serializing and formatting everything. I'm not saying that the slowness is due to the aggregation function, it could still be just overhead from concurrency, integrity, and friends. I just don't know how to isolate the aggregation as the sole independent variable.</em></p>\n" }, { "answer_id": 53713, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 1, "selected": false, "text": "<p>Are you using TCP to access the Postgres? In that case Nagle is messing with your timing.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5357/" ]
I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows): ``` SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples; ``` Is this normal behaviour when using a SQL database? The schema (the table holds responses to a survey): ``` CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer); \copy tuples from '350,000 responses.csv' delimiter as ',' ``` I wrote some tests in Java and Python for context and they crush SQL (except for pure python): ``` java 1.5 threads ~ 7 ms java 1.5 ~ 10 ms python 2.5 numpy ~ 18 ms python 2.5 ~ 370 ms ``` Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown) Tunings i've tried without success include (blindly following some web advice): ``` increased the shared memory available to Postgres to 256MB increased the working memory to 2MB disabled connection and statement logging used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL ``` So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help. --- No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest. The sqlite3 timing is driven by the Python program and is running from disk (not :memory:) I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data. The Postgres query doesn't change timing on subsequent runs. I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)
Postgres is doing a lot more than it looks like (maintaining data consistency for a start!) If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up. (Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation). [Materialized Views](http://jonathangardner.net/tech/w/PostgreSQL/Materialized_Views) Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back. I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk. The real question is, is 200ms fast enough? -------------- More -------------------- I was interested in solving this using materialized views, since I've never really played with them. This is in oracle. First I created a MV which refreshes every minute. ``` create materialized view mv_so_x build immediate refresh complete START WITH SYSDATE NEXT SYSDATE + 1/24/60 as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x; ``` While its refreshing, there is no rows returned ``` SQL> select * from mv_so_x; no rows selected Elapsed: 00:00:00.00 ``` Once it refreshes, its MUCH faster than doing the raw query ``` SQL> select count(*),avg(a),avg(b),avg(c),avg(d) from so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D) ---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836 Elapsed: 00:00:05.74 SQL> select * from mv_so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D) ---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836 Elapsed: 00:00:00.00 SQL> ``` If we insert into the base table, the result is not immediately viewable view the MV. ``` SQL> insert into so_x values (1,2,3,4,5); 1 row created. Elapsed: 00:00:00.00 SQL> commit; Commit complete. Elapsed: 00:00:00.00 SQL> select * from mv_so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D) ---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836 Elapsed: 00:00:00.00 SQL> ``` But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want. ``` SQL> / COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D) ---------- ---------- ---------- ---------- ---------- 1899460 7495.35823 22.2905352 5.00276078 2.17647059 Elapsed: 00:00:00.00 SQL> ``` This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate.
51,572
<p>How does one <strong>reliably</strong> determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command?</p> <p>This is regarding MIME or content type, not file system classifications, such as directory, file, or socket.</p>
[ { "answer_id": 51616, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": -1, "selected": false, "text": "<p>You could give a go with <a href=\"http://mime-types.rubyforge.org/\" rel=\"nofollow noreferrer\">MIME::Types for Ruby</a>.</p>\n\n<blockquote>\n <p>This library allows for the identification of a file’s likely MIME content type. The identification of MIME content type is based on a file’s filename extensions.</p>\n</blockquote>\n" }, { "answer_id": 56933, "author": "Patrick Ritchie", "author_id": 4748, "author_profile": "https://Stackoverflow.com/users/4748", "pm_score": 5, "selected": false, "text": "<p>If you're on a Unix machine try this:</p>\n\n<pre><code>mimetype = `file -Ib #{path}`.gsub(/\\n/,\"\")\n</code></pre>\n\n<p>I'm not aware of any pure Ruby solutions that work as reliably as 'file'.</p>\n\n<p>Edited to add: depending what OS you are running you may need to use 'i' instead of 'I' to get file to return a mime-type.</p>\n" }, { "answer_id": 94102, "author": "Chris Ingrassia", "author_id": 6991, "author_profile": "https://Stackoverflow.com/users/6991", "pm_score": 2, "selected": false, "text": "<p>You could give <a href=\"http://shared-mime.rubyforge.org/\" rel=\"nofollow noreferrer\">shared-mime</a> a try (gem install shared-mime-info). Requires the use ofthe Freedesktop shared-mime-info library, but does both filename/extension checks as well as \"magic\" checks... tried giving it a whirl myself just now but I don't have the freedesktop shared-mime-info database installed and have to do \"real work,\" unfortunately, but it might be what you're looking for.</p>\n" }, { "answer_id": 901660, "author": "Martin Carpenter", "author_id": 39443, "author_profile": "https://Stackoverflow.com/users/39443", "pm_score": 6, "selected": false, "text": "<p>There is a ruby binding to <code>libmagic</code> that does what you need. It is available as a gem named <a href=\"https://rubygems.org/gems/ruby-filemagic/versions/0.7.1\" rel=\"noreferrer\">ruby-filemagic</a>:</p>\n\n<pre><code>gem install ruby-filemagic\n</code></pre>\n\n<p>Require <code>libmagic-dev</code>.</p>\n\n<p>The documentation seems a little thin, but this should get you started:</p>\n\n<pre><code>$ irb \nirb(main):001:0&gt; require 'filemagic' \n=&gt; true\nirb(main):002:0&gt; fm = FileMagic.new\n=&gt; #&lt;FileMagic:0x7fd4afb0&gt;\nirb(main):003:0&gt; fm.file('foo.zip') \n=&gt; \"Zip archive data, at least v2.0 to extract\"\nirb(main):004:0&gt; \n</code></pre>\n" }, { "answer_id": 1373705, "author": "Qianjigui", "author_id": 158165, "author_profile": "https://Stackoverflow.com/users/158165", "pm_score": -1, "selected": false, "text": "<p>The ruby gem is well.\n<a href=\"http://rubyforge.org/projects/mime-types/\" rel=\"nofollow noreferrer\">mime-types for ruby</a></p>\n" }, { "answer_id": 3754019, "author": "heathanderson", "author_id": 393068, "author_profile": "https://Stackoverflow.com/users/393068", "pm_score": 1, "selected": false, "text": "<p>I recently found <a href=\"http://github.com/mattetti/mimetype-fu\" rel=\"nofollow noreferrer\">mimetype-fu</a>. </p>\n\n<p>It seems to be the easiest reliable solution to get a file's MIME type.</p>\n\n<p>The only caveat is that on a Windows machine it only uses the file extension, whereas on *Nix based systems it works great.</p>\n" }, { "answer_id": 4117137, "author": "jamiew", "author_id": 144807, "author_profile": "https://Stackoverflow.com/users/144807", "pm_score": 4, "selected": false, "text": "<p>I found shelling out to be the most reliable. For compatibility on both Mac OS X and Ubuntu Linux I used:</p>\n\n<p><code>file --mime -b myvideo.mp4</code>\n<br/><strong>video/mp4; charset=binary</strong></p>\n\n<p>Ubuntu also prints video codec information if it can which is pretty cool:</p>\n\n<p><code>file -b myvideo.mp4</code>\n<br /><strong>ISO Media, MPEG v4 system, version 2</strong></p>\n" }, { "answer_id": 9005833, "author": "knoopx", "author_id": 62368, "author_profile": "https://Stackoverflow.com/users/62368", "pm_score": 0, "selected": false, "text": "<p>The best I found so far: </p>\n\n<p><a href=\"http://bogomips.org/mahoro.git/\" rel=\"nofollow\">http://bogomips.org/mahoro.git/</a></p>\n" }, { "answer_id": 10253211, "author": "joelparkerhenderson", "author_id": 528726, "author_profile": "https://Stackoverflow.com/users/528726", "pm_score": 1, "selected": false, "text": "<p>Pure Ruby solution using magic bytes and returning a symbol for the matching type:</p>\n\n<p><a href=\"https://github.com/SixArm/sixarm_ruby_magic_number_type\" rel=\"nofollow\">https://github.com/SixArm/sixarm_ruby_magic_number_type</a></p>\n\n<p>I wrote it, so if you have suggestions, let me know.</p>\n" }, { "answer_id": 16636012, "author": "Alain Beauvois", "author_id": 183331, "author_profile": "https://Stackoverflow.com/users/183331", "pm_score": 3, "selected": false, "text": "<p>You can use this reliable method base on the magic header of the file :</p>\n\n<pre><code>def get_image_extension(local_file_path)\n png = Regexp.new(\"\\x89PNG\".force_encoding(\"binary\"))\n jpg = Regexp.new(\"\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\".force_encoding(\"binary\"))\n jpg2 = Regexp.new(\"\\xff\\xd8\\xff\\xe1(.*){2}Exif\".force_encoding(\"binary\"))\n case IO.read(local_file_path, 10)\n when /^GIF8/\n 'gif'\n when /^#{png}/\n 'png'\n when /^#{jpg}/\n 'jpg'\n when /^#{jpg2}/\n 'jpg'\n else\n mime_type = `file #{local_file_path} --mime-type`.gsub(\"\\n\", '') # Works on linux and mac\n raise UnprocessableEntity, \"unknown file type\" if !mime_type\n mime_type.split(':')[1].split('/')[1].gsub('x-', '').gsub(/jpeg/, 'jpg').gsub(/text/, 'txt').gsub(/x-/, '')\n end \nend\n</code></pre>\n" }, { "answer_id": 25892795, "author": "spyle", "author_id": 326979, "author_profile": "https://Stackoverflow.com/users/326979", "pm_score": 3, "selected": false, "text": "<p>If you're using the File class, you can augment it with the following functions based on @PatrickRichie's answer:</p>\n\n<pre><code>class File\n def mime_type\n `file --brief --mime-type #{self.path}`.strip\n end\n\n def charset\n `file --brief --mime #{self.path}`.split(';').second.split('=').second.strip\n end\nend\n</code></pre>\n\n<p>And, if you're using Ruby on Rails, you can drop this into config/initializers/file.rb and have available throughout your project.</p>\n" }, { "answer_id": 50278033, "author": "Paulo Fidalgo", "author_id": 1006863, "author_profile": "https://Stackoverflow.com/users/1006863", "pm_score": 2, "selected": false, "text": "<p>For those who came here by the search engine, a modern approach to find the MimeType in pure ruby is to use the <a href=\"https://github.com/minad/mimemagic\" rel=\"nofollow noreferrer\">mimemagic</a> gem.</p>\n\n<pre><code>require 'mimemagic'\n\nMimeMagic.by_magic(File.open('tux.jpg')).type # =&gt; \"image/jpeg\" \n</code></pre>\n\n<p>If you feel that is safe to use only the file extension, then you can use the <a href=\"https://github.com/mime-types/ruby-mime-types\" rel=\"nofollow noreferrer\">mime-types</a> gem:</p>\n\n<pre><code>MIME::Types.type_for('tux.jpg') =&gt; [#&lt;MIME::Type: image/jpeg&gt;]\n</code></pre>\n" }, { "answer_id": 57431940, "author": "Jason Swett", "author_id": 199712, "author_profile": "https://Stackoverflow.com/users/199712", "pm_score": 3, "selected": false, "text": "<p>This was added as a comment on <a href=\"https://stackoverflow.com/a/56933/199712\">this answer</a> but should really be its own answer:</p>\n\n<pre><code>path = # path to your file\n\nIO.popen(\n [\"file\", \"--brief\", \"--mime-type\", path],\n in: :close, err: :close\n) { |io| io.read.chomp }\n</code></pre>\n\n<p>I can confirm that it worked for me.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How does one **reliably** determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command? This is regarding MIME or content type, not file system classifications, such as directory, file, or socket.
There is a ruby binding to `libmagic` that does what you need. It is available as a gem named [ruby-filemagic](https://rubygems.org/gems/ruby-filemagic/versions/0.7.1): ``` gem install ruby-filemagic ``` Require `libmagic-dev`. The documentation seems a little thin, but this should get you started: ``` $ irb irb(main):001:0> require 'filemagic' => true irb(main):002:0> fm = FileMagic.new => #<FileMagic:0x7fd4afb0> irb(main):003:0> fm.file('foo.zip') => "Zip archive data, at least v2.0 to extract" irb(main):004:0> ```
51,582
<p>Let's say I have the following class:</p> <pre><code>public class Test&lt;E&gt; { public boolean sameClassAs(Object o) { // TODO help! } } </code></pre> <p>How would I check that <code>o</code> is the same class as <code>E</code>?</p> <pre><code>Test&lt;String&gt; test = new Test&lt;String&gt;(); test.sameClassAs("a string"); // returns true; test.sameClassAs(4); // returns false; </code></pre> <p>I can't change the method signature from <code>(Object o)</code> as I'm overridding a superclass and so don't get to choose my method signature.</p> <p>I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.</p>
[ { "answer_id": 51603, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 2, "selected": false, "text": "<p>I could only make it working like this:</p>\n\n<pre><code>public class Test&lt;E&gt; { \n\n private E e; \n\n public void setE(E e) { \n this.e = e; \n }\n\n public boolean sameClassAs(Object o) { \n\n return (o.getClass().equals(e.getClass())); \n }\n\n public boolean sameClassAs2(Object o) { \n return e.getClass().isInstance(o); \n }\n}\n</code></pre>\n" }, { "answer_id": 51615, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 3, "selected": false, "text": "<p>The method I've always used is below. It is a pain and a bit ugly, but I haven't found a better one. You have to pass the class type through on construction, as when Generics are compiled class information is lost.</p>\n\n<pre><code>public class Test&lt;E&gt; {\n private Class&lt;E&gt; clazz;\n public Test(Class&lt;E&gt; clazz) {\n this.clazz = clazz;\n }\n public boolean sameClassAs(Object o) {\n return this.clazz.isInstance(o);\n }\n}\n</code></pre>\n" }, { "answer_id": 51623, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "<p>An instance of <code>Test</code> has no information as to what <code>E</code> is at runtime. So, you need to pass a <code>Class&lt;E&gt;</code> to the constructor of Test.</p>\n\n<pre><code>public class Test&lt;E&gt; {\n private final Class&lt;E&gt; clazz;\n public Test(Class&lt;E&gt; clazz) {\n if (clazz == null) {\n throw new NullPointerException();\n }\n this.clazz = clazz;\n }\n // To make things easier on clients:\n public static &lt;T&gt; Test&lt;T&gt; create(Class&lt;T&gt; clazz) {\n return new Test&lt;T&gt;(clazz);\n }\n public boolean sameClassAs(Object o) {\n return o != null &amp;&amp; o.getClass() == clazz;\n }\n}\n</code></pre>\n\n<p>If you want an \"instanceof\" relationship, use <code>Class.isAssignableFrom</code> instead of the <code>Class</code> comparison. Note, <code>E</code> will need to be a non-generic type, for the same reason <code>Test</code> needs the <code>Class</code> object.</p>\n\n<p>For examples in the Java API, see <code>java.util.Collections.checkedSet</code> and similar.</p>\n" }, { "answer_id": 765241, "author": "Ayman", "author_id": 77222, "author_profile": "https://Stackoverflow.com/users/77222", "pm_score": -1, "selected": false, "text": "<p>I was just trying to do the same thing, and one neat trick i just realized is that you can can try a cast, and if the cast fails, ClassCastException will be thrown. You can can catch that, and do whatever. </p>\n\n<p>so your sameClassAs method should look like:</p>\n\n<pre><code>public boolean sameClassAs(Object o) {\n boolean same = false;\n try {\n E t = (E)o;\n same = true;\n } catch (ClassCastException e) {\n // same is false, nothing else to do\n } finally {\n return same;\n }\n}\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
Let's say I have the following class: ``` public class Test<E> { public boolean sameClassAs(Object o) { // TODO help! } } ``` How would I check that `o` is the same class as `E`? ``` Test<String> test = new Test<String>(); test.sameClassAs("a string"); // returns true; test.sameClassAs(4); // returns false; ``` I can't change the method signature from `(Object o)` as I'm overridding a superclass and so don't get to choose my method signature. I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.
An instance of `Test` has no information as to what `E` is at runtime. So, you need to pass a `Class<E>` to the constructor of Test. ``` public class Test<E> { private final Class<E> clazz; public Test(Class<E> clazz) { if (clazz == null) { throw new NullPointerException(); } this.clazz = clazz; } // To make things easier on clients: public static <T> Test<T> create(Class<T> clazz) { return new Test<T>(clazz); } public boolean sameClassAs(Object o) { return o != null && o.getClass() == clazz; } } ``` If you want an "instanceof" relationship, use `Class.isAssignableFrom` instead of the `Class` comparison. Note, `E` will need to be a non-generic type, for the same reason `Test` needs the `Class` object. For examples in the Java API, see `java.util.Collections.checkedSet` and similar.
51,586
<p>Is there a way to collect (e.g. in a List) multiple 'generic' objects that don't share a common super class? If so, how can I access their common properties?</p> <p>For example:</p> <pre><code>class MyObject&lt;T&gt; { public T Value { get; set; } public string Name { get; set; } public MyObject(string name, T value) { Name = name; Value = value; } } var fst = new MyObject&lt;int&gt;("fst", 42); var snd = new MyObject&lt;bool&gt;("snd", true); List&lt;MyObject&lt;?&gt;&gt; list = new List&lt;MyObject&lt;?&gt;&gt;(){fst, snd}; foreach (MyObject&lt;?&gt; o in list) Console.WriteLine(o.Name); </code></pre> <p>Obviously, this is pseudo code, this doesn't work.</p> <p>Also I don't need to access the .Value property (since that wouldn't be type-safe).</p> <p><strong>EDIT:</strong> Now that I've been thinking about this, It would be possible to use sub-classes for this. However, I think that would mean I'd have to write a new subclass for every new type.</p> <hr> <p>@<a href="https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51621">Grzenio</a> Yes, that exactly answered my question. Of course, now I need to duplicate the entire shared interface, but that's not a big problem. I should have thought of that...</p> <p>@<a href="https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51611">aku</a> You are right about the duck typing. I wouldn't expect two completely random types of objects to be accessible.</p> <p>But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. Apparently, this is not the case automatically.</p>
[ { "answer_id": 51611, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>C# doesn't support duck typing. You have 2 choices: interfaces and inheritance, otherwise you can't access similar properties of different types of objects.</p>\n" }, { "answer_id": 51621, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 4, "selected": true, "text": "<p>I don't think it is possible in C#, because MyObject is not a baseclass of MyObject. What I usually do is to define an interface (a 'normal' one, not generic) and make MyObject implement that interface, e.g.</p>\n\n<pre><code>interface INamedObject\n{\n string Name {get;}\n}\n</code></pre>\n\n<p>and then you can use the interface:</p>\n\n<pre><code>List&lt;INamedObject&gt; list = new List&lt;INamedObject&gt;(){fst, snd};\n\nforeach (INamedObject o in list)\n Console.WriteLine(o.Name);\n</code></pre>\n\n<p>Did it answer your question?</p>\n" }, { "answer_id": 51634, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 0, "selected": false, "text": "<p>The best way would be to add a common base class, otherwise you can fall back to reflection.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2597/" ]
Is there a way to collect (e.g. in a List) multiple 'generic' objects that don't share a common super class? If so, how can I access their common properties? For example: ``` class MyObject<T> { public T Value { get; set; } public string Name { get; set; } public MyObject(string name, T value) { Name = name; Value = value; } } var fst = new MyObject<int>("fst", 42); var snd = new MyObject<bool>("snd", true); List<MyObject<?>> list = new List<MyObject<?>>(){fst, snd}; foreach (MyObject<?> o in list) Console.WriteLine(o.Name); ``` Obviously, this is pseudo code, this doesn't work. Also I don't need to access the .Value property (since that wouldn't be type-safe). **EDIT:** Now that I've been thinking about this, It would be possible to use sub-classes for this. However, I think that would mean I'd have to write a new subclass for every new type. --- @[Grzenio](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51621) Yes, that exactly answered my question. Of course, now I need to duplicate the entire shared interface, but that's not a big problem. I should have thought of that... @[aku](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51611) You are right about the duck typing. I wouldn't expect two completely random types of objects to be accessible. But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. Apparently, this is not the case automatically.
I don't think it is possible in C#, because MyObject is not a baseclass of MyObject. What I usually do is to define an interface (a 'normal' one, not generic) and make MyObject implement that interface, e.g. ``` interface INamedObject { string Name {get;} } ``` and then you can use the interface: ``` List<INamedObject> list = new List<INamedObject>(){fst, snd}; foreach (INamedObject o in list) Console.WriteLine(o.Name); ``` Did it answer your question?
51,593
<p>What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC?</p>
[ { "answer_id": 52995, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 1, "selected": false, "text": "<p>According to the <a href=\"http://www.xmlrpc.com/spec\" rel=\"nofollow noreferrer\">XML-RPC Spec</a> it returns the \"fault\" in the xml.</p>\n\n<p>Is this the \"Exception\" you are referring to or are you refering to a Java Exception generated while making the XML-RPC call?</p>\n\n<p><strong>Fault example</strong></p>\n\n<pre><code>HTTP/1.1 200 OK\nConnection: close\nContent-Length: 426\nContent-Type: text/xml\nDate: Fri, 17 Jul 1998 19:55:02 GMT\nServer: UserLand Frontier/5.1.2-WinNT\n\n&lt;?xml version=\"1.0\"?&gt;\n&lt;methodResponse&gt;\n &lt;fault&gt;\n &lt;value&gt;\n &lt;struct&gt;\n &lt;member&gt;\n &lt;name&gt;faultCode&lt;/name&gt;\n &lt;value&gt;&lt;int&gt;4&lt;/int&gt;&lt;/value&gt;\n &lt;/member&gt;\n &lt;member&gt;\n &lt;name&gt;faultString&lt;/name&gt;\n &lt;value&gt;\n &lt;string&gt;Too many parameters.&lt;/string&gt;\n &lt;/value&gt;\n &lt;/member&gt;\n &lt;/struct&gt;\n &lt;/value&gt;\n &lt;/fault&gt;\n&lt;/methodResponse&gt; \n</code></pre>\n" }, { "answer_id": 56631, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 3, "selected": true, "text": "<p>It turns out that getting the cause exception from the Apache exception is the right one. </p>\n\n<pre><code>} catch (XmlRpcException rpce) {\n Throwable cause = rpce.getCause();\n if(cause != null) {\n if(cause instanceof ExceptionYouCanHandleException) {\n handler(cause);\n }\n else { throw(cause); }\n }\n else { throw(rpce); }\n}\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/279/" ]
What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC?
It turns out that getting the cause exception from the Apache exception is the right one. ``` } catch (XmlRpcException rpce) { Throwable cause = rpce.getCause(); if(cause != null) { if(cause instanceof ExceptionYouCanHandleException) { handler(cause); } else { throw(cause); } } else { throw(rpce); } } ```
51,645
<p>How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).</p> <p>I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.</p>
[ { "answer_id": 51656, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 1, "selected": false, "text": "<p>this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:</p>\n\n<pre><code>Me.lstDrives.Items.Clear()\nFor Each item As DriveInfo In My.Computer.FileSystem.Drives\n If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then\n Me.lstDrives.Items.Add(item.Name)\n End If\nNext\n</code></pre>\n\n<p>it won't be that hard to modify this code into a c# equivalent, and more <em>driveType</em>'s are available.<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.drivetype.aspx\" rel=\"nofollow noreferrer\">From MSDN:</a></p>\n\n<ul>\n<li><strong>Unknown:</strong> The type of drive is unknown. </li>\n<li><strong>NoRootDirectory:</strong> The drive does not have a root directory.</li>\n<li><strong>Removable:</strong> The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.</li>\n<li><strong>Fixed:</strong> The drive is a fixed disk.</li>\n<li><strong>Network:</strong> The drive is a network drive.</li>\n<li><strong>CDRom:</strong> The drive is an optical disc device, such as a CD or DVD-ROM. </li>\n<li><strong>Ram:</strong> The drive is a RAM disk.</li>\n</ul>\n" }, { "answer_id": 51672, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "<pre><code>using System.IO;\n\nDriveInfo[] allDrives = DriveInfo.GetDrives();\nforeach (DriveInfo d in allDrives)\n{\n if (d.IsReady &amp;&amp; d.DriveType == DriveType.Removable)\n {\n // This is the drive you want...\n }\n}\n</code></pre>\n\n<p>The DriveInfo class documentation is here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx</a></p>\n" }, { "answer_id": 51678, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 1, "selected": false, "text": "<p>in c# you can get the same by using the System.IO.DriveInfo class</p>\n\n<pre><code>using System.IO;\n\npublic static class GetDrives\n{\n public static IEnumerable&lt;DriveInfo&gt; GetCDDVDAndRemovableDevices()\n {\n return DriveInfo.GetDrives().\n Where(d =&gt; d.DriveType == DriveType.Removable\n &amp;&amp; d.DriveType == DriveType.CDRom);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 12752540, "author": "Searush", "author_id": 1587402, "author_profile": "https://Stackoverflow.com/users/1587402", "pm_score": 0, "selected": false, "text": "<p>This is a complete module for VB.NET : <br>\nImports System.IO <br>\nModule GetDriveNamesByType <br>\n Function GetDriveNames(Optional ByVal DType As DriveType = DriveType.Removable) As ListBox <br>\n For Each DN As System.IO.DriveInfo In My.Computer.FileSystem.Drives <br>\n If DN.DriveType = DType Then <br>\n GetDriveNames.Items.Add(DN.Name) <br>\n End If <br>\n Next <br>\n End Function <br>\nEnd Module <br></p>\n\n<pre><code>'Drive Types &lt;br&gt;\n'Unknown: The type of drive is unknown. &lt;br&gt;\n'NoRootDirectory: The drive does not have a root directory. &lt;br&gt;\n'Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. &lt;br&gt;\n'Fixed: The drive is a fixed disk. &lt;br&gt;\n'Network: The drive is a network drive. &lt;br&gt;\n'CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. &lt;br&gt;\n'Ram: The drive is a RAM disk. &lt;br&gt;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019/" ]
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0). I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.
``` using System.IO; DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { if (d.IsReady && d.DriveType == DriveType.Removable) { // This is the drive you want... } } ``` The DriveInfo class documentation is here: <http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx>
51,654
<p>I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table.</p> <p>Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class.</p> <p>The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and <strong>use the table name as a parameter</strong> which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data).</p> <p>Has anybody dealt with this kind of situation, and can it be done at all?</p>
[ { "answer_id": 51683, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p>one way you could do it is to declare an interface say IGisObject that has the common properties declared on the interface. Then implement a concrete class which maps to each table. That way they'll still be all of type IGisObject.</p>\n" }, { "answer_id": 51692, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 0, "selected": false, "text": "<p>You can have a look at what Ayende is saying here : <a href=\"http://www.ayende.com/Blog/archive/2007/04/24/Multi-Table-Entities-in-NHibernate.aspx\" rel=\"nofollow noreferrer\">MultiTable Entities</a>.</p>\n\n<p>But since you have separate tables , i don't think it will work. \nYou can also check out <a href=\"http://groups.google.com/group/nhusers\" rel=\"nofollow noreferrer\">nhuser group</a></p>\n" }, { "answer_id": 51829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It sounds like the simplest thing to do here may be to create an abstract base class with all of the common GIS members and then to inherit the other X classes that will have nothing more than the necessary NHibernate mappings. I would then use the Factory pattern to create the object of the specific type using your metadata.</p>\n" }, { "answer_id": 51934, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 2, "selected": true, "text": "<p>@Brian Chiasson</p>\n\n<p>Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my user will have in the application. Therefore, the in-front per-class mapping model doesn't work because tomorrow there will be another new database table, and a need to create new class with new mapping.</p>\n\n<p>@all\nThere might be a possibility to write my own custom query in the XML config file of my GisObject class, then in the data access class fetching that query using the </p>\n\n<pre><code>string qs = getSession().getNamedQuery(queryName);\n</code></pre>\n\n<p>and use the string replace to inject database name (by replacing some placeholder string) which i will pass as a parameter. </p>\n\n<pre><code>qs = qs.replace(\":tablename:\", tableName);\n</code></pre>\n\n<p>How do you feel about that solution? I know it might be a security risk in an uncontrolled environment where the table name would be fetched as the user input, but in this case, i have a meta table containing right and valid table names for the GIS data classes which i will read before calling the query for fetching data for the specific class of GIS objects.</p>\n" }, { "answer_id": 53476, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 0, "selected": false, "text": "<p>I guess I'd ask the question to why you are going after the GIS data directly in the database and not using what API that is typically provided as an abstraction for you. If this is an ESRI system there are tools that allow you to create static database views into their GIS objects and then maybe from that point it might be appropriate for data extract.</p>\n" }, { "answer_id": 98574, "author": "Eric Lathrop", "author_id": 18392, "author_profile": "https://Stackoverflow.com/users/18392", "pm_score": 0, "selected": false, "text": "<p>From the NHibernate documentation, you could use one of the <a href=\"http://www.hibernate.org/hib_docs/nhibernate/html/inheritance.html\" rel=\"nofollow noreferrer\">inheritance mappings</a>.</p>\n\n<p>You might also have a separate class for each table, but have them all implement some common interface</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4723/" ]
I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table. Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class. The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and **use the table name as a parameter** which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data). Has anybody dealt with this kind of situation, and can it be done at all?
@Brian Chiasson Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my user will have in the application. Therefore, the in-front per-class mapping model doesn't work because tomorrow there will be another new database table, and a need to create new class with new mapping. @all There might be a possibility to write my own custom query in the XML config file of my GisObject class, then in the data access class fetching that query using the ``` string qs = getSession().getNamedQuery(queryName); ``` and use the string replace to inject database name (by replacing some placeholder string) which i will pass as a parameter. ``` qs = qs.replace(":tablename:", tableName); ``` How do you feel about that solution? I know it might be a security risk in an uncontrolled environment where the table name would be fetched as the user input, but in this case, i have a meta table containing right and valid table names for the GIS data classes which i will read before calling the query for fetching data for the specific class of GIS objects.
51,658
<p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
[ { "answer_id": 51663, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/2.7/library/os.html\" rel=\"nofollow noreferrer\">os.statvfs()</a> function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says \"Availability: Unix\" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).</p>\n\n<p>Otherwise, you can use the <a href=\"http://sourceforge.net/projects/pywin32/\" rel=\"nofollow noreferrer\">pywin32</a> library to directly call the <a href=\"http://msdn.microsoft.com/en-us/library/aa364937(VS.85).aspx\" rel=\"nofollow noreferrer\">GetDiskFreeSpaceEx</a> function.</p>\n" }, { "answer_id": 51675, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 0, "selected": false, "text": "<p>I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.</p>\n\n<p>For Windows, there's the <a href=\"http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetDiskFreeSpaceEx_meth.html\" rel=\"nofollow noreferrer\">GetDiskFreeSpaceEx</a> method in the win32 extensions.</p>\n" }, { "answer_id": 53170, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://man.he.net/?section=all&amp;topic=df\" rel=\"noreferrer\">df</a> as a cross-platform way. It is a part of <a href=\"http://www.gnu.org/software/coreutils/\" rel=\"noreferrer\">GNU core utilities</a>. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, <a href=\"http://getgnuwin32.sourceforge.net/\" rel=\"noreferrer\">GetGnuWin32</a> comes in handy).</p>\n\n<p><em>df</em> is a command-line utility, therefore a wrapper required for scripting purposes.\nFor example: </p>\n\n<pre><code>from subprocess import PIPE, Popen\n\ndef free_volume(filename):\n \"\"\"Find amount of disk space available to the current user (in bytes) \n on the file system containing filename.\"\"\"\n stats = Popen([\"df\", \"-Pk\", filename], stdout=PIPE).communicate()[0]\n return int(stats.splitlines()[1].split()[3]) * 1024\n</code></pre>\n" }, { "answer_id": 1728106, "author": "Stefan Lundström", "author_id": 78757, "author_profile": "https://Stackoverflow.com/users/78757", "pm_score": 3, "selected": false, "text": "<p>If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly. </p>\n\n<pre><code>import ctypes\n\nfree_bytes = ctypes.c_ulonglong(0)\n\nctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\\\'), None, None, ctypes.pointer(free_bytes))\n\nif free_bytes.value == 0:\n print 'dont panic'\n</code></pre>\n" }, { "answer_id": 2372171, "author": "Frankovskyi Bogdan", "author_id": 273689, "author_profile": "https://Stackoverflow.com/users/273689", "pm_score": 6, "selected": false, "text": "<pre><code>import ctypes\nimport os\nimport platform\nimport sys\n\ndef get_free_space_mb(dirname):\n \"\"\"Return folder/drive free space (in megabytes).\"\"\"\n if platform.system() == 'Windows':\n free_bytes = ctypes.c_ulonglong(0)\n ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))\n return free_bytes.value / 1024 / 1024\n else:\n st = os.statvfs(dirname)\n return st.f_bavail * st.f_frsize / 1024 / 1024\n</code></pre>\n\n<p>Note that you <em>must</em> pass a directory name for <code>GetDiskFreeSpaceEx()</code> to work\n(<code>statvfs()</code> works on both files and directories). You can get a directory name\nfrom a file with <code>os.path.dirname()</code>.</p>\n\n<p>Also see the documentation for <a href=\"https://docs.python.org/3/library/os.html#os.fstatvfs\" rel=\"noreferrer\"><code>os.statvfs()</code></a> and <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx\" rel=\"noreferrer\"><code>GetDiskFreeSpaceEx</code></a>.</p>\n" }, { "answer_id": 6773639, "author": "Yuriy", "author_id": 855556, "author_profile": "https://Stackoverflow.com/users/855556", "pm_score": 3, "selected": false, "text": "<p>A good cross-platform way is using psutil: <a href=\"http://pythonhosted.org/psutil/#disks\" rel=\"nofollow\">http://pythonhosted.org/psutil/#disks</a>\n(Note that you'll need psutil 0.3.0 or above).</p>\n" }, { "answer_id": 19332602, "author": "Erxin", "author_id": 1602830, "author_profile": "https://Stackoverflow.com/users/1602830", "pm_score": 5, "selected": false, "text": "<p>You could use the <a href=\"https://pypi.python.org/pypi/WMI/\">wmi</a> module for windows and os.statvfs for unix</p>\n\n<p>for window</p>\n\n<pre><code>import wmi\n\nc = wmi.WMI ()\nfor d in c.Win32_LogicalDisk():\n print( d.Caption, d.FreeSpace, d.Size, d.DriveType)\n</code></pre>\n\n<p>for unix or linux</p>\n\n<pre><code>from os import statvfs\n\nstatvfs(path)\n</code></pre>\n" }, { "answer_id": 29944093, "author": "jhasse", "author_id": 647898, "author_profile": "https://Stackoverflow.com/users/647898", "pm_score": 5, "selected": false, "text": "<p>Install <a href=\"https://pypi.org/project/psutil/\" rel=\"noreferrer\">psutil</a> using <code>pip install psutil</code>. Then you can get the amount of free space in bytes using:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import psutil\nprint(psutil.disk_usage(\".\").free)\n</code></pre>\n" }, { "answer_id": 35860878, "author": "Sanjay Bhosale", "author_id": 1074838, "author_profile": "https://Stackoverflow.com/users/1074838", "pm_score": 1, "selected": false, "text": "<p>Below code returns correct value on windows</p>\n\n<pre><code>import win32file \n\ndef get_free_space(dirname):\n secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)\n return secsPerClus * bytesPerSec * nFreeClus\n</code></pre>\n" }, { "answer_id": 38889608, "author": "Mišo", "author_id": 2988107, "author_profile": "https://Stackoverflow.com/users/2988107", "pm_score": 3, "selected": false, "text": "<p>From Python 3.3 you can use <a href=\"https://docs.python.org/3/library/shutil.html#shutil.disk_usage\" rel=\"noreferrer\">shutil.disk_usage(\"/\").free</a> from standard library for both Windows and UNIX :)</p>\n" }, { "answer_id": 48555562, "author": "Rob Truxal", "author_id": 6293857, "author_profile": "https://Stackoverflow.com/users/6293857", "pm_score": 4, "selected": false, "text": "<h1>If you're running python3:</h1>\n\n<p>Using <code>shutil.disk_usage()</code>with <code>os.path.realpath('/')</code> name-regularization works:</p>\n\n<pre><code>from os import path\nfrom shutil import disk_usage\n\nprint([i / 1000000 for i in disk_usage(path.realpath('/'))])\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\\\Users\\\\phannypack'))\n\nprint(total_bytes / 1000000) # for Mb\nprint(used_bytes / 1000000)\nprint(free_bytes / 1000000)\n</code></pre>\n\n<p>giving you the total, used, &amp; free space in MB.</p>\n" }, { "answer_id": 73115043, "author": "grepit", "author_id": 717630, "author_profile": "https://Stackoverflow.com/users/717630", "pm_score": 0, "selected": false, "text": "<p>Most previous answers are correct, I'm using Python 3.10 and shutil.\nMy use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the <a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"nofollow noreferrer\">documentation</a>)</p>\n<p>Here is the example for Windows:</p>\n<pre><code>import shutil\n\ntotal, used, free = shutil.disk_usage(&quot;C:/&quot;)\n\nprint(&quot;Total: %d GiB&quot; % (total // (2**30)))\nprint(&quot;Used: %d GiB&quot; % (used // (2**30)))\nprint(&quot;Free: %d GiB&quot; % (free // (2**30)))\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?
``` import ctypes import os import platform import sys def get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value / 1024 / 1024 else: st = os.statvfs(dirname) return st.f_bavail * st.f_frsize / 1024 / 1024 ``` Note that you *must* pass a directory name for `GetDiskFreeSpaceEx()` to work (`statvfs()` works on both files and directories). You can get a directory name from a file with `os.path.dirname()`. Also see the documentation for [`os.statvfs()`](https://docs.python.org/3/library/os.html#os.fstatvfs) and [`GetDiskFreeSpaceEx`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx).
51,684
<p>I have a <a href="http://www.samurize.com/modules/news/" rel="noreferrer">Samurize</a> config that shows a CPU usage graph similar to Task manager. </p> <p>How do I also display the name of the process with the current highest CPU usage percentage? </p> <p>I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option.</p> <hr> <p>Further clarification: </p> <p>I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property. </p> <p>Can I calculate this in some way?</p>
[ { "answer_id": 51705, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 1, "selected": false, "text": "<p>You might be able to use <a href=\"http://commandwindows.com/server2003tools.htm\" rel=\"nofollow noreferrer\">Pmon.exe</a> for this. You can get it as part of the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd\" rel=\"nofollow noreferrer\">Windows Resource Kit tools</a> (the link is to the Server 2003 version, which can apparently be used in XP as well).</p>\n" }, { "answer_id": 51743, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 1, "selected": false, "text": "<pre><code>Process.TotalProcessorTime\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx</a></p>\n" }, { "answer_id": 51789, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": -1, "selected": true, "text": "<p>With PowerShell:</p>\n\n<pre><code>Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader\n</code></pre>\n\n<p>returns somewhat like:</p>\n\n<pre><code> 16.8641632 System\n 12.548072 csrss\n 11.9892168 powershell\n</code></pre>\n" }, { "answer_id": 51820, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 3, "selected": false, "text": "<p>What you want to get its the instant CPU usage (kind of)...</p>\n\n<p>Actually, the instant CPU usage for a process does not exists. Instead you have to make two measurements and calculate the average CPU usage, the formula is quite simple:</p>\n\n<blockquote>\n <p>AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1]</p>\n</blockquote>\n\n<p>The lower Time2 and Time1 difference is, the more \"instant\" your measurement will be. Windows Task Manager calculate the CPU use with an interval of one second. I've found that is more than enough and you might even consider doing it in 5 seconds intervals cause the act of measuring itself takes up CPU cycles...</p>\n\n<p>So, first, to get the average CPU time</p>\n\n<pre><code> using System.Diagnostics;\n\nfloat GetAverageCPULoad(int procID, DateTme from, DateTime, to)\n{\n // For the current process\n //Process proc = Process.GetCurrentProcess();\n // Or for any other process given its id\n Process proc = Process.GetProcessById(procID);\n System.TimeSpan lifeInterval = (to - from);\n // Get the CPU use\n float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100;\n // You need to take the number of present cores into account\n return CPULoad / System.Environment.ProcessorCount;\n}\n</code></pre>\n\n<p>now, for the \"instant\" CPU load you'll need an specialized class:</p>\n\n<pre><code> class ProcLoad\n{\n // Last time you checked for a process\n public Dictionary&lt;int, DateTime&gt; lastCheckedDict = new Dictionary&lt;int, DateTime&gt;();\n\n public float GetCPULoad(int procID)\n {\n if (lastCheckedDict.ContainsKey(procID))\n {\n DateTime last = lastCheckedDict[procID];\n lastCheckedDict[procID] = DateTime.Now;\n return GetAverageCPULoad(procID, last, lastCheckedDict[procID]);\n }\n else\n {\n lastCheckedDict.Add(procID, DateTime.Now);\n return 0;\n }\n }\n}\n</code></pre>\n\n<p>You should call that class from a timer (or whatever interval method you like) for <strong>each process you want to monitor</strong>, if you want all the processes just use the <a href=\"http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx\" rel=\"nofollow noreferrer\">Process.GetProcesses</a> static method</p>\n" }, { "answer_id": 15454096, "author": "MD. Mohiuddin Ahmed", "author_id": 1895925, "author_profile": "https://Stackoverflow.com/users/1895925", "pm_score": 0, "selected": false, "text": "<p>You can also do it this way :-</p>\n\n<pre><code>public Process getProcessWithMaxCPUUsage()\n {\n const int delay = 500;\n Process[] processes = Process.GetProcesses();\n\n var counters = new List&lt;PerformanceCounter&gt;();\n\n foreach (Process process in processes)\n {\n var counter = new PerformanceCounter(\"Process\", \"% Processor Time\", process.ProcessName);\n counter.NextValue();\n counters.Add(counter);\n }\n System.Threading.Thread.Sleep(delay);\n //You must wait(ms) to ensure that the current\n //application process does not have MAX CPU\n int mxproc = -1;\n double mxcpu = double.MinValue, tmpcpu;\n for (int ik = 0; ik &lt; counters.Count; ik++)\n {\n tmpcpu = Math.Round(counters[ik].NextValue(), 1);\n if (tmpcpu &gt; mxcpu)\n {\n mxcpu = tmpcpu;\n mxproc = ik;\n }\n\n }\n return processes[mxproc];\n }\n</code></pre>\n\n<p>Usage:-</p>\n\n<pre><code>static void Main()\n {\n Process mxp=getProcessWithMaxCPUUsage();\n Console.WriteLine(mxp.ProcessName);\n }\n</code></pre>\n" }, { "answer_id": 19474434, "author": "Ayan Mullick", "author_id": 2748772, "author_profile": "https://Stackoverflow.com/users/2748772", "pm_score": 1, "selected": false, "text": "<p>Somehow </p>\n\n<p><code>Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName,TotalProcessorTime -hidetableheader</code></p>\n\n<p>wasn't getting the CPU information from the remote machine. I had to come up with this.</p>\n\n<p><code>Get-Counter '\\Process(*)\\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 10| ft -AutoSize</code></p>\n" }, { "answer_id": 22675167, "author": "Ambrose Leung", "author_id": 2205372, "author_profile": "https://Stackoverflow.com/users/2205372", "pm_score": 1, "selected": false, "text": "<p>Thanks for the formula, Jorge. I don't quite understand why you have to divide by the number of cores, but the numbers I get match the Task Manager. Here's my powershell code:</p>\n\n<pre><code>$procID = 4321\n\n$time1 = Get-Date\n$cpuTime1 = Get-Process -Id $procID | Select -Property CPU\n\nStart-Sleep -s 2\n\n$time2 = Get-Date\n$cpuTime2 = Get-Process -Id $procID | Select -Property CPU\n\n$avgCPUUtil = ($cpuTime2.CPU - $cpuTime1.CPU)/($time2-$time1).TotalSeconds *100 / [System.Environment]::ProcessorCount\n</code></pre>\n" }, { "answer_id": 31356645, "author": "Vidar", "author_id": 346645, "author_profile": "https://Stackoverflow.com/users/346645", "pm_score": 2, "selected": false, "text": "<p>Building on Frederic's answer and utilizing the code at the bottom of the page <a href=\"http://blogs.msdn.com/b/powershell/archive/2012/07/13/join-object.aspx\" rel=\"nofollow\">here</a> (for an example of usage see <a href=\"http://blogs.msdn.com/b/powershell/archive/2012/10/04/joining-multiple-tables-grouping-and-evaluating-totals.aspx\" rel=\"nofollow\">this</a> post) to join the full set of processes gotten from <code>Get-Process</code>, we get the following:</p>\n\n<pre><code>$sampleInterval = 3\n\n$process1 = Get-Process |select Name,Id, @{Name=\"Sample1CPU\"; Expression = {$_.CPU}}\n\nStart-Sleep -Seconds $sampleInterval\n\n$process2 = Get-Process | select Id, @{Name=\"Sample2CPU\"; Expression = {$_.CPU}}\n\n$samples = Join-Object -Left $process1 -Right $process2 -LeftProperties Name,Sample1CPU -RightProperties Sample2CPU -Where {$args[0].Id -eq $args[1].Id}\n\n$samples | select Name,@{Name=\"CPU Usage\";Expression = {($_.Sample2CPU-$_.Sample1CPU)/$sampleInterval * 100}} | sort -Property \"CPU Usage\" -Descending | select -First 10 | ft -AutoSize\n</code></pre>\n\n<p>Which gives an example output of </p>\n\n<pre><code>Name CPU Usage\n---- ---------\nfirefox 20.8333333333333\npowershell_ise 5.72916666666667\nBattle.net 1.5625\nSkype 1.5625\nchrome 1.5625\nchrome 1.04166666666667\nchrome 1.04166666666667\nchrome 1.04166666666667\nchrome 1.04166666666667\nLCore 1.04166666666667\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023/" ]
I have a [Samurize](http://www.samurize.com/modules/news/) config that shows a CPU usage graph similar to Task manager. How do I also display the name of the process with the current highest CPU usage percentage? I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option. --- Further clarification: I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property. Can I calculate this in some way?
With PowerShell: ``` Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader ``` returns somewhat like: ``` 16.8641632 System 12.548072 csrss 11.9892168 powershell ```
51,686
<p>Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?</p> <p>The same question applies to VB6, C++ and other native Windows applications.</p>
[ { "answer_id": 51691, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 1, "selected": false, "text": "<p>I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:</p>\n\n<p><a href=\"http://blogs.msdn.com/g/archive/2008/06/06/sample-demonstrating-clickonce-deployment-of-com-component-implemented-in-managed-assembly-without-using-gac-or-registry-and-without-requiring-admin-rights.aspx\" rel=\"nofollow noreferrer\">How To: ClickOnce deployment for unmanaged app with COM component in managed assembly </a></p>\n" }, { "answer_id": 153754, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 2, "selected": false, "text": "<p>No, the entry point to your app needs to be managed code.</p>\n\n<p>This is from a <a href=\"http://www.softinsight.com/bnoyes/CommentView,guid,5df8d49a-2a4e-45a6-af95-a0300c5ea5cd.aspx#commentstart\" rel=\"nofollow noreferrer\">blog post</a> by Brian Noyes, one of the main authorites on ClickOnce and author of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321197690\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Smart Client Deployment with ClickOnce</a>.</p>\n\n<blockquote>\n <p>If you app is REALLY legacy (i.e. VB6, MFC, ATL, etc.), as in an unmanaged code executable, then no, you cannot deploy it as an executable through ClickOnce.</p>\n</blockquote>\n\n<p>The accepted workaround seems to be a managed code stub exe that launches the main exe.</p>\n" }, { "answer_id": 1149048, "author": "Sake", "author_id": 77996, "author_profile": "https://Stackoverflow.com/users/77996", "pm_score": 4, "selected": true, "text": "<p>Personally, I build my own mechanism to kick off self update process when my application timestamp is out of sync with the server. Not too difficult, but it's not a simple task.</p>\n\n<p>By the way, for Delphi you can use some thirdparty help:</p>\n\n<p><a href=\"http://www.tmssoftware.com/site/wupdate.asp\" rel=\"nofollow noreferrer\">http://www.tmssoftware.com/site/wupdate.asp</a></p>\n\n<p>UPDATED:</p>\n\n<p>For my implementation:</p>\n\n<p>MyApp.EXE will run in 3 different modes</p>\n\n<ol>\n<li><p>MyApp.EXE without any argument. This will start the application typically.</p>\n\n<p>1.1 The very first thing it does is to validate its own file-time with the server.</p>\n\n<p>1.2 If update is required then it will download the updated file to the file named \"MyApp-YYYY-MM-DD-HH-MM-SS.exe\"</p>\n\n<p>1.3 Then it invoke \"MyApp-YYYY-MM-DD-HH-MM-SS.exe\" with command argument </p>\n\n<pre><code>MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE\n</code></pre>\n\n<p>1.4 Terminate this application.</p>\n\n<p>1.5 If there is no update required then the application will start normally from 1.1</p></li>\n<li><p>MyApp.EXE --update \"FILENAME\".</p>\n\n<p>2.1 Try copying itself to \"FILENAME\" every 100ms until success.</p>\n\n<p>2.2 Invoke \"FILENAME\" when it success</p>\n\n<p>2.3 Invoke \"FILNAME --delete MyApp-YYYY-MM-DD-HH-MM-SS.exe\" to delete itself.</p>\n\n<p>2.4 Terminate</p></li>\n<li><p>MyApp.EXE --delete \"FILENAME\"</p>\n\n<p>3.1 Try deleting the file \"FILENAME\" every 500ms until success.</p>\n\n<p>3.2 Terminate</p></li>\n</ol>\n\n<p>I've already been using this scheme for my application for 7 years and it works well. It could be quite painful to debug when things goes wrong since the steps involve many processes. I suggest you make a lot of trace logging to allow simpler trouble-shooting.</p>\n\n<p>Good Luck</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5362/" ]
Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application? The same question applies to VB6, C++ and other native Windows applications.
Personally, I build my own mechanism to kick off self update process when my application timestamp is out of sync with the server. Not too difficult, but it's not a simple task. By the way, for Delphi you can use some thirdparty help: <http://www.tmssoftware.com/site/wupdate.asp> UPDATED: For my implementation: MyApp.EXE will run in 3 different modes 1. MyApp.EXE without any argument. This will start the application typically. 1.1 The very first thing it does is to validate its own file-time with the server. 1.2 If update is required then it will download the updated file to the file named "MyApp-YYYY-MM-DD-HH-MM-SS.exe" 1.3 Then it invoke "MyApp-YYYY-MM-DD-HH-MM-SS.exe" with command argument ``` MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE ``` 1.4 Terminate this application. 1.5 If there is no update required then the application will start normally from 1.1 2. MyApp.EXE --update "FILENAME". 2.1 Try copying itself to "FILENAME" every 100ms until success. 2.2 Invoke "FILENAME" when it success 2.3 Invoke "FILNAME --delete MyApp-YYYY-MM-DD-HH-MM-SS.exe" to delete itself. 2.4 Terminate 3. MyApp.EXE --delete "FILENAME" 3.1 Try deleting the file "FILENAME" every 500ms until success. 3.2 Terminate I've already been using this scheme for my application for 7 years and it works well. It could be quite painful to debug when things goes wrong since the steps involve many processes. I suggest you make a lot of trace logging to allow simpler trouble-shooting. Good Luck
51,687
<p>Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app.<br> I think the procedure would have to be something like:</p> <p>steps:</p> <ol> <li><p>Get dialog parent HWND or CWnd* </p></li> <li><p>Get the rect of the parent window and draw an overlay with a translucency over that window </p></li> <li>allow the dialog to do it's modal draw routine, e.g DoModal()</li> </ol> <p>Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC?<br> <strong>edit</strong> Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means<br> <strong>Some App</strong>:<br> <img src="https://farm4.static.flickr.com/3065/2843243996_8a4536f516_o.png" alt="alt text"> </p> <p>with a lightbox dialog box<br> <img src="https://farm4.static.flickr.com/3280/2842409249_4a1c7f5810_o.png" alt="alt text"></p>
[ { "answer_id": 51979, "author": "Brian Lyttle", "author_id": 636, "author_profile": "https://Stackoverflow.com/users/636", "pm_score": 2, "selected": false, "text": "<p>I think you just need to create a window and set the transparency. There is an MFC <a href=\"http://www.codeproject.com/KB/dialog/CGlassDialog.aspx\" rel=\"nofollow noreferrer\">CGlassDialog sample on CodeProject</a> that might help you. There is also an <a href=\"http://www.codeproject.com/KB/winsdk/quaker1.aspx\" rel=\"nofollow noreferrer\">article</a> on how to do this with the Win32 APIs.</p>\n" }, { "answer_id": 54341, "author": "geocoin", "author_id": 379, "author_profile": "https://Stackoverflow.com/users/379", "pm_score": 3, "selected": true, "text": "<p>Here's what I did* based on Brian's links<br>\nFirst create a dialog resource with the properties:</p>\n\n<ul>\n<li>border <strong>FALSE</strong></li>\n<li>3D look <strong>FALSE</strong></li>\n<li>client edge <strong>FALSE</strong></li>\n<li>Popup style</li>\n<li>static edge <strong>FALSE</strong></li>\n<li>Transparent <strong>TRUE</strong></li>\n<li>Title bar <strong>FALSE</strong> </li>\n</ul>\n\n<p>and you should end up with a dialog window with no frame or anything, just a grey box.\noverride the Create function to look like this: </p>\n\n<pre><code>BOOL LightBoxDlg::Create(UINT nIDTemplate, CWnd* pParentWnd)\n{\n\n if(!CDialog::Create(nIDTemplate, pParentWnd))\n return false;\n RECT rect;\n RECT size;\n\n GetParent()-&gt;GetWindowRect(&amp;rect);\n size.top = 0;\n size.left = 0;\n size.right = rect.right - rect.left;\n size.bottom = rect.bottom - rect.top;\n SetWindowPos(m_pParentWnd,rect.left,rect.top,size.right,size.bottom,NULL);\n\n HWND hWnd=m_hWnd; \n SetWindowLong (hWnd , GWL_EXSTYLE ,GetWindowLong (hWnd , GWL_EXSTYLE ) | WS_EX_LAYERED ) ;\n typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD);\n PSLWA pSetLayeredWindowAttributes;\n HMODULE hDLL = LoadLibrary (_T(\"user32\"));\n pSetLayeredWindowAttributes = \n (PSLWA) GetProcAddress(hDLL,\"SetLayeredWindowAttributes\");\n if (pSetLayeredWindowAttributes != NULL) \n {\n /*\n * Second parameter RGB(255,255,255) sets the colorkey \n * to white LWA_COLORKEY flag indicates that color key \n * is valid LWA_ALPHA indicates that ALphablend parameter \n * is valid - here 100 is used\n */\n pSetLayeredWindowAttributes (hWnd, \n RGB(255,255,255), 100, LWA_COLORKEY|LWA_ALPHA);\n }\n\n\n return true;\n}\n</code></pre>\n\n<p>then create a small black bitmap in an image editor (say 48x48) and import it as a bitmap resource (in this example IDB_BITMAP1)<br>\noverride the WM_ERASEBKGND message with:</p>\n\n<pre><code>BOOL LightBoxDlg::OnEraseBkgnd(CDC* pDC)\n{\n\n BOOL bRet = CDialog::OnEraseBkgnd(pDC);\n\n RECT rect;\n RECT size;\n m_pParentWnd-&gt;GetWindowRect(&amp;rect);\n size.top = 0;\n size.left = 0;\n size.right = rect.right - rect.left;\n size.bottom = rect.bottom - rect.top;\n\n CBitmap cbmp;\n cbmp.LoadBitmapW(IDB_BITMAP1);\n BITMAP bmp;\n cbmp.GetBitmap(&amp;bmp);\n CDC memDc;\n memDc.CreateCompatibleDC(pDC);\n memDc.SelectObject(&amp;cbmp);\n pDC-&gt;StretchBlt(0,0,size.right,size.bottom,&amp;memDc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);\n\n return bRet;\n}\n</code></pre>\n\n<p>Instantiate it in the DoModal of the desired dialog, Create it like a Modal Dialog i.e. on the stack(or heap if desired), call it's Create manually, show it then create your actual modal dialog over the top of it: </p>\n\n<pre><code>INT_PTR CAboutDlg::DoModal()\n{\n LightBoxDlg Dlg(m_pParentWnd);//make sure to pass in the parent of the new dialog\n Dlg.Create(LightBoxDlg::IDD);\n Dlg.ShowWindow(SW_SHOW);\n\n BOOL ret = CDialog::DoModal();\n\n Dlg.ShowWindow(SW_HIDE);\n return ret;\n}\n</code></pre>\n\n<p>and this results in something <strong>exactly</strong> like my mock up above </p>\n\n<p>*there are still places for improvment, like doing it without making a dialog box to begin with and some other general tidyups.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379/" ]
Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app. I think the procedure would have to be something like: steps: 1. Get dialog parent HWND or CWnd\* 2. Get the rect of the parent window and draw an overlay with a translucency over that window 3. allow the dialog to do it's modal draw routine, e.g DoModal() Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC? **edit** Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means **Some App**: ![alt text](https://farm4.static.flickr.com/3065/2843243996_8a4536f516_o.png) with a lightbox dialog box ![alt text](https://farm4.static.flickr.com/3280/2842409249_4a1c7f5810_o.png)
Here's what I did\* based on Brian's links First create a dialog resource with the properties: * border **FALSE** * 3D look **FALSE** * client edge **FALSE** * Popup style * static edge **FALSE** * Transparent **TRUE** * Title bar **FALSE** and you should end up with a dialog window with no frame or anything, just a grey box. override the Create function to look like this: ``` BOOL LightBoxDlg::Create(UINT nIDTemplate, CWnd* pParentWnd) { if(!CDialog::Create(nIDTemplate, pParentWnd)) return false; RECT rect; RECT size; GetParent()->GetWindowRect(&rect); size.top = 0; size.left = 0; size.right = rect.right - rect.left; size.bottom = rect.bottom - rect.top; SetWindowPos(m_pParentWnd,rect.left,rect.top,size.right,size.bottom,NULL); HWND hWnd=m_hWnd; SetWindowLong (hWnd , GWL_EXSTYLE ,GetWindowLong (hWnd , GWL_EXSTYLE ) | WS_EX_LAYERED ) ; typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD); PSLWA pSetLayeredWindowAttributes; HMODULE hDLL = LoadLibrary (_T("user32")); pSetLayeredWindowAttributes = (PSLWA) GetProcAddress(hDLL,"SetLayeredWindowAttributes"); if (pSetLayeredWindowAttributes != NULL) { /* * Second parameter RGB(255,255,255) sets the colorkey * to white LWA_COLORKEY flag indicates that color key * is valid LWA_ALPHA indicates that ALphablend parameter * is valid - here 100 is used */ pSetLayeredWindowAttributes (hWnd, RGB(255,255,255), 100, LWA_COLORKEY|LWA_ALPHA); } return true; } ``` then create a small black bitmap in an image editor (say 48x48) and import it as a bitmap resource (in this example IDB\_BITMAP1) override the WM\_ERASEBKGND message with: ``` BOOL LightBoxDlg::OnEraseBkgnd(CDC* pDC) { BOOL bRet = CDialog::OnEraseBkgnd(pDC); RECT rect; RECT size; m_pParentWnd->GetWindowRect(&rect); size.top = 0; size.left = 0; size.right = rect.right - rect.left; size.bottom = rect.bottom - rect.top; CBitmap cbmp; cbmp.LoadBitmapW(IDB_BITMAP1); BITMAP bmp; cbmp.GetBitmap(&bmp); CDC memDc; memDc.CreateCompatibleDC(pDC); memDc.SelectObject(&cbmp); pDC->StretchBlt(0,0,size.right,size.bottom,&memDc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY); return bRet; } ``` Instantiate it in the DoModal of the desired dialog, Create it like a Modal Dialog i.e. on the stack(or heap if desired), call it's Create manually, show it then create your actual modal dialog over the top of it: ``` INT_PTR CAboutDlg::DoModal() { LightBoxDlg Dlg(m_pParentWnd);//make sure to pass in the parent of the new dialog Dlg.Create(LightBoxDlg::IDD); Dlg.ShowWindow(SW_SHOW); BOOL ret = CDialog::DoModal(); Dlg.ShowWindow(SW_HIDE); return ret; } ``` and this results in something **exactly** like my mock up above \*there are still places for improvment, like doing it without making a dialog box to begin with and some other general tidyups.
51,690
<p>Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error:</p> <pre><code>Problem signature: Problem Event Name: BEX Application Name: iexplore.exe Application Version: 7.0.6001.18000 Application Timestamp: 47918f11 Fault Module Name: ntdll.dll Fault Module Version: 6.0.6001.18000 Fault Module Timestamp: 4791a7a6 Exception Offset: 00087ba6 Exception Code: c000000d Exception Data: 00000000 OS Version: 6.0.6001.2.1.0.768.3 Locale ID: 1037 Additional Information 1: fd00 Additional Information 2: ea6f5fe8924aaa756324d57f87834160 Additional Information 3: fd00 Additional Information 4: ea6f5fe8924aaa756324d57f87834160 </code></pre> <p>Googling revealed this sort of problems <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1194672&amp;SiteID=1" rel="noreferrer">is</a> <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=eu&amp;comments_parentId=101420&amp;forumId=1" rel="noreferrer">common</a> <a href="http://www.eggheadcafe.com/software/aspnet/29930817/bex-problem.aspx" rel="noreferrer">for</a> <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.vc.mfc&amp;tid=d511c635-3c99-431d-8118-526d3e3fff00&amp;cat=&amp;lang=&amp;cr=&amp;sloc=&amp;p=1" rel="noreferrer">Vista</a> and relates to <a href="http://www.gomanuals.com/java_not_working_on_windows_vista.shtml" rel="noreferrer">Java</a> (although SUN <a href="http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html" rel="noreferrer">negates</a>). Also I think it has something to do with DEP. I failed to find official Microsoft Kb.</p> <p>So, the questions are:</p> <ul> <li>What BEX stands for?</li> <li>What is it about?</li> <li>How to deal with such kind of errors?</li> </ul>
[ { "answer_id": 166316, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": true, "text": "<p>BEX=Buffer overflow exception. See <a href=\"http://technet.microsoft.com/en-us/library/cc738483.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc738483.aspx</a> for details. However, c000000d is STATUS_INVALID_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP)</p>\n" }, { "answer_id": 223855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Java and IE7 do not like to play together nicely. Just turn off DEP, it will work fine then.</p>\n\n<p><a href=\"http://www.tech-recipes.com/rx/1261/vista_disable_dep_noexecute_protection_fix_explorer_crashing/\" rel=\"nofollow noreferrer\">http://www.tech-recipes.com/rx/1261/vista_disable_dep_noexecute_protection_fix_explorer_crashing/</a></p>\n" }, { "answer_id": 351405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me</p>\n\n<p>go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me</p>\n" }, { "answer_id": 1055956, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Most likely there is an addon that is messing with IE.</p>\n\n<p>You can try this.\n1. Open IE\n2. Switch to the Advanced tab.\n3. Click the Reset Internet Explorer Settings button.\n4. Click Reset to confirm the operation.\n5. Click Close when the resetting process finished.\n6. Uncheck Enable third-party browser extensions option in the Settings box.\n7. Click Apply, click OK.</p>\n\n<p>After this, check to see if it works and if it does, enable one addon at a time until you find the culprit. Then uninstall it and reinstall it if you need it.</p>\n" }, { "answer_id": 1698970, "author": "chris", "author_id": 206566, "author_profile": "https://Stackoverflow.com/users/206566", "pm_score": 0, "selected": false, "text": "<p>just try disabling the bing or msn toolbar - should do the trick. </p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5383/" ]
Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error: ``` Problem signature: Problem Event Name: BEX Application Name: iexplore.exe Application Version: 7.0.6001.18000 Application Timestamp: 47918f11 Fault Module Name: ntdll.dll Fault Module Version: 6.0.6001.18000 Fault Module Timestamp: 4791a7a6 Exception Offset: 00087ba6 Exception Code: c000000d Exception Data: 00000000 OS Version: 6.0.6001.2.1.0.768.3 Locale ID: 1037 Additional Information 1: fd00 Additional Information 2: ea6f5fe8924aaa756324d57f87834160 Additional Information 3: fd00 Additional Information 4: ea6f5fe8924aaa756324d57f87834160 ``` Googling revealed this sort of problems [is](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1194672&SiteID=1) [common](http://support.mozilla.com/tiki-view_forum_thread.php?locale=eu&comments_parentId=101420&forumId=1) [for](http://www.eggheadcafe.com/software/aspnet/29930817/bex-problem.aspx) [Vista](http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.vc.mfc&tid=d511c635-3c99-431d-8118-526d3e3fff00&cat=&lang=&cr=&sloc=&p=1) and relates to [Java](http://www.gomanuals.com/java_not_working_on_windows_vista.shtml) (although SUN [negates](http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html)). Also I think it has something to do with DEP. I failed to find official Microsoft Kb. So, the questions are: * What BEX stands for? * What is it about? * How to deal with such kind of errors?
BEX=Buffer overflow exception. See <http://technet.microsoft.com/en-us/library/cc738483.aspx> for details. However, c000000d is STATUS\_INVALID\_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP)
51,700
<p>I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:</p> <pre><code>ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; </code></pre> <p>But it seems to return a string instead of ValuationInput and it throws an exception. </p> <p>I made a quick hack, which works fine:</p> <pre><code>string valuationInputStr = (string) Settings.Default.Properties["ValuationInput"].DefaultValue; XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput)); ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr)); </code></pre> <p>But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: <code>ValuationInput valuationInput = Settings.Default.ValuationInput;</code></p>
[ { "answer_id": 166316, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": true, "text": "<p>BEX=Buffer overflow exception. See <a href=\"http://technet.microsoft.com/en-us/library/cc738483.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc738483.aspx</a> for details. However, c000000d is STATUS_INVALID_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP)</p>\n" }, { "answer_id": 223855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Java and IE7 do not like to play together nicely. Just turn off DEP, it will work fine then.</p>\n\n<p><a href=\"http://www.tech-recipes.com/rx/1261/vista_disable_dep_noexecute_protection_fix_explorer_crashing/\" rel=\"nofollow noreferrer\">http://www.tech-recipes.com/rx/1261/vista_disable_dep_noexecute_protection_fix_explorer_crashing/</a></p>\n" }, { "answer_id": 351405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me</p>\n\n<p>go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me</p>\n" }, { "answer_id": 1055956, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Most likely there is an addon that is messing with IE.</p>\n\n<p>You can try this.\n1. Open IE\n2. Switch to the Advanced tab.\n3. Click the Reset Internet Explorer Settings button.\n4. Click Reset to confirm the operation.\n5. Click Close when the resetting process finished.\n6. Uncheck Enable third-party browser extensions option in the Settings box.\n7. Click Apply, click OK.</p>\n\n<p>After this, check to see if it works and if it does, enable one addon at a time until you find the culprit. Then uninstall it and reinstall it if you need it.</p>\n" }, { "answer_id": 1698970, "author": "chris", "author_id": 206566, "author_profile": "https://Stackoverflow.com/users/206566", "pm_score": 0, "selected": false, "text": "<p>just try disabling the bing or msn toolbar - should do the trick. </p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ]
I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use: ``` ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; ``` But it seems to return a string instead of ValuationInput and it throws an exception. I made a quick hack, which works fine: ``` string valuationInputStr = (string) Settings.Default.Properties["ValuationInput"].DefaultValue; XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput)); ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr)); ``` But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: `ValuationInput valuationInput = Settings.Default.ValuationInput;`
BEX=Buffer overflow exception. See <http://technet.microsoft.com/en-us/library/cc738483.aspx> for details. However, c000000d is STATUS\_INVALID\_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP)
51,741
<p>I was given an .xml file that I needed to read into my code as a DataSet (as background, the file was created by creating a <code>DataSet</code> in C# and calling <code>dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema)</code>, but this was done by someone else). </p> <p>The .xml file was shaped like this:</p> <pre><code> &lt;?xml version="1.0" standalone="yes"?&gt; &lt;NewDataSet&gt; &lt;Foo&gt; &lt;Bar&gt;abcd&lt;/Bar&gt; &lt;Foo&gt;efg&lt;/Foo&gt; &lt;/Foo&gt; &lt;Foo&gt; &lt;Bar&gt;hijk&lt;/Bar&gt; &lt;Foo&gt;lmn&lt;/Foo&gt; &lt;/Foo&gt; &lt;/NewDataSet&gt; </code></pre> <p>Using C# and .NET 2.0, I read the file in using the code below:</p> <pre><code> DataSet ds = new DataSet(); ds.ReadXml(file); </code></pre> <p>Using a breakpoint, after this <code>line ds.Tables[0]</code> looked like this (using dashes in place of underscores that I couldn't get to format properly):</p> <pre><code>Bar Foo-Id Foo-Id-0 abcd 0 null null 1 0 hijk 2 null null 3 2 </code></pre> <p>I have found a workaround (I know there are many) and have been able to successfully read in the .xml, but what I would like to understand why <code>ds.ReadXml(file)</code> performed in this manner, so I will be able to avoid the issue in the future. Thanks.</p>
[ { "answer_id": 51777, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 0, "selected": false, "text": "<p>These are my observations rather than a full answer:</p>\n\n<p>My guess (without trying to re-produce it myself) is that a couple of things may be happening as the DataSet tries to 'flatten' a hierarchical structure to a relational data structure.</p>\n\n<p>1) thinking about the data from a relational database perspective; there is no obvious primary key field for identifying each of the Foo elements in the collection so the DataSet has automatically used the ordinal position in the file as an auto-generated field called Foo-Id.</p>\n\n<p>2) There are actually two elements called 'Foo' so that probably explains the generation of a strange name for the column 'Foo-Id-0' (it has auto-generated a unique name for the column - I guess you could think of this as a fault-tolerant behaviour in the DataSet).</p>\n" }, { "answer_id": 51867, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<p>This appears to be correct for your <em>nested</em> Foo tags:</p>\n\n<pre><code>&lt;NewDataSet&gt; \n &lt;Foo&gt; &lt;!-- Foo-Id: 0 --&gt;\n &lt;Bar&gt;abcd&lt;/Bar&gt;\n &lt;Foo&gt;efg&lt;/Foo&gt; &lt;!-- Foo-Id: 1, Parent-Id: 0 --&gt;\n &lt;/Foo&gt;\n &lt;Foo&gt; &lt;!-- Foo-Id: 2 --&gt;\n &lt;Bar&gt;hijk&lt;/Bar&gt;\n &lt;Foo&gt;lmn&lt;/Foo&gt; &lt;!-- Foo-Id: 3, Parent-Id: 2 --&gt;\n &lt;/Foo&gt;\n&lt;/NewDataSet&gt;\n</code></pre>\n\n<p>So this correctly becomes 4 records in your result, with a parent-child key of \"Foo-Id-0\"</p>\n\n<p>Try:</p>\n\n<pre><code>&lt;NewDataSet&gt; \n &lt;Rec&gt; &lt;!-- Rec-Id: 0 --&gt;\n &lt;Bar&gt;abcd&lt;/Bar&gt;\n &lt;Foo&gt;efg&lt;/Foo&gt; \n &lt;/Rec&gt;\n &lt;Rec&gt; &lt;!-- Rec-Id: 1 --&gt;\n &lt;Bar&gt;hijk&lt;/Bar&gt;\n &lt;Foo&gt;lmn&lt;/Foo&gt; \n &lt;/Rec&gt;\n&lt;/NewDataSet&gt;\n</code></pre>\n\n<p>Which should result in:</p>\n\n<pre><code>Bar Foo Rec-Id\nabcd efg 0\nhijk lmn 1\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ]
I was given an .xml file that I needed to read into my code as a DataSet (as background, the file was created by creating a `DataSet` in C# and calling `dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema)`, but this was done by someone else). The .xml file was shaped like this: ``` <?xml version="1.0" standalone="yes"?> <NewDataSet> <Foo> <Bar>abcd</Bar> <Foo>efg</Foo> </Foo> <Foo> <Bar>hijk</Bar> <Foo>lmn</Foo> </Foo> </NewDataSet> ``` Using C# and .NET 2.0, I read the file in using the code below: ``` DataSet ds = new DataSet(); ds.ReadXml(file); ``` Using a breakpoint, after this `line ds.Tables[0]` looked like this (using dashes in place of underscores that I couldn't get to format properly): ``` Bar Foo-Id Foo-Id-0 abcd 0 null null 1 0 hijk 2 null null 3 2 ``` I have found a workaround (I know there are many) and have been able to successfully read in the .xml, but what I would like to understand why `ds.ReadXml(file)` performed in this manner, so I will be able to avoid the issue in the future. Thanks.
This appears to be correct for your *nested* Foo tags: ``` <NewDataSet> <Foo> <!-- Foo-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 --> </Foo> <Foo> <!-- Foo-Id: 2 --> <Bar>hijk</Bar> <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 --> </Foo> </NewDataSet> ``` So this correctly becomes 4 records in your result, with a parent-child key of "Foo-Id-0" Try: ``` <NewDataSet> <Rec> <!-- Rec-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> </Rec> <Rec> <!-- Rec-Id: 1 --> <Bar>hijk</Bar> <Foo>lmn</Foo> </Rec> </NewDataSet> ``` Which should result in: ``` Bar Foo Rec-Id abcd efg 0 hijk lmn 1 ```
51,751
<p>I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE. FireFox works fine. If I install the website on another machine without .Net 3.5 SP1, it works as expected.</p> <p>When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed". The form seems to be posting to pages other than page I'm viewing.</p> <p>The form's action is "#" for the page on the broken website (with SP1). The form's action is "Default.aspx" for the same page on a website without SP1.</p> <p>Any ideas?</p>
[ { "answer_id": 51777, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 0, "selected": false, "text": "<p>These are my observations rather than a full answer:</p>\n\n<p>My guess (without trying to re-produce it myself) is that a couple of things may be happening as the DataSet tries to 'flatten' a hierarchical structure to a relational data structure.</p>\n\n<p>1) thinking about the data from a relational database perspective; there is no obvious primary key field for identifying each of the Foo elements in the collection so the DataSet has automatically used the ordinal position in the file as an auto-generated field called Foo-Id.</p>\n\n<p>2) There are actually two elements called 'Foo' so that probably explains the generation of a strange name for the column 'Foo-Id-0' (it has auto-generated a unique name for the column - I guess you could think of this as a fault-tolerant behaviour in the DataSet).</p>\n" }, { "answer_id": 51867, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<p>This appears to be correct for your <em>nested</em> Foo tags:</p>\n\n<pre><code>&lt;NewDataSet&gt; \n &lt;Foo&gt; &lt;!-- Foo-Id: 0 --&gt;\n &lt;Bar&gt;abcd&lt;/Bar&gt;\n &lt;Foo&gt;efg&lt;/Foo&gt; &lt;!-- Foo-Id: 1, Parent-Id: 0 --&gt;\n &lt;/Foo&gt;\n &lt;Foo&gt; &lt;!-- Foo-Id: 2 --&gt;\n &lt;Bar&gt;hijk&lt;/Bar&gt;\n &lt;Foo&gt;lmn&lt;/Foo&gt; &lt;!-- Foo-Id: 3, Parent-Id: 2 --&gt;\n &lt;/Foo&gt;\n&lt;/NewDataSet&gt;\n</code></pre>\n\n<p>So this correctly becomes 4 records in your result, with a parent-child key of \"Foo-Id-0\"</p>\n\n<p>Try:</p>\n\n<pre><code>&lt;NewDataSet&gt; \n &lt;Rec&gt; &lt;!-- Rec-Id: 0 --&gt;\n &lt;Bar&gt;abcd&lt;/Bar&gt;\n &lt;Foo&gt;efg&lt;/Foo&gt; \n &lt;/Rec&gt;\n &lt;Rec&gt; &lt;!-- Rec-Id: 1 --&gt;\n &lt;Bar&gt;hijk&lt;/Bar&gt;\n &lt;Foo&gt;lmn&lt;/Foo&gt; \n &lt;/Rec&gt;\n&lt;/NewDataSet&gt;\n</code></pre>\n\n<p>Which should result in:</p>\n\n<pre><code>Bar Foo Rec-Id\nabcd efg 0\nhijk lmn 1\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5389/" ]
I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE. FireFox works fine. If I install the website on another machine without .Net 3.5 SP1, it works as expected. When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed". The form seems to be posting to pages other than page I'm viewing. The form's action is "#" for the page on the broken website (with SP1). The form's action is "Default.aspx" for the same page on a website without SP1. Any ideas?
This appears to be correct for your *nested* Foo tags: ``` <NewDataSet> <Foo> <!-- Foo-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 --> </Foo> <Foo> <!-- Foo-Id: 2 --> <Bar>hijk</Bar> <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 --> </Foo> </NewDataSet> ``` So this correctly becomes 4 records in your result, with a parent-child key of "Foo-Id-0" Try: ``` <NewDataSet> <Rec> <!-- Rec-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> </Rec> <Rec> <!-- Rec-Id: 1 --> <Bar>hijk</Bar> <Foo>lmn</Foo> </Rec> </NewDataSet> ``` Which should result in: ``` Bar Foo Rec-Id abcd efg 0 hijk lmn 1 ```
51,768
<p>As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog.</p> <p>A .NET stack trace on my machine looks like this:</p> <pre><code>at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(String path) at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 </code></pre> <p>I have this question:</p> <p>The format looks to be this:</p> <pre><code>at &lt;class/method&gt; [in file:line ##] </code></pre> <p>However, the <em>at</em> and <em>in</em> keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed.</p> <p>Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this?</p> <p>In other words, I'd like this information from the above text:</p> <pre><code>C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 </code></pre> <p>Any advice you can give will be helpful.</p>
[ { "answer_id": 51803, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 7, "selected": true, "text": "<p>You should be able to get a StackTrace object instead of a string by saying</p>\n\n<pre><code>var trace = new System.Diagnostics.StackTrace(exception);\n</code></pre>\n\n<p>You can then look at the frames yourself without relying on the framework's formatting.</p>\n\n<p>See also: <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx\" rel=\"noreferrer\">StackTrace reference</a></p>\n" }, { "answer_id": 51821, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "<p>As alternative, log4net, though potentially dangerous, has given me better results than System.Diagnostics. Basically in log4net, you have a method for the various log levels, each with an Exception parameter. So, when you pass the second exception, it will print the stack trace to whichever appender you have configured. </p>\n\n<p>example: <code>Logger.Error(\"Danger!!!\", myException );</code></p>\n\n<p>The output, depending on configuration, looks something like</p>\n\n<pre><code>System.ApplicationException: Something went wrong.\n at Adapter.WriteToFile(OleDbCommand cmd) in C:\\Adapter.vb:line 35\n at Adapter.GetDistributionDocument(Int32 id) in C:\\Adapter.vb:line 181\n ...\n</code></pre>\n" }, { "answer_id": 1239123, "author": "Lindholm", "author_id": 122253, "author_profile": "https://Stackoverflow.com/users/122253", "pm_score": 5, "selected": false, "text": "<p>Here is the code I use to do this without an exception</p>\n\n<pre><code>public static void LogStack()\n{\n var trace = new System.Diagnostics.StackTrace();\n foreach (var frame in trace.GetFrames())\n {\n var method = frame.GetMethod();\n if (method.Name.Equals(\"LogStack\")) continue;\n Log.Debug(string.Format(\"{0}::{1}\", \n method.ReflectedType != null ? method.ReflectedType.Name : string.Empty,\n method.Name));\n }\n}\n</code></pre>\n" }, { "answer_id": 6088221, "author": "Hertzel Guinness", "author_id": 293974, "author_profile": "https://Stackoverflow.com/users/293974", "pm_score": 4, "selected": false, "text": "<p>Just to make this a 15 sec copy-paste answer:</p>\n\n<pre><code>static public string StackTraceToString()\n{\n StringBuilder sb = new StringBuilder(256);\n var frames = new System.Diagnostics.StackTrace().GetFrames();\n for (int i = 1; i &lt; frames.Length; i++) /* Ignore current StackTraceToString method...*/\n {\n var currFrame = frames[i];\n var method = currFrame.GetMethod();\n sb.AppendLine(string.Format(\"{0}:{1}\", \n method.ReflectedType != null ? method.ReflectedType.Name : string.Empty,\n method.Name));\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p>(based on Lindholm answer)</p>\n" }, { "answer_id": 8779644, "author": "Aftershock", "author_id": 135807, "author_profile": "https://Stackoverflow.com/users/135807", "pm_score": 3, "selected": false, "text": "<p>Or there is even shorter version..</p>\n\n<pre><code>Console.Write(exception.StackTrace);\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog. A .NET stack trace on my machine looks like this: ``` at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(String path) at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 ``` I have this question: The format looks to be this: ``` at <class/method> [in file:line ##] ``` However, the *at* and *in* keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed. Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this? In other words, I'd like this information from the above text: ``` C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 ``` Any advice you can give will be helpful.
You should be able to get a StackTrace object instead of a string by saying ``` var trace = new System.Diagnostics.StackTrace(exception); ``` You can then look at the frames yourself without relying on the framework's formatting. See also: [StackTrace reference](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx)
51,781
<p>I have a variable of type <code>Dynamic</code> and I know for sure one of its fields, lets call it <code>a</code>, actually is an array. But when I'm writing </p> <pre><code>var d : Dynamic = getDynamic(); for (t in d.a) { } </code></pre> <p>I get a compilation error on line two:</p> <blockquote> <p>You can't iterate on a Dynamic value, please specify Iterator or Iterable</p> </blockquote> <p>How can I make this compilable?</p>
[ { "answer_id": 51802, "author": "Danny Wilson", "author_id": 5364, "author_profile": "https://Stackoverflow.com/users/5364", "pm_score": 4, "selected": true, "text": "<p>Haxe can't iterate over <code>Dynamic</code> variables (as the compiler says).</p>\n\n<p>You can make it work in several ways, where this one is probably easiest (depending on your situation):</p>\n\n<pre><code>var d : {a:Array&lt;Dynamic&gt;} = getDynamic();\nfor (t in d.a) { ... }\n</code></pre>\n\n<p>You could also change <code>Dynamic</code> to the type of the contents of the array.</p>\n" }, { "answer_id": 67059, "author": "Michael Pliskin", "author_id": 9777, "author_profile": "https://Stackoverflow.com/users/9777", "pm_score": 2, "selected": false, "text": "<p>Another way to do the same is to use an extra temp variable and explicit typing:</p>\n\n<pre><code>var d = getDynamic();\nvar a: Array&lt;Dynamic&gt; = d.a;\nfor (t in a) { ... }\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a variable of type `Dynamic` and I know for sure one of its fields, lets call it `a`, actually is an array. But when I'm writing ``` var d : Dynamic = getDynamic(); for (t in d.a) { } ``` I get a compilation error on line two: > > You can't iterate on a Dynamic value, please specify Iterator or Iterable > > > How can I make this compilable?
Haxe can't iterate over `Dynamic` variables (as the compiler says). You can make it work in several ways, where this one is probably easiest (depending on your situation): ``` var d : {a:Array<Dynamic>} = getDynamic(); for (t in d.a) { ... } ``` You could also change `Dynamic` to the type of the contents of the array.
51,783
<p>Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data.</p> <p>But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges.</p> <p>So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly.</p> <p>I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this.</p>
[ { "answer_id": 51794, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 3, "selected": false, "text": "<p>XML is very verbose. Whenever I do it, I roll my own. Here's an example of a 3 node directed acyclic graph. It's pretty compact and does everything I need it to do:</p>\n\n<pre><code>0: foo\n1: bar\n2: bat\n----\n0 1\n0 2\n1 2\n</code></pre>\n" }, { "answer_id": 51804, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 0, "selected": false, "text": "<p>On a less academic, more practical note, in <a href=\"http://cubictest.openqa.org\" rel=\"nofollow noreferrer\">CubicTest</a> we use <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">Xstream</a> (Java) to serialize tests to and from xml. Xstream handles graph-structured object relations, so you might learn a thing or two from looking at it's source and the resulting xml. You're right about the <em>ugly</em> part though, the generated xml files don't look pretty.</p>\n" }, { "answer_id": 51814, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 1, "selected": false, "text": "<p>One example you might be familiar is Java serialization. This effectively serializes by graph, with each object instance being a node, and each reference being an edge. The algorithm used is recursive, but skipping duplicates. So the pseudo code would be:</p>\n\n<pre><code>serialize(x):\n done - a set of serialized objects\n if(serialized(x, done)) then return\n otherwise:\n record properties of x\n record x as serialized in done\n for each neighbour/child of x: serialize(child)\n</code></pre>\n\n<p>Another way of course is as a list of nodes and edges, which can be done as XML, or in any other preferred serialization format, or as an adjacency matrix.</p>\n" }, { "answer_id": 51816, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 5, "selected": true, "text": "<p>How do you represent your graph in memory?<br>\nBasically you have two (good) options:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Adjacency_list\" rel=\"noreferrer\">an adjacency list representation</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Adjacency_matrix\" rel=\"noreferrer\">an adjacency matrix representation</a></li>\n</ul>\n\n<p>in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs.</p>\n\n<p>If you used suchs representations then you could serialize those representations instead.</p>\n\n<p>If it has to be <em>human readable</em> you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any \"normal\" matrix: just print out the columns and rows, and all the data in it like so:</p>\n\n<pre><code> 1 2 3\n1 #t #f #f\n2 #f #f #t\n3 #f #t #f\n</code></pre>\n\n<p>(this is a non-optimized, non weighted representation, but can be used for directed graphs)</p>\n" }, { "answer_id": 51838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Typically relationships in XML are shown by the parent/child relationship. XML can handle graph data but not in this manner. To handle graphs in XML you should use the <a href=\"http://www.zvon.org/xxl/xmlSchema2001Reference/Standard/xmlschema-2.html#ID\" rel=\"noreferrer\">xs:ID</a> and <a href=\"http://www.zvon.org/xxl/xmlSchema2001Reference/Standard/xmlschema-2.html#IDREF\" rel=\"noreferrer\">xs:IDREF</a> schema types.</p>\n\n<p>In an example, assume that node/@id is an xs:ID type and that link/@ref is an xs:IDREF type. The following XML shows the cycle of three nodes 1 -> 2 -> 3 -> 1.</p>\n\n<pre><code>&lt;data&gt;\n &lt;node id=\"1\"&gt; \n &lt;link ref=\"2\"/&gt;\n &lt;/node&gt;\n &lt;node id=\"2\"&gt;\n &lt;link ref=\"3\"/&gt;\n &lt;/node&gt;\n &lt;node id=\"3\"&gt;\n &lt;link ref=\"1\"/&gt;\n &lt;/node&gt;\n&lt;/data&gt;\n</code></pre>\n\n<p>Many development tools have support for ID and IDREF too. I have used Java's JAXB (Java XML Binding. It supports these through the <a href=\"http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlID.html\" rel=\"noreferrer\">@XmlID</a> and the <a href=\"http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlIDREF.html\" rel=\"noreferrer\">@XmlIDREF</a> annotations. You can build your graph using plain Java objects and then use JAXB to handle the actual serialization to XML.</p>\n" }, { "answer_id": 145095, "author": "jbl", "author_id": 2353001, "author_profile": "https://Stackoverflow.com/users/2353001", "pm_score": 1, "selected": false, "text": "<p>Adjacency lists and adjacency matrices are the two common ways of representing graphs in memory. The first decision you need to make when deciding between these two is what you want to optimize for. Adjacency lists are very fast if you need to, for example, get the list of a vertex's neighbors. On the other hand, if you are doing a lot of testing for edge existence or have a graph representation of a markov chain, then you'd probably favor an adjacency matrix.</p>\n\n<p>The next question you need to consider is how much you need to fit into memory. In most cases, where the number of edges in the graph is much much smaller than the total number of possible edges, an adjacency list is going to be more efficient, since you only need to store the edges that actually exist. A happy medium is to represent the adjacency matrix in compressed sparse row format in which you keep a vector of the non-zero entries from top left to bottom right, a corresponding vector indicating which columns the non-zero entries can be found in, and a third vector indicating the start of each row in the column-entry vector.</p>\n\n<pre><code>[[0.0, 0.0, 0.3, 0.1]\n [0.1, 0.0, 0.0, 0.0]\n [0.0, 0.0, 0.0, 0.0]\n [0.5, 0.2, 0.0, 0.3]]\n</code></pre>\n\n<p>can be represented as:</p>\n\n<pre><code>vals: [0.3, 0.1, 0.1, 0.5, 0.2, 0.3]\ncols: [2, 3, 0, 0, 1, 4]\nrows: [0, 2, null, 4]\n</code></pre>\n\n<p>Compressed sparse row is effectively an adjacency list (the column indices function the same way), but the format lends itself a bit more cleanly to matrix operations.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data. But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges. So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly. I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this.
How do you represent your graph in memory? Basically you have two (good) options: * [an adjacency list representation](http://en.wikipedia.org/wiki/Adjacency_list) * [an adjacency matrix representation](http://en.wikipedia.org/wiki/Adjacency_matrix) in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs. If you used suchs representations then you could serialize those representations instead. If it has to be *human readable* you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any "normal" matrix: just print out the columns and rows, and all the data in it like so: ``` 1 2 3 1 #t #f #f 2 #f #f #t 3 #f #t #f ``` (this is a non-optimized, non weighted representation, but can be used for directed graphs)
51,786
<p>How can I generate UML diagrams (especially sequence diagrams) from existing Java code?</p>
[ { "answer_id": 51864, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 5, "selected": false, "text": "<p>What is your codebase? Java or C++?</p>\n\n<p><a href=\"http://marketplace.eclipse.org/content/euml2-free-edition\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c8TO1.png\" alt=\"alt text\"></a></p>\n\n<blockquote>\n <p>eUML2 for Java is a powerful UML modeler designed for Java developper\n in Eclipse. The free edition can be used for commercial use. It\n supports the following features:</p>\n \n <ul>\n <li>CVS and Team Support</li>\n <li>Designed for large project with multiple and customizable model views</li>\n <li>Helios Compliant</li>\n <li>Real-time code/model synchronization</li>\n <li>UML2.1 compliant and support of OMG XMI</li>\n <li>JDK 1.4 and 1.5 support</li>\n <li><p>The commercial edition provides:</p></li>\n <li><p>Advanced reversed engineering</p></li>\n <li>Powerful true dependency analyze tools</li>\n <li>UML Profile and MDD</li>\n <li>Database tools</li>\n <li>Customizable template support</li>\n </ul>\n</blockquote>\n" }, { "answer_id": 114412, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 1, "selected": false, "text": "<p>By far the best tool I have used for reverse engineering, and round tripping java -> UML is <a href=\"http://www.borland.com/products/together/default.aspx\" rel=\"nofollow noreferrer\">Borland's Together</a>. It is based on Eclipse (not just a single plugin) and really works well.</p>\n" }, { "answer_id": 732247, "author": "Vineet Reynolds", "author_id": 3916, "author_profile": "https://Stackoverflow.com/users/3916", "pm_score": 2, "selected": false, "text": "<p>I would recommend <a href=\"http://www.omondo.com\" rel=\"nofollow noreferrer\">EclipseUML from Omondo</a> for general usage, although I did experience some problems a few months back, with my web projects. They had a free edition at one point in time, but that is supposedly no longer promoted.</p>\n\n<p>If you are really keen on reverse engineering sequence diagrams from source code, I would recommend <a href=\"http://code.google.com/p/jtracert/\" rel=\"nofollow noreferrer\">jTracert</a>.</p>\n\n<p>As far as Eclipse projects themselves are concerned, the <a href=\"http://wiki.eclipse.org/MDT-UML2Tools\" rel=\"nofollow noreferrer\">Eclipse UML2 Tools</a> project might support reverse engineering, although I've have never seen its use in practice.</p>\n\n<p>The <a href=\"http://www.eclipse.org/gmt/modisco/\" rel=\"nofollow noreferrer\">MoDisco</a> (Model Discovery) project Eclipse GMT project seems to be clearer in achieving your objective. The <a href=\"http://www.eclipse.org/gmt/modisco/technologies/\" rel=\"nofollow noreferrer\">list of technology specific tools</a> would be a good place to start with.</p>\n" }, { "answer_id": 824221, "author": "Patrick Cornelissen", "author_id": 33624, "author_profile": "https://Stackoverflow.com/users/33624", "pm_score": 2, "selected": false, "text": "<p>You could also give the netbeans UML modeller a try. I have used it to generate javacode that I used in my eclipse projects. You can even import eclipse projects in netbeans and keep the eclipse settings synced with the netbeans project settings.</p>\n\n<p>I tried several UML modellers for eclipse and wasn't satisfied with them. They were either unstable, complicated or just plain ugly. ;-)</p>\n" }, { "answer_id": 4007561, "author": "Zamel", "author_id": 22158, "author_profile": "https://Stackoverflow.com/users/22158", "pm_score": 3, "selected": false, "text": "<p>How about <a href=\"http://plantuml.sourceforge.net/\" rel=\"noreferrer\">PlantUML</a>?\nIt's not for reverse engineering!!! It's for engineering before you code.</p>\n" }, { "answer_id": 4884743, "author": "UML GURU", "author_id": 294000, "author_profile": "https://Stackoverflow.com/users/294000", "pm_score": 2, "selected": false, "text": "<p>You can use the 30 days evaluation build of EclipseUML for Eclipse 3.5 : <a href=\"http://www.uml2.org/eclipse-java-galileo-SR2-win32_eclipseUML2.2_package_may2010.zip\" rel=\"nofollow noreferrer\">http://www.uml2.org/eclipse-java-galileo-SR2-win32_eclipseUML2.2_package_may2010.zip</a>\nThis is not the latest 3.6 build, but is pretty good and don't require you purchase it for testing and reverse engineering.</p>\n\n<p>Reverse engineering : <a href=\"http://www.forum-omondo.com/documentation_eclipseuml_2008/reverse/reverse/reverse_engineering_example.html\" rel=\"nofollow noreferrer\">http://www.forum-omondo.com/documentation_eclipseuml_2008/reverse/reverse/reverse_engineering_example.html</a></p>\n\n<p>Live flash demo: <a href=\"http://www.ejb3.org/reverse.swf\" rel=\"nofollow noreferrer\">http://www.ejb3.org/reverse.swf</a></p>\n\n<p>EclipseUML Omondo is the best tool in the world for Java. Only eUML seems to compete with it on this live java synchronization market, but eUML adds model tags in the code which is really very very bad and a definitive no go for me.</p>\n" }, { "answer_id": 5818760, "author": "pcmind", "author_id": 600207, "author_profile": "https://Stackoverflow.com/users/600207", "pm_score": 2, "selected": false, "text": "<p>I found <a href=\"http://green.sourceforge.net/\" rel=\"nofollow\">Green</a> plugin very simple to use and to generate class diagram from source code.\nGive it a try :).\nJust copy the plugin to your plugin dir.</p>\n" }, { "answer_id": 8751193, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 8, "selected": false, "text": "<h1><a href=\"http://www.objectaid.com/home\" rel=\"noreferrer\">ObjectAid UML Explorer</a></h1>\n\n<p>Is what I used. It is easily <strong><a href=\"https://www.objectaid.com/install-objectaid\" rel=\"noreferrer\">installed</a></strong> from the repository:</p>\n\n<pre><code>Name: ObjectAid UML Explorer\nLocation: http://www.objectaid.com/update/current\n</code></pre>\n\n<p>And produces quite nice UML diagrams:</p>\n\n<p><img src=\"https://i.stack.imgur.com/QPnZD.png\" alt=\"Screenshot\"></p>\n\n<h2>Description from the website:</h2>\n\n<blockquote>\n <p>The ObjectAid UML Explorer is different from other UML tools. It uses\n the UML notation to show a graphical representation of existing code\n that is as accurate and up-to-date as your text editor, while being\n very easy to use. Several unique features make this possible:</p>\n \n <ul>\n <li>Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format.</li>\n <li>If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code.</li>\n <li>Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the\n changes without going out of sync.</li>\n <li>All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your\n version control system.</li>\n <li>Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related\n information is shown in other views wherever applicable.</li>\n </ul>\n</blockquote>\n" }, { "answer_id": 10966290, "author": "Ismail Marmoush", "author_id": 263215, "author_profile": "https://Stackoverflow.com/users/263215", "pm_score": 6, "selected": false, "text": "<p>EDIT:\nIf you're a designer then <a href=\"http://www.papyrusuml.org\" rel=\"nofollow noreferrer\">Papyrus</a> is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then <a href=\"http://objectaid.com/\" rel=\"nofollow noreferrer\">ObjectAid</a> is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.</p>\n\n<hr>\n\n<p><strong>UPDATE Oct 11th, 2013</strong></p>\n\n<p>My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.</p>\n\n<p>I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.</p>\n\n<p><strong>The Answer</strong> (Oct 11th, 2013)</p>\n\n<p><strong>Tools</strong></p>\n\n<ol>\n<li>Download Papyrus</li>\n<li>Go to Help -> Install New Software...</li>\n<li>In the <em>Work with:</em> drop-down, select <em>--All Available Sites--</em></li>\n<li>In the filter, type in <em>Papyrus</em></li>\n<li>After installation finishes restart Eclipse</li>\n<li>Repeat steps 1-3 and this time, install <em>Modisco</em></li>\n</ol>\n\n<p><strong>Steps</strong></p>\n\n<ol>\n<li>In your java project (assume it's called MyProject) create a folder e.g UML</li>\n<li>Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated.\n<img src=\"https://i.stack.imgur.com/4PnYJ.png\" alt=\"enter image description here\"></li>\n<li>Right click project name file --> new --> papyrus model -> and call it MyProject.</li>\n<li>Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder</li>\n<li><p>Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml \n<img src=\"https://i.stack.imgur.com/x4YZO.png\" alt=\"enter image description here\"></p></li>\n<li><p>Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.</p></li>\n<li><p>ALT+W -> show view -> papyrus -> model explorer</p></li>\n<li><p>In that view, you'll find your classes like in the picture \n<img src=\"https://i.stack.imgur.com/VLL54.png\" alt=\"enter image description here\"></p></li>\n<li><p>In the view Right click root model -> New diagram <img src=\"https://i.stack.imgur.com/jIBGE.png\" alt=\"enter image description here\"></p></li>\n<li><p>Then start grabbing classes to the diagram from the view</p></li>\n</ol>\n\n<p><strong>Some features</strong></p>\n\n<ul>\n<li><p>To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!</p></li>\n<li><p>You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram</p></li>\n<li><p>one very important setting is <strong>Arrange</strong> when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All</p></li>\n<li><p>Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc</p></li>\n<li><p>After all of that your settings will show diagrams like \n<img src=\"https://i.stack.imgur.com/CEPI8.png\" alt=\"enter image description here\"></p></li>\n<li><p>Synchronization isn't available as far as I know you'll need to manually import any new classes.</p></li>\n</ul>\n\n<p>That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.</p>\n\n<p>Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.</p>\n" }, { "answer_id": 31780857, "author": "Masood", "author_id": 2713018, "author_profile": "https://Stackoverflow.com/users/2713018", "pm_score": 0, "selected": false, "text": "<p>I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.</p>\n\n<p>you can install PlantUML plugin in the netbeans by this method:</p>\n\n<p>Netbeans Menu -> Tools -> Plugin</p>\n\n<p>Now select Available Plugins and then find PlantUML and install it.</p>\n\n<p>For more information go to website: www.plantuml.com</p>\n" }, { "answer_id": 39018106, "author": "juanmf", "author_id": 711855, "author_profile": "https://Stackoverflow.com/users/711855", "pm_score": 3, "selected": false, "text": "<p>I developed a <strong>maven plugin that can</strong> both, be run from CLI as a plugin goal, or import as dependency and programmatically use the parser, <code>@see Main#main()</code> to get the idea on how. </p>\n\n<p>It <strong>renders <a href=\"http://plantuml.com/classes.html\" rel=\"nofollow noreferrer\">PlantUML</a> src code of desired packages recursively</strong> that you can edit manually if needed (hopefully you won't). Then, by pasting the code in the plantUML page, or by downloading plant's jar you can render the UML diagram as a png image. </p>\n\n<p>Check it out here <a href=\"https://github.com/juanmf/Java2PlantUML\" rel=\"nofollow noreferrer\">https://github.com/juanmf/Java2PlantUML</a></p>\n\n<p>Example output diagram:\n<a href=\"https://i.stack.imgur.com/kkUpH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kkUpH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any contribution is more than welcome. It has a set of filters that customize output but I didn't expose these yet in the plugin CLI params.</p>\n\n<p><strong>It's important to note that it's not limited to your *.java files, it can render UML diagrams src from you maven dependencies as well. This is very handy to understand libraries you depend on. It actually inspects compiled classes with reflection so no source needed</strong> </p>\n\n<p>Be the 1st to star it at GitHub :P </p>\n" }, { "answer_id": 45166435, "author": "Ihor Rybak", "author_id": 5810648, "author_profile": "https://Stackoverflow.com/users/5810648", "pm_score": 2, "selected": false, "text": "<p>Using IntelliJ IDEA. To generate class diagram select package and press <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>U</kbd>:<a href=\"https://i.stack.imgur.com/WBXpI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WBXpI.png\" alt=\"enter image description here\"></a></p>\n\n<p>By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies:\n<a href=\"https://i.stack.imgur.com/DFsXM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DFsXM.png\" alt=\"enter image description here\"></a></p>\n\n<p>To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>U</kbd>:\n<a href=\"https://i.stack.imgur.com/HblBN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HblBN.png\" alt=\"enter image description here\"></a></p>\n\n<p>The result:\n<a href=\"https://i.stack.imgur.com/7HQhD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7HQhD.png\" alt=\"enter image description here\"></a></p>\n\n<p>Also it is possible to generate more others diagrams. See <a href=\"https://www.jetbrains.com/help/idea/working-with-diagrams.html\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n" }, { "answer_id": 45239269, "author": "Devs love ZenUML", "author_id": 529187, "author_profile": "https://Stackoverflow.com/users/529187", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally.</p>\n</blockquote>\n\n<p>On Intellij IDEA, ZenUML can generate sequence diagram from Java code.\n<a href=\"https://i.stack.imgur.com/UcsWi.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UcsWi.gif\" alt=\"enter image description here\"></a></p>\n\n<p>Check it out at <a href=\"https://plugins.jetbrains.com/plugin/12437-zenuml-support\" rel=\"nofollow noreferrer\">https://plugins.jetbrains.com/plugin/12437-zenuml-support</a></p>\n\n<p>Source code: <a href=\"https://github.com/ZenUml/jetbrains-zenuml\" rel=\"nofollow noreferrer\">https://github.com/ZenUml/jetbrains-zenuml</a></p>\n" }, { "answer_id": 52669901, "author": "whoami - fakeFaceTrueSoul", "author_id": 7237613, "author_profile": "https://Stackoverflow.com/users/7237613", "pm_score": 1, "selected": false, "text": "<p>I've noticed SequenceDiagram plugin for Intellij is also a good option.</p>\n" }, { "answer_id": 57943814, "author": "abulka", "author_id": 528955, "author_profile": "https://Stackoverflow.com/users/528955", "pm_score": 1, "selected": false, "text": "<p>Another modelling tool for Java is (my) website <a href=\"https://www.gituml.com\" rel=\"nofollow noreferrer\">GitUML</a>.\nGenerate UML diagrams from Java or Python code stored in GitHub repositories. </p>\n\n<p>One key idea with GitUML is to address one of the problems with \"documentation\": that diagrams are always out of date. With GitUML, diagrams automatically update when you push code using git.</p>\n\n<p>Browse through community UML diagrams, there are some Java design patterns there. Surf through popular GitHub repositories and visualise the architectures and patterns in them.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hjt0p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hjt0p.png\" alt=\"diagram browser\"></a></p>\n\n<p>Create diagrams using point and click. There is no drag drop editor, just click on the classes in the repository tree that you want to visualise:</p>\n\n<p><a href=\"https://i.stack.imgur.com/O6ARG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O6ARG.png\" alt=\"select the java classes you want to visualise\"></a></p>\n\n<p>The underlying technology is PlantUML based, which means you can refine your diagrams with additional PlantUML markup.</p>\n" }, { "answer_id": 60583105, "author": "Happy", "author_id": 2412606, "author_profile": "https://Stackoverflow.com/users/2412606", "pm_score": 1, "selected": false, "text": "<p>There is a <strong>Free</strong> tool named <a href=\"https://github.com/fuiny/binarydoc-docker\" rel=\"nofollow noreferrer\">binarydoc</a> which can generate <code>UML Sequence Diagram</code>, or <code>Control Flow Graph</code> (<code>CFG</code>) from the <code>bytecode</code> (instead of source code) of a Java method.</p>\n<p>Here is an sample diagram <strong>binarydoc</strong> generated for the java method <a href=\"https://openjdk.binarydoc.org/net.java/openjdk/13.0/method?classfilelocation=java.net.abstractplainsocketimpl&amp;seq=19&amp;methodname=getInputStream\" rel=\"nofollow noreferrer\">java.net.AbstractPlainSocketImpl.getInputStream</a>:</p>\n<ul>\n<li><strong>Control Flow Graph</strong> of method <code>java.net.AbstractPlainSocketImpl.getInputStream</code>:</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/xuV2z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xuV2z.png\" alt=\"Control Flow Graph\" /></a></p>\n<ul>\n<li><strong>UML Sequence Diagram</strong> of method <code>java.net.AbstractPlainSocketImpl.getInputStream</code>:</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/fQ3HW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fQ3HW.png\" alt=\"UML Sequence Diagram\" /></a></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772/" ]
How can I generate UML diagrams (especially sequence diagrams) from existing Java code?
[ObjectAid UML Explorer](http://www.objectaid.com/home) ======================================================= Is what I used. It is easily **[installed](https://www.objectaid.com/install-objectaid)** from the repository: ``` Name: ObjectAid UML Explorer Location: http://www.objectaid.com/update/current ``` And produces quite nice UML diagrams: ![Screenshot](https://i.stack.imgur.com/QPnZD.png) Description from the website: ----------------------------- > > The ObjectAid UML Explorer is different from other UML tools. It uses > the UML notation to show a graphical representation of existing code > that is as accurate and up-to-date as your text editor, while being > very easy to use. Several unique features make this possible: > > > * Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format. > * If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code. > * Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the > changes without going out of sync. > * All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your > version control system. > * Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related > information is shown in other views wherever applicable. > > >
51,827
<p>I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object.</p> <p>I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built. </p> <p>Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore. </p> <p>Is there a cleaner, more stable way of doing this?</p> <p>Any Suggestions?</p> <p>EDIT: To add detail to my previous post:</p> <ol> <li>I cannot really template my query due to the requirements. It just changes too much.</li> <li>I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by </li> <li>Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax].</li> <li>I am using an efficient paging technique that uses Row_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query.</li> </ol> <p>I will show some code (the horror!) so that you guys have an idea of what I'm dealing with.</p> <pre><code>sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare + ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible + "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " " + sortDirection + ") as ROWRANK" // generates a rowrank for each row + outerFields + " FROM ( SELECT c.id AS ContactID" + coreFields + from // sometimes different tables are required + where + ") T " // user input goes here. + groupBy+ " " + havingClause //can be empty + ";" + "select @@rowcount as rCount;" // return 2 recordsets, avoids second query + " SELECT " + fields + ",field1,field2" // join onto the other cols n the table +" FROM @t t INNER JOIN contacts c on t.ContactID = c.id" +" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND " + ( (pageIndex + 1) * pageSize); // here I select the pages I want </code></pre> <p>In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so:</p> <pre><code>// Add Parameter to SQL Command AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue); // Create SQL code Fragment where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z); </code></pre>
[ { "answer_id": 51839, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 0, "selected": false, "text": "<p>Out of curiousity, have you considered using an ORM for managing your data access. A lot of the functionality you're trying to implement could already be there. It may be something to look at because its best not to re-invent the wheel.</p>\n" }, { "answer_id": 51841, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>You could try the approach used by code generation tools like CodeSmith. Create a SQL template with placeholders. At runtime, read the template into a string and substitute the placeholders with actual values. This is only useful if all the SQL code follow a pattern.</p>\n" }, { "answer_id": 51848, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": true, "text": "<p>I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL: </p>\n\n<ul>\n<li>Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query.</li>\n<li>The last five classes are all related to a Query object. So the Query object itself has collections of each class.</li>\n<li>Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods</li>\n</ul>\n\n<p>It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don't think that there are any big switch statements). And don't forget to use StringBuilder.</p>\n" }, { "answer_id": 51935, "author": "Scott Lawrence", "author_id": 3475, "author_profile": "https://Stackoverflow.com/users/3475", "pm_score": 1, "selected": false, "text": "<p>Gulzar and Ryan Lanciaux make good points in mentioning CodeSmith and ORM. Either of those might reduce or eliminate your current burden when it comes to generating dynamic SQL. Your current approach of using parameterized SQL is wise, simply because it protects well against SQL injection attacks.</p>\n\n<p>Without an actual code sample to comment on, it's difficult to provide an informed alternative to the loops and switch statements you're currently using. But since you mention that you're setting a CommandText property, I would recommend the use of string.Format in your implementation (if you aren't already using it). I think it may make your code easier to restructure, and therefore improve readability and understanding.</p>\n" }, { "answer_id": 51938, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Usually it's something like this:</p>\n\n<pre><code>string query= \"SELECT {0} FROM .... WHERE {1}\"\nStringBuilder selectclause = new StringBuilder();\nStringBuilder wherecaluse = new StringBuilder();\n\n// .... the logic here will vary greatly depending on what your system looks like\n\nMySqlcommand.CommandText = String.Format(query, selectclause.ToString(), whereclause.ToString());\n</code></pre>\n\n<p>I'm also just getting started out with ORMs. You might want to take a look at one of those. ActiveRecord / Hibernate are some good keywords to google.</p>\n" }, { "answer_id": 51970, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM</a>s have already solved the problem of dynamic SQL generation (I prefer <a href=\"http://www.hibernate.org/343.html\" rel=\"nofollow noreferrer\">NHibernate</a>/<a href=\"http://www.castleproject.org/activerecord/index.html\" rel=\"nofollow noreferrer\">ActiveRecord</a>). Using these tools you can create a query with an unknown number of conditions by looping across user input and generating an array of Expression objects. Then execute the built-in query methods with that custom expression set.</p>\n\n<pre><code>List&lt;Expression&gt; expressions = new List&lt;Expression&gt;(userConditions.Count);\nforeach(Condition c in userConditions)\n{\n expressions.Add(Expression.Eq(c.Field, c.Value));\n}\nSomeTable[] records = SomeTable.Find(expressions);\n</code></pre>\n\n<p>There are more 'Expression' options: non-equality, greater/less than, null/not-null, etc. The 'Condition' type I just made up, you can probably stuff your user input into a useful class.</p>\n" }, { "answer_id": 52100, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>If you really need to do this from code, then an ORM is probably the way to go to try to keep it clean.</p>\n\n<p>But I'd like to offer an alternative that works well and could avoid the performance problems that accompany dynamic queries, due to changing SQL that requires new query plans to be created, with different demands on indexes.</p>\n\n<p>Create a stored procedure that accepts all possible parameters, and then use something like this in the where clause:</p>\n\n<pre><code>where...\nand (@MyParam5 is null or @MyParam5 = Col5)\n</code></pre>\n\n<p>then, from code, it's much simpler to set the parameter value to DBNull.Value when it is not applicable, rather than changing the SQL string you generate.</p>\n\n<p>Your DBAs will be much happier with you, because they will have one place to go for query tuning, the SQL will be easy to read, and they won't have to dig through profiler traces to find the many different queries being generated by your code.</p>\n" }, { "answer_id": 52119, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 2, "selected": false, "text": "<p>We created our own FilterCriteria object that is kind of a <em>black-box</em> dynamic query builder. It has collection properties for SelectClause, WhereClause, GroupByClause and OrderByClause. It also contains a properties for CommandText, CommandType, and MaximumRecords.</p>\n\n<p>We then jut pass our FilterCriteria object to our data logic and it executes it against the database server and passes parameter values to a stored procedure that executes the dynamic code. </p>\n\n<p>Works well for us ... and keeps the SQL generation nicely contained in an object.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197/" ]
I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object. I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built. Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore. Is there a cleaner, more stable way of doing this? Any Suggestions? EDIT: To add detail to my previous post: 1. I cannot really template my query due to the requirements. It just changes too much. 2. I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by 3. Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax]. 4. I am using an efficient paging technique that uses Row\_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query. I will show some code (the horror!) so that you guys have an idea of what I'm dealing with. ``` sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare + ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible + "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " " + sortDirection + ") as ROWRANK" // generates a rowrank for each row + outerFields + " FROM ( SELECT c.id AS ContactID" + coreFields + from // sometimes different tables are required + where + ") T " // user input goes here. + groupBy+ " " + havingClause //can be empty + ";" + "select @@rowcount as rCount;" // return 2 recordsets, avoids second query + " SELECT " + fields + ",field1,field2" // join onto the other cols n the table +" FROM @t t INNER JOIN contacts c on t.ContactID = c.id" +" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND " + ( (pageIndex + 1) * pageSize); // here I select the pages I want ``` In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so: ``` // Add Parameter to SQL Command AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue); // Create SQL code Fragment where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z); ```
I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL: * Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query. * The last five classes are all related to a Query object. So the Query object itself has collections of each class. * Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don't think that there are any big switch statements). And don't forget to use StringBuilder.
51,837
<p>I have up to 4 files based on this structure (note the prefixes are dates)</p> <ul> <li>0830filename.txt</li> <li>0907filename.txt</li> <li>0914filename.txt</li> <li>0921filename.txt</li> </ul> <p>I want to open the the most recent one (0921filename.txt). how can i do this in a batch file?</p> <p>Thanks.</p>
[ { "answer_id": 51861, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": -1, "selected": false, "text": "<p>Use regular expression to parse the relevant integer out and compare them.</p>\n" }, { "answer_id": 51868, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 1, "selected": false, "text": "<p>Here you go... (hope no-one beat me to it...) (You'll need to save the file as lasttext.bat or something) \nThis will open up / run the oldest .txt file</p>\n\n<pre><code>dir *.txt /b /od &gt; systext.bak \nFOR /F %%i in (systext.bak) do set sysRunCommand=%%i \ncall %sysRunCommand%\ndel systext.bak /Y\n</code></pre>\n\n<p>Probably XP only. BEHOLD The mighty power of DOS.<br>\nAlthough this takes the latest filename by date - NOT by filename..</p>\n\n<p>If you want to get the latest filename, change /od to /on .<br>\nIf you want to sort on something else, add a \"sort\" command to the second line. </p>\n" }, { "answer_id": 51875, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 4, "selected": true, "text": "<p>This method uses the actual file modification date, to figure out which one is the latest file:</p>\n\n<pre><code>@echo off\nfor /F %%i in ('dir /B /O:-D *.txt') do (\n call :open \"%%i\"\n exit /B 0\n)\n:open\n start \"dummy\" \"%~1\"\nexit /B 0\n</code></pre>\n\n<p>This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work:</p>\n\n<pre><code>@echo off\nfor /F %%i in ('dir /B *.txt^|sort /R') do (\n call :open \"%%i\"\n exit /B 0\n)\n:open\n start \"dummy\" \"%~1\"\nexit /B 0\n</code></pre>\n\n<p>You actually have to choose which method is better for you.</p>\n" }, { "answer_id": 51906, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "<p>One liner, using EXIT trick:</p>\n\n<pre><code>FOR /F %%I IN ('DIR *.TXT /B /O:-D') DO NOTEPAD %%I &amp; EXIT\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>@pam: you're right, I was assuming that the files were in date order, but you can change the command to:</p>\n\n<pre><code>FOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I &amp; EXIT\n</code></pre>\n\n<p>then you have the file list sorted by name in reverse order.</p>\n" }, { "answer_id": 51922, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 3, "selected": false, "text": "<p>Sorry, for spamming this question, but I just really feel like posting <strong>The Real Answer</strong>.\nIf you want your BATCH script to <em>parse</em> and <em>compare</em> the dates in filenames, then you can use something like this:</p>\n\n<pre><code>@echo off\n\nrem Enter the ending of the filenames.\nrem Basically, you must specify everything that comes after the date.\nset fn_end=filename.txt\n\nrem Do not touch anything bellow this line.\nset max_month=00\nset max_day=00\n\nfor /F %%i in ('dir /B *%fn_end%') do call :check \"%%i\"\ncall :open %max_month% %max_day%\nexit /B 0\n\n:check\n set name=%~1\n set date=%name:~0,4%\n set month=%date:~0,2%\n set day=%date:~2,2%\n if /I %month% GTR %max_month% (\n set max_month=%month%\n set max_day=%day%\n ) else if /I %month% EQU %max_month% (\n set max_month=%month%\n if /I %day% GTR %max_day% (\n set max_day=%day%\n )\n )\nexit /B 0\n\n:open\n set date=%~1\n set month=%~2\n set name=%date%%month%%fn_end%\n start \"dummy\" \"%name%\"\nexit /B 0\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I have up to 4 files based on this structure (note the prefixes are dates) * 0830filename.txt * 0907filename.txt * 0914filename.txt * 0921filename.txt I want to open the the most recent one (0921filename.txt). how can i do this in a batch file? Thanks.
This method uses the actual file modification date, to figure out which one is the latest file: ``` @echo off for /F %%i in ('dir /B /O:-D *.txt') do ( call :open "%%i" exit /B 0 ) :open start "dummy" "%~1" exit /B 0 ``` This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work: ``` @echo off for /F %%i in ('dir /B *.txt^|sort /R') do ( call :open "%%i" exit /B 0 ) :open start "dummy" "%~1" exit /B 0 ``` You actually have to choose which method is better for you.
51,927
<p>How do I figure out if an array contains an element? I thought there might be something like <code>[1, 2, 3].includes(1)</code> which would evaluate as <code>true</code>.</p>
[ { "answer_id": 51951, "author": "banderson623", "author_id": 5419, "author_profile": "https://Stackoverflow.com/users/5419", "pm_score": 6, "selected": false, "text": "<p>For lists, use <code>contains</code>:</p>\n\n<pre><code>[1,2,3].contains(1) == true\n</code></pre>\n" }, { "answer_id": 62082, "author": "dahernan", "author_id": 6435, "author_profile": "https://Stackoverflow.com/users/6435", "pm_score": 8, "selected": false, "text": "<p>Some syntax sugar</p>\n\n<pre><code>1 in [1,2,3]\n</code></pre>\n" }, { "answer_id": 66753, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 8, "selected": true, "text": "<p>.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()</p>\n\n<pre><code>[a:1,b:2,c:3].containsValue(3)\n[a:1,b:2,c:3].containsKey('a')\n</code></pre>\n" }, { "answer_id": 163883, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 3, "selected": false, "text": "<p>If you really want your includes method on an ArrayList, just add it:</p>\n\n<pre><code>ArrayList.metaClass.includes = { i -&gt; i in delegate }\n</code></pre>\n" }, { "answer_id": 27724859, "author": "Twelve24", "author_id": 1513628, "author_profile": "https://Stackoverflow.com/users/1513628", "pm_score": 2, "selected": false, "text": "<p>IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...</p>\n\n<pre><code>import groovy.transform.EqualsAndHashCode\n@EqualsAndHashCode(includes = \"settingNameId, value\")\n</code></pre>\n\n<p>then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.</p>\n" }, { "answer_id": 39934815, "author": "HinataXV", "author_id": 6942112, "author_profile": "https://Stackoverflow.com/users/6942112", "pm_score": 2, "selected": false, "text": "<pre><code>def fruitBag = [\"orange\",\"banana\",\"coconut\"]\ndef fruit = fruitBag.collect{item -&gt; item.contains('n')}\n</code></pre>\n\n<p>I did it like this so it works if someone is looking for it.</p>\n" }, { "answer_id": 59853867, "author": "MagGGG", "author_id": 1726413, "author_profile": "https://Stackoverflow.com/users/1726413", "pm_score": 3, "selected": false, "text": "<p>You can use Membership operator:</p>\n\n<pre><code>def list = ['Grace','Rob','Emmy']\nassert ('Emmy' in list) \n</code></pre>\n\n<p><a href=\"https://docs.groovy-lang.org/latest/html/documentation/#_membership_operator\" rel=\"noreferrer\">Membership operator Groovy</a></p>\n" }, { "answer_id": 62537459, "author": "ninj", "author_id": 7760893, "author_profile": "https://Stackoverflow.com/users/7760893", "pm_score": 0, "selected": false, "text": "<p>You can also use matches with regular expression like this:</p>\n<pre><code>boolean bool = List.matches(&quot;(?i).*SOME STRING HERE.*&quot;)\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5419/" ]
How do I figure out if an array contains an element? I thought there might be something like `[1, 2, 3].includes(1)` which would evaluate as `true`.
.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue() ``` [a:1,b:2,c:3].containsValue(3) [a:1,b:2,c:3].containsKey('a') ```
51,931
<p>I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows.</p> <blockquote> <p>error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument</p> </blockquote> <p>The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas?</p>
[ { "answer_id": 51951, "author": "banderson623", "author_id": 5419, "author_profile": "https://Stackoverflow.com/users/5419", "pm_score": 6, "selected": false, "text": "<p>For lists, use <code>contains</code>:</p>\n\n<pre><code>[1,2,3].contains(1) == true\n</code></pre>\n" }, { "answer_id": 62082, "author": "dahernan", "author_id": 6435, "author_profile": "https://Stackoverflow.com/users/6435", "pm_score": 8, "selected": false, "text": "<p>Some syntax sugar</p>\n\n<pre><code>1 in [1,2,3]\n</code></pre>\n" }, { "answer_id": 66753, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 8, "selected": true, "text": "<p>.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()</p>\n\n<pre><code>[a:1,b:2,c:3].containsValue(3)\n[a:1,b:2,c:3].containsKey('a')\n</code></pre>\n" }, { "answer_id": 163883, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 3, "selected": false, "text": "<p>If you really want your includes method on an ArrayList, just add it:</p>\n\n<pre><code>ArrayList.metaClass.includes = { i -&gt; i in delegate }\n</code></pre>\n" }, { "answer_id": 27724859, "author": "Twelve24", "author_id": 1513628, "author_profile": "https://Stackoverflow.com/users/1513628", "pm_score": 2, "selected": false, "text": "<p>IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...</p>\n\n<pre><code>import groovy.transform.EqualsAndHashCode\n@EqualsAndHashCode(includes = \"settingNameId, value\")\n</code></pre>\n\n<p>then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.</p>\n" }, { "answer_id": 39934815, "author": "HinataXV", "author_id": 6942112, "author_profile": "https://Stackoverflow.com/users/6942112", "pm_score": 2, "selected": false, "text": "<pre><code>def fruitBag = [\"orange\",\"banana\",\"coconut\"]\ndef fruit = fruitBag.collect{item -&gt; item.contains('n')}\n</code></pre>\n\n<p>I did it like this so it works if someone is looking for it.</p>\n" }, { "answer_id": 59853867, "author": "MagGGG", "author_id": 1726413, "author_profile": "https://Stackoverflow.com/users/1726413", "pm_score": 3, "selected": false, "text": "<p>You can use Membership operator:</p>\n\n<pre><code>def list = ['Grace','Rob','Emmy']\nassert ('Emmy' in list) \n</code></pre>\n\n<p><a href=\"https://docs.groovy-lang.org/latest/html/documentation/#_membership_operator\" rel=\"noreferrer\">Membership operator Groovy</a></p>\n" }, { "answer_id": 62537459, "author": "ninj", "author_id": 7760893, "author_profile": "https://Stackoverflow.com/users/7760893", "pm_score": 0, "selected": false, "text": "<p>You can also use matches with regular expression like this:</p>\n<pre><code>boolean bool = List.matches(&quot;(?i).*SOME STRING HERE.*&quot;)\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows. > > error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument > > > The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas?
.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue() ``` [a:1,b:2,c:3].containsValue(3) [a:1,b:2,c:3].containsKey('a') ```
51,941
<p>I have created a database report generator in Excel. I am trying to create a dialog box that displays status information as the program runs.</p> <p>When I generate the report, although the dialog box appears, I cannot refresh/update the information it displays. Most of the time, the dialog box only partially appears. I have tried using the .repaint method, but I still get the same results. I only see the complete dialog box, after the report is generated.</p>
[ { "answer_id": 51946, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 0, "selected": false, "text": "<p>The dialog box is also running on the same UI thread. So, it is too busy to repaint itself. Not sure if VBA has good multi-threading capabilities.</p>\n" }, { "answer_id": 51953, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 3, "selected": false, "text": "<p>I have used Excel's own status bar (in bottom left of window) to display progress information for a similar application I developed in the past.</p>\n\n<p>It works out very well if you just want to display textual updates on progress, and avoids the need for an updating dialog at all.</p>\n\n<p>Ok @JonnyGold, here's an example of the kind of thing I used...</p>\n\n<pre><code>Sub StatusBarExample()\n Application.ScreenUpdating = False \n ' turns off screen updating\n Application.DisplayStatusBar = True \n ' makes sure that the statusbar is visible\n Application.StatusBar = \"Please wait while performing task 1...\"\n ' add some code for task 1 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = \"Please wait while performing task 2...\"\n ' add some code for task 2 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = False \n ' gives control of the statusbar back to the programme\nEnd Sub\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 51957, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>Try adding a <strong>DoEvents</strong> call in your loop. That should allow the form to repaint &amp; accept other requests.</p>\n" }, { "answer_id": 91978, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 3, "selected": true, "text": "<p>The code below works well when performing actions within Excel (XP or later).</p>\n\n<p>For actions that take place outside Excel, for example connecting to a database and retrieving data the best this offers is the opportunity to show dialogs before and after the action (e.g. <em>\"Getting data\"</em>, <em>\"Got data\"</em>)</p>\n\n<p>Create a form called <strong>\"frmStatus\"</strong>, put a label on the form called <strong>\"Label1\"</strong>.</p>\n\n<p>Set the form property <strong>'ShowModal' = false</strong>, this allows the code to run while the form is displayed.</p>\n\n<pre><code>Sub ShowForm_DoSomething()\n\n Load frmStatus\n frmStatus.Label1.Caption = \"Starting\"\n frmStatus.Show\n frmStatus.Repaint\n'Load the form and set text\n\n frmStatus.Label1.Caption = \"Doing something\"\n frmStatus.Repaint\n\n'code here to perform an action\n\n frmStatus.Label1.Caption = \"Doing something else\"\n frmStatus.Repaint\n\n'code here to perform an action\n\n frmStatus.Label1.Caption = \"Finished\"\n frmStatus.Repaint\n Application.Wait (Now + TimeValue(\"0:00:01\"))\n frmStatus.Hide\n Unload frmStatus\n'hide and unload the form\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 17247251, "author": "Richard Knott", "author_id": 2510909, "author_profile": "https://Stackoverflow.com/users/2510909", "pm_score": 2, "selected": false, "text": "<p>Insert a blank sheet in your workbook\nRename the Sheet eg. \"information\"</p>\n\n<pre><code>Sheets(\"information\").Select\nRange(\"C3\").Select\nActiveCell.FormulaR1C1 = \"Updating Records\"\nApplication.ScreenUpdating = False\nApplication.Wait Now + TimeValue(\"00:00:02\")\n</code></pre>\n\n<p><em>Continue Macro</em></p>\n\n<pre><code>Sheets(\"information\").Select\nRange(\"C3\").Select\nApplication.ScreenUpdating = True\nActiveCell.FormulaR1C1 = \"Preparing Information\"\nApplication.ScreenUpdating = False\nApplication.Wait Now + TimeValue(\"00:00:02\")\n</code></pre>\n\n<p><em>Continue Macro</em></p>\n\n<p>Etc\nAlternatively select a blank cell somewhere on the existing sheet instead of inserting a new sheet</p>\n\n<pre><code>Range(\"C3\").Select\nActiveCell.FormulaR1C1 = \"Updating Records\"\nApplication.ScreenUpdating = False\nApplication.Wait Now + TimeValue(\"00:00:02\")\n</code></pre>\n\n<p>Etc</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ]
I have created a database report generator in Excel. I am trying to create a dialog box that displays status information as the program runs. When I generate the report, although the dialog box appears, I cannot refresh/update the information it displays. Most of the time, the dialog box only partially appears. I have tried using the .repaint method, but I still get the same results. I only see the complete dialog box, after the report is generated.
The code below works well when performing actions within Excel (XP or later). For actions that take place outside Excel, for example connecting to a database and retrieving data the best this offers is the opportunity to show dialogs before and after the action (e.g. *"Getting data"*, *"Got data"*) Create a form called **"frmStatus"**, put a label on the form called **"Label1"**. Set the form property **'ShowModal' = false**, this allows the code to run while the form is displayed. ``` Sub ShowForm_DoSomething() Load frmStatus frmStatus.Label1.Caption = "Starting" frmStatus.Show frmStatus.Repaint 'Load the form and set text frmStatus.Label1.Caption = "Doing something" frmStatus.Repaint 'code here to perform an action frmStatus.Label1.Caption = "Doing something else" frmStatus.Repaint 'code here to perform an action frmStatus.Label1.Caption = "Finished" frmStatus.Repaint Application.Wait (Now + TimeValue("0:00:01")) frmStatus.Hide Unload frmStatus 'hide and unload the form End Sub ```
51,950
<p>I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?</p>
[ { "answer_id": 51958, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.80).aspx\" rel=\"noreferrer\">InternalsVisibleTo</a> attribute to the rescue!</p>\n\n<p>Just add: </p>\n\n<pre><code>[assembly:InternalsVisibleToAttribute(\"UnitTestAssemblyName\")]\n</code></pre>\n\n<p>to your Core classes AssemblyInfo.cs file</p>\n\n<p>See <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies\" rel=\"noreferrer\">Friend Assemblies (C# Programming Guide)</a> for best practices.</p>\n" }, { "answer_id": 51960, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 2, "selected": false, "text": "<p>You can use reflection (as the MS Test items do), or you can declare the unit test assembly a friend of the core assembly.</p>\n\n<p>The other option is to put the unit tests in the same assembly.</p>\n" }, { "answer_id": 51986, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 4, "selected": false, "text": "<p>With InternalsVisible if your assemblies are strongly named you need to specify the public key (note: the full key <strong>not</strong> the public key token) for example...</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"BoardEx_BusinessObjects.Tests, \n PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb3a2d8 etc etc\")]\n</code></pre>\n\n<p>and the following trick is really useful for getting the public key without resorting to the cmd line...</p>\n\n<p><a href=\"http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx\" rel=\"noreferrer\">http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx</a></p>\n" }, { "answer_id": 52019, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 2, "selected": false, "text": "<p>I would suggest not going to such troubles ... if you really want to unit test your \"internal\" classes, just hide them away in a namespace that only your internal code would end up using. Unless you're writing a framework on the scale of the .NET framework, you don't <strong>really</strong> need that level of hiding.</p>\n" }, { "answer_id": 52200, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>I put my unit tests in the same assembly as the code that it's testing. This makes sense to me, because I think of \"test yourself\" as a feature of a class, along with things like \"initialize yourself\" and \"describe yourself\".</p>\n\n<p>I've heard some objections to this approach, but few of them have been convincing.</p>\n\n<p><strong>It hurts performance</strong> Bah, I say! Don't optimize without hard data! Perhaps if you are planning your assemblies to be downloaded over slow links, then minimizing assembly size would be worthwhile. </p>\n\n<p><strong>It's a security risk</strong>. Only if you have secrets in your tests. Don't do that.</p>\n\n<p>Now, your situation is different from mine, so maybe it'll make sense for you, and maybe it won't. You'll have to figure that out yourself.</p>\n\n<p>Aside: In C#, I once tried putting my unit tests in a class named \"Tests\" that was nested inside the class that it was testing. This made the correct organization of things obvious. It also avoided the duplication of names that occurs when tests for the class \"Foo\" are in a class called \"FooTests\". However, the unit testing frameworks that I had access to refused to accept tests that weren't marked \"public\". This means that the class that you're testing can't be \"private\". I can't think of any good reason to require tests to be \"public\", since no one really calls them as public methods - everything is through reflection. If you ever write a unit testing framework for .Net, please consider allowing non-public tests, for my sake!</p>\n" }, { "answer_id": 71554850, "author": "paraJdox1", "author_id": 11565087, "author_profile": "https://Stackoverflow.com/users/11565087", "pm_score": 0, "selected": false, "text": "<h2>Let's start with an example class:</h2>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Runtime.CompilerServices;\n\n[assembly: InternalsVisibleTo(&quot;App.Infrastructure.UnitTests&quot;)]\n\nnamespace App.Infrastructure.Data.Repositories\n{\n internal class UserRepository : IUserRepository\n {\n // internal members that you want to test/access\n }\n}\n</code></pre>\n<p>The <code>[assembly: InternalsVisibleTo(&quot;Input_The_Assembly_That_Can_Access_Your_Internals_Here&quot;)]</code> attribute allows <em>all</em> of your <strong>internal classes and members to be accessed by another assembly</strong>, but the <strong>InternalsVisibleTo</strong> attribute is not only applied to a single class (on where you declared it), rather on the <strong>WHOLE</strong> assembly itself.</p>\n<p>In the example code - <code>App.Infrastructure.UnitTests</code> can access all internals in the assembly that you declared (InternalsVisibleTo attribute) it even if you didn't explicitly declare it to other classes that belong to the same assembly.</p>\n<br>\n<h3><a href=\"https://youtu.be/noxNMji-DRw\" rel=\"nofollow noreferrer\">I found out in this youtube video:</a> That there are 2 approaches to make your internals accessible to certain assemblies (or assembly)</h3>\n<p><strong>1. Creating your own AssemblyInfo.cs file</strong></p>\n<p>These are the <strong>only</strong> lines you'll need in your AssemblyInfo.cs (delete all &quot;default&quot; code, and replace with the code below)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Runtime.CompilerServices;\n[assembly: InternalsVisibleTo(&quot;App.Infrastructure.UnitTests&quot;),\n InternalsVisibleTo(&quot;Another.Assembly&quot;)]\n</code></pre>\n<p><strong>2. Adding the InternalsVisibleTo attribute in the project's .csproj (double click the project that you want its internals to be exposed)</strong></p>\n<pre><code>&lt;ItemGroup&gt;\n &lt;AssemblyAttribute Include=&quot;System.Runtime.CompilerServices.InternalsVisibleTo&quot;&gt;\n &lt;_Parameter1&gt;The_Assembly_That_Can_Access_Your_Internals&lt;/_Parameter1&gt;\n &lt;/AssemblyAttribute&gt;\n \n &lt;AssemblyAttribute Include=&quot;System.Runtime.CompilerServices.InternalsVisibleTo&quot;&gt;\n &lt;_Parameter1&gt;Another_Assembly_Or_Project&lt;/_Parameter1&gt;\n &lt;/AssemblyAttribute&gt;\n&lt;/ItemGroup&gt;\n\n</code></pre>\n<p><strong>Note:</strong> <a href=\"https://youtu.be/noxNMji-DRw\" rel=\"nofollow noreferrer\">watch the whole youtube video for a more detailed explanation on Assembly-Level Attributes</a></p>\n" }, { "answer_id": 72820728, "author": "kewur", "author_id": 4695519, "author_profile": "https://Stackoverflow.com/users/4695519", "pm_score": 0, "selected": false, "text": "<p>in dotnet core we can add AssembyAttribute in the .csproj file</p>\n<p>just add this into your .csproj</p>\n<pre><code>&lt;!-- Make internals available for Unit Testing --&gt;\n&lt;ItemGroup&gt;\n &lt;AssemblyAttribute Include=&quot;System.Runtime.CompilerServices.InternalsVisibleTo&quot;&gt;\n &lt;_Parameter1&gt;Myproject.Tests&lt;/_Parameter1&gt;\n &lt;/AssemblyAttribute&gt;\n&lt;/ItemGroup&gt;\n&lt;!-- End Unit test Internals --&gt;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?
[InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.80).aspx) attribute to the rescue! Just add: ``` [assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")] ``` to your Core classes AssemblyInfo.cs file See [Friend Assemblies (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies) for best practices.
51,964
<p>In my base page I need to remove an item from the query string and redirect. I can't use<br/></p> <pre><code>Request.QueryString.Remove("foo") </code></pre> <p>because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?</p>
[ { "answer_id": 51981, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 2, "selected": false, "text": "<pre><code>Response.Redirect(String.Format(\"nextpage.aspx?{0}\", Request.QueryString.ToString().Replace(\"foo\", \"mangledfoo\")));\n</code></pre>\n\n<p>I quick hack, saves you little. But foo will not be present for the code awaiting it in nextpge.aspx :)</p>\n" }, { "answer_id": 51987, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": -1, "selected": false, "text": "<p>Can you clone the collection and then redirect to the page with the cloned (and modified) collection?</p>\n\n<p>I know it's not much better than iterating...</p>\n" }, { "answer_id": 51995, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 4, "selected": true, "text": "<p>You'd have to reconstruct the url and then redirect. Something like this:</p>\n\n<pre><code>string url = Request.RawUrl;\n\nNameValueCollection params = Request.QueryString;\nfor (int i=0; i&lt;params.Count; i++)\n{\n if (params[i].GetKey(i).ToLower() == \"foo\")\n {\n url += string.Concat((i==0 ? \"?\" : \"&amp;\"), params[i].GetKey(i), \"=\", params.Get(i));\n }\n}\nResponse.Redirect(url);\n</code></pre>\n\n<p>Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction)</p>\n" }, { "answer_id": 52004, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>Interesting question. I don't see any real viable alternative to manually copying the collection since <em>CopyTo</em> will only allow you to get the values (and not the keys).</p>\n<p>I think <a href=\"https://stackoverflow.com/questions/51964/how-do-i-remove-items-from-the-query-string-for-redirection#51981\">HollyStyles' Hack</a> would work (although I would be nervous about putting a Replace in a QueryString - obv. dependant on use case), but there is one thing thats bothering me..</p>\n<p><strong>If the target page is not reading it, why do you need to remove it from the QueryString?</strong></p>\n<p>It will just be ignored?</p>\n<p>Failing that, I think you would just need to bite the bullet and create a util method to alter the collection for you.</p>\n<h3>UPDATE - Following Response from OP</h3>\n<p>Ahhhh! I see now, yes, I have had similar problems with SiteMap performing full comparison of the string.</p>\n<p>Since changing the other source code (i.e. the search) is out of the question, I would probably say it may be best to do a Replace on the string. Although to be fair, if you often encounter code similar to this, it would equally be just as quick to set up a utility function to clone the collection, taking an array of values to filter from it.</p>\n<p>This way you would never have to worry about such issues again :)</p>\n" }, { "answer_id": 52128, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><strong>The search page appends \"&amp;terms=\" to the query string for highlighting, so\n it messes it up.</strong></p>\n</blockquote>\n\n<p>Only other option is a regex replace. If you <em>know for sure</em> that &amp;terms is in the middle of the collection somewhere leave the trailing &amp; in the regex, if you <em>know for sure</em> it's on the end then drop the trailing &amp; and change the replacement string \"&amp;\" to String.Empty</p>\n\n<pre><code>Response.Redirect(String.Format(\"nextpage.aspx?{0}\", Regex.Replace(Request.QueryString.ToString(), \"&amp;terms=.*&amp;\", \"&amp;\"));\n</code></pre>\n" }, { "answer_id": 1632995, "author": "Ziad", "author_id": 144227, "author_profile": "https://Stackoverflow.com/users/144227", "pm_score": 3, "selected": false, "text": "<p>You can avoid touching the original query string by working on a copy of it instead. You can then redirect the page to the a url containing your modified query string like so:</p>\n\n<pre><code> var nvc = new NameValueCollection();\n\n nvc.Add(HttpUtility.ParseQueryString(Request.Url.Query));\n\n nvc.Remove(\"foo\");\n\n string url = Request.Url.AbsolutePath;\n\n for (int i = 0; i &lt; nvc.Count; i++)\n url += string.Format(\"{0}{1}={2}\", (i == 0 ? \"?\" : \"&amp;\"), nvc.Keys[i], nvc[i]);\n\n Response.Redirect(url);\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>Turns out we can simplify the code like so:</p>\n\n<pre><code> var nvc = HttpUtility.ParseQueryString(Request.Url.Query);\n\n nvc.Remove(\"foo\");\n\n string url = Request.Url.AbsolutePath + \"?\" + nvc.ToString();\n\n Response.Redirect(url);\n</code></pre>\n" }, { "answer_id": 8169154, "author": "alex1kirch", "author_id": 991442, "author_profile": "https://Stackoverflow.com/users/991442", "pm_score": 2, "selected": false, "text": "<p><code>HttpUtility.ParseQueryString(Request.Url.Query)</code> return is<code>QueryStringValueCollection</code>. It is inherit from <code>NameValueCollection</code>.</p>\n\n<pre><code> var qs = HttpUtility.ParseQueryString(Request.Url.Query);\n qs.Remove(\"foo\"); \n\n string url = \"~/Default.aspx\"; \n if (qs.Count &gt; 0)\n url = url + \"?\" + qs.ToString();\n\n Response.Redirect(url); \n</code></pre>\n" }, { "answer_id": 8919043, "author": "Answer", "author_id": 1157369, "author_profile": "https://Stackoverflow.com/users/1157369", "pm_score": 0, "selected": false, "text": "<p><code>Request.Url.GetLeftPart(UriPartial.Path)</code> should do this</p>\n" }, { "answer_id": 10412157, "author": "Chris", "author_id": 94278, "author_profile": "https://Stackoverflow.com/users/94278", "pm_score": 0, "selected": false, "text": "<p>I found this was a more elegant solution</p>\n\n<pre><code>var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());\nqs.Remove(\"item\");\nConsole.WriteLine(qs.ToString());\n</code></pre>\n" }, { "answer_id": 16279198, "author": "biofractal", "author_id": 776476, "author_profile": "https://Stackoverflow.com/users/776476", "pm_score": 0, "selected": false, "text": "<p>Here is a solution that uses LINQ against the <code>Request.QueryString</code> which allows for complex filtering of qs params if required. </p>\n\n<p>The example below shows me filtering out the <code>uid</code> param to create a relative url ready for redirection.</p>\n\n<p>Before: <code>http://www.domain.com/home.aspx?color=red&amp;uid=1&amp;name=bob</code></p>\n\n<p>After: <code>~/home.aspx?color=red&amp;name=bob</code></p>\n\n<p><strong>Remove QS param from url</strong></p>\n\n<pre><code>var rq = this.Request.QueryString;\nvar qs = string.Join(\"&amp;\", rq.Cast&lt;string&gt;().Where(k =&gt; k != \"uid\").Select(k =&gt; string.Format(\"{0}={1}\", k, rq[k])).ToArray());\nvar url = string.Concat(\"~\", Request.RawUrl.Split('?')[0], \"?\", qs);\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
In my base page I need to remove an item from the query string and redirect. I can't use ``` Request.QueryString.Remove("foo") ``` because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?
You'd have to reconstruct the url and then redirect. Something like this: ``` string url = Request.RawUrl; NameValueCollection params = Request.QueryString; for (int i=0; i<params.Count; i++) { if (params[i].GetKey(i).ToLower() == "foo") { url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i)); } } Response.Redirect(url); ``` Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction)
51,969
<p>In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command <code>ALTER DATABASE &lt;database&gt; SET READ_COMMITTED_SNAPSHOT ON;</code>?</p> <p>I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.</p>
[ { "answer_id": 51977, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 9, "selected": true, "text": "<pre><code>SELECT is_read_committed_snapshot_on FROM sys.databases \nWHERE name= 'YourDatabase'\n</code></pre>\n<p>Return value:</p>\n<ul>\n<li><strong>1</strong>: <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>ON</strong>. Read operations under the <code>READ COMMITTED</code> isolation level are based on snapshot scans and do not acquire locks.</li>\n<li><strong>0</strong> (default): <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>OFF</strong>. Read operations under the <code>READ COMMITTED</code> isolation level use <a href=\"https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)\" rel=\"noreferrer\">Shared (S) locks</a>.</li>\n</ul>\n" }, { "answer_id": 20942633, "author": "user3164106", "author_id": 3164106, "author_profile": "https://Stackoverflow.com/users/3164106", "pm_score": 0, "selected": false, "text": "<p>Neither on SQL2005 nor 2012 does <code>DBCC USEROPTIONS</code> show <code>is_read_committed_snapshot_on</code>:</p>\n\n<pre><code>Set Option Value\ntextsize 2147483647\nlanguage us_english\ndateformat mdy\ndatefirst 7\nlock_timeout -1\nquoted_identifier SET\narithabort SET\nansi_null_dflt_on SET\nansi_warnings SET\nansi_padding SET\nansi_nulls SET\nconcat_null_yields_null SET\nisolation level read committed\n</code></pre>\n" }, { "answer_id": 38287052, "author": "MikeL", "author_id": 6569861, "author_profile": "https://Stackoverflow.com/users/6569861", "pm_score": 2, "selected": false, "text": "<ol>\n<li>As per <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql\" rel=\"nofollow noreferrer\">DBCC USEROPTIONS (Transact-SQL)</a>:</li>\n</ol>\n<blockquote>\n<p>DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed.</p>\n</blockquote>\n<ol start=\"2\">\n<li>Also in SQL Server Management Studio, in database properties under Options-&gt;Miscellaneous there is &quot;Is Read Committed Snapshot On&quot; option status</li>\n</ol>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5217/" ]
In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command `ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;`? I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.
``` SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name= 'YourDatabase' ``` Return value: * **1**: `READ_COMMITTED_SNAPSHOT` option is **ON**. Read operations under the `READ COMMITTED` isolation level are based on snapshot scans and do not acquire locks. * **0** (default): `READ_COMMITTED_SNAPSHOT` option is **OFF**. Read operations under the `READ COMMITTED` isolation level use [Shared (S) locks](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)).
52,002
<p><strong>Definition:</strong></p> <p><em>A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction</em></p> <p>How to check if the given string is a palindrome?</p> <p>This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.</p> <p>Looking for solutions in any and all languages possible.</p>
[ { "answer_id": 52013, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 2, "selected": false, "text": "<pre><code>boolean isPalindrome(String str1) {\n //first strip out punctuation and spaces\n String stripped = str1.replaceAll(\"[^a-zA-Z0-9]\", \"\");\n return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());\n}\n</code></pre>\n\n<p>Java version</p>\n" }, { "answer_id": 52014, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 5, "selected": false, "text": "<p>Language agnostic meta-code then...</p>\n\n<pre><code>rev = StringReverse(originalString)\nreturn ( rev == originalString );\n</code></pre>\n" }, { "answer_id": 52015, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 2, "selected": false, "text": "<p>Here's my solution in c#</p>\n\n<pre><code>static bool isPalindrome(string s)\n{\n string allowedChars = \"abcdefghijklmnopqrstuvwxyz\"+\n \"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string compareString = String.Empty;\n string rev = string.Empty;\n\n for (int i = 0; i &lt;= s.Length - 1; i++)\n {\n char c = s[i];\n\n if (allowedChars.IndexOf(c) &gt; -1)\n {\n compareString += c;\n }\n }\n\n\n for (int i = compareString.Length - 1; i &gt;= 0; i--)\n {\n char c = compareString[i];\n rev += c;\n }\n\n return rev.Equals(compareString, \n StringComparison.CurrentCultureIgnoreCase);\n}\n</code></pre>\n" }, { "answer_id": 52021, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "<pre><code>Delphi\n\nfunction IsPalindrome(const s: string): boolean;\nvar\n i, j: integer;\nbegin\n Result := false;\n j := Length(s);\n for i := 1 to Length(s) div 2 do begin\n if s[i] &lt;&gt; s[j] then\n Exit;\n Dec(j);\n end;\n Result := true;\nend;\n</code></pre>\n" }, { "answer_id": 52023, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>Unoptimized Python:</p>\n\n<pre><code>&gt;&gt;&gt; def is_palindrome(s):\n... return s == s[::-1]\n</code></pre>\n" }, { "answer_id": 52028, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "<p>Here's a python way. Note: this isn't really that \"pythonic\" but it demonstrates the algorithm.</p>\n\n<pre><code>def IsPalindromeString(n):\n myLen = len(n)\n i = 0\n while i &lt;= myLen/2:\n if n[i] != n[myLen-1-i]:\n return False\n i += 1\n return True\n</code></pre>\n" }, { "answer_id": 52031, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 5, "selected": false, "text": "<p>Windows XP (might also work on 2000) or later BATCH script:</p>\n\n<pre><code>@echo off\n\ncall :is_palindrome %1\nif %ERRORLEVEL% == 0 (\n echo %1 is a palindrome\n) else (\n echo %1 is NOT a palindrome\n)\nexit /B 0\n\n:is_palindrome\n set word=%~1\n set reverse=\n call :reverse_chars \"%word%\"\n set return=1\n if \"$%word%\" == \"$%reverse%\" (\n set return=0\n )\nexit /B %return%\n\n:reverse_chars\n set chars=%~1\n set reverse=%chars:~0,1%%reverse%\n set chars=%chars:~1%\n if \"$%chars%\" == \"$\" (\n exit /B 0\n ) else (\n call :reverse_chars \"%chars%\"\n )\nexit /B 0\n</code></pre>\n" }, { "answer_id": 52034, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p>C#: LINQ</p>\n\n<pre><code>var str = \"a b a\";\nvar test = Enumerable.SequenceEqual(str.ToCharArray(), \n str.ToCharArray().Reverse());\n</code></pre>\n" }, { "answer_id": 52036, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 1, "selected": false, "text": "<p>Many ways to do it. I guess the key is to do it in the most efficient way possible (without looping the string). I would do it as a char array which can be reversed easily (using C#).</p>\n\n<pre><code>string mystring = \"abracadabra\";\n\nchar[] str = mystring.ToCharArray();\nArray.Reverse(str);\nstring revstring = new string(str);\n\nif (mystring.equals(revstring))\n{\n Console.WriteLine(\"String is a Palindrome\");\n}\n</code></pre>\n" }, { "answer_id": 52038, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "<p><strong>C#</strong> in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function.</p>\n\n<pre><code>boolean IsPalindrome(string s) {\n for (int i = 0; i &lt; s.Length / 2; i++)\n {\n if (s[i] != s[s.Length - 1 - i]) return false;\n }\n return true;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> removed unnecessary \"<code>+1</code>\" in loop condition and spent the saved comparison on removing the redundant Length comparison. Thanks to the commenters!</p>\n" }, { "answer_id": 52039, "author": "xanadont", "author_id": 1886, "author_profile": "https://Stackoverflow.com/users/1886", "pm_score": 3, "selected": false, "text": "<p>Using a good data structure usually helps impress the professor:</p>\n\n<p>Push half the chars onto a stack (Length / 2).<br />\nPop and compare each char until the first unmatch.<br />\nIf the stack has zero elements: palindrome.<br />\n*in the case of a string with an odd Length, throw out the middle char.</p>\n" }, { "answer_id": 52040, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Here's my solution, without using a strrev. Written in C#, but it will work in any language that has a string length function.</p>\n\n<pre><code>private static bool Pal(string s) {\n for (int i = 0; i &lt; s.Length; i++) {\n if (s[i] != s[s.Length - 1 - i]) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52041, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 2, "selected": false, "text": "<p>This Java code should work inside a <strong>boolean</strong> method:</p>\n\n<p><strong>Note</strong>: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made.</p>\n\n<pre><code>private static boolean doPal(String test) {\n for(int i = 0; i &lt; test.length() / 2; i++) {\n if(test.charAt(i) != test.charAt(test.length() - 1 - i)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52048, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 4, "selected": false, "text": "<p>Java solution:</p>\n\n<pre><code>public class QuickTest {\n\npublic static void main(String[] args) {\n check(\"AmanaplanacanalPanama\".toLowerCase());\n check(\"Hello World\".toLowerCase());\n}\n\npublic static void check(String aString) {\n System.out.print(aString + \": \");\n char[] chars = aString.toCharArray();\n for (int i = 0, j = (chars.length - 1); i &lt; (chars.length / 2); i++, j--) {\n if (chars[i] != chars[j]) {\n System.out.println(\"Not a palindrome!\");\n return;\n }\n }\n System.out.println(\"Found a palindrome!\");\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 52051, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": false, "text": "<p><strong>PHP sample</strong>:</p>\n\n<pre><code>$string = \"A man, a plan, a canal, Panama\";\n\nfunction is_palindrome($string)\n{\n $a = strtolower(preg_replace(\"/[^A-Za-z0-9]/\",\"\",$string));\n return $a==strrev($a);\n}\n</code></pre>\n\n<p>Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.</p>\n" }, { "answer_id": 52053, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 3, "selected": false, "text": "<p>EDIT: from the comments:</p>\n\n<pre><code>bool palindrome(std::string const&amp; s) \n{ \n return std::equal(s.begin(), s.end(), s.rbegin()); \n} \n</code></pre>\n\n<hr>\n\n<p>The c++ way.</p>\n\n<p>My naive implementation using the elegant iterators. In reality, you would probably check\nand stop once your forward iterator has past the halfway mark to your string.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\nbool palindrome(string foo)\n{\n string::iterator front;\n string::reverse_iterator back;\n bool is_palindrome = true;\n for(front = foo.begin(), back = foo.rbegin();\n is_palindrome &amp;&amp; front!= foo.end() &amp;&amp; back != foo.rend();\n ++front, ++back\n )\n {\n if(*front != *back)\n is_palindrome = false;\n }\n return is_palindrome;\n}\nint main()\n{\n string a = \"hi there\", b = \"laval\";\n\n cout &lt;&lt; \"String a: \\\"\" &lt;&lt; a &lt;&lt; \"\\\" is \" &lt;&lt; ((palindrome(a))? \"\" : \"not \") &lt;&lt; \"a palindrome.\" &lt;&lt;endl;\n cout &lt;&lt; \"String b: \\\"\" &lt;&lt; b &lt;&lt; \"\\\" is \" &lt;&lt; ((palindrome(b))? \"\" : \"not \") &lt;&lt; \"a palindrome.\" &lt;&lt;endl;\n\n}\n</code></pre>\n" }, { "answer_id": 52057, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.</p>\n\n<p><em>Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.</em></p>\n\n<pre><code>function TForm1.IsPalindrome(txt: string): boolean;\nvar\n i, halfway, len : integer;\nbegin\n Result := True;\n len := Length(txt);\n\n {\n special cases:\n an empty string is *never* a palindrome\n a 1-character string is *always* a palindrome\n }\n case len of\n 0 : Result := False;\n 1 : Result := True;\n else begin\n halfway := Round((len/2) - (1/2)); //if odd, round down to get 1/2way pt\n\n //scan half of our string, make sure it is mirrored on the other half\n for i := 1 to halfway do begin\n if txt[i] &lt;&gt; txt[len-(i-1)] then begin\n Result := False;\n Break;\n end; //if we found a non-mirrored character\n end; //for 1st half of string\n end; //else not a special case\n end; //case\nend;\n</code></pre>\n\n<p>And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.</p>\n\n<pre><code>private bool IsPalindrome(string txt) {\n int len = txt.Length;\n\n /*\n Special cases:\n An empty string is *never* a palindrome\n A 1-character string is *always* a palindrome\n */ \n switch (len) {\n case 0: return false;\n case 1: return true;\n } //switch\n int halfway = (len / 2);\n\n //scan half of our string, make sure it is mirrored on the other half\n for (int i = 0; i &lt; halfway; ++i) {\n if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {\n return false;\n } //if\n } //for\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52063, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>C#3 - This returns false as soon as a char counted from the beginning fails to match its equivalent at the end:</p>\n\n<pre><code>static bool IsPalindrome(this string input)\n{\n char[] letters = input.ToUpper().ToCharArray();\n\n int i = 0;\n while( i &lt; letters.Length / 2 )\n if( letters[i] != letters[letters.Length - ++i] )\n return false;\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52064, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p>Here's a Python version that deals with different cases, punctuation and whitespace.</p>\n\n<pre><code>import string\n\ndef is_palindrome(palindrome):\n letters = palindrome.translate(string.maketrans(\"\",\"\"),\n string.whitespace + string.punctuation).lower()\n return letters == letters[::-1]\n</code></pre>\n\n<p><strong>Edit:</strong> Shamelessly stole from <a href=\"https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52023\">Blair Conrad's</a> neater answer to remove the slightly clumsy list processing from my previous version. </p>\n" }, { "answer_id": 52138, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "<p>Three versions in Smalltalk, from dumbest to correct.</p>\n\n<hr>\n\n<p>In Smalltalk, <code>=</code> is the comparison operator:</p>\n\n<pre><code>isPalindrome: aString\n \"Dumbest.\"\n ^ aString reverse = aString\n</code></pre>\n\n<hr>\n\n<p>The message <code>#translateToLowercase</code> returns the string as lowercase:</p>\n\n<pre><code>isPalindrome: aString\n \"Case insensitive\"\n |lowercase|\n lowercase := aString translateToLowercase.\n ^ lowercase reverse = lowercase\n</code></pre>\n\n<hr>\n\n<p>And in Smalltalk, strings are part of the <code>Collection</code> framework, you can use the message <code>#select:thenCollect:</code>, so here's the last version:</p>\n\n<pre><code>isPalindrome: aString\n \"Case insensitive and keeping only alphabetic chars\n (blanks &amp; punctuation insensitive).\"\n |lowercaseLetters|\n lowercaseLetters := aString\n select: [:char | char isAlphabetic]\n thenCollect: [:char | char asLowercase]. \n ^ lowercaseLetters reverse = lowercaseLetters\n</code></pre>\n" }, { "answer_id": 52153, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Another C++ one. Optimized for speed and size.</p>\n\n<p><code><pre>bool is_palindrome(const std::string&amp; candidate) {\n for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left &lt; --right ; ++left)\n if (*left != *right)\n return false;\n return true;\n}</pre></code></p>\n" }, { "answer_id": 52328, "author": "kranzky", "author_id": 5442, "author_profile": "https://Stackoverflow.com/users/5442", "pm_score": 1, "selected": false, "text": "<p>In Ruby, converting to lowercase and stripping everything not alphabetic:</p>\n\n<pre><code>def isPalindrome( string )\n ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse\nend\n</code></pre>\n\n<p>But that feels like cheating, right? No pointers or anything! So here's a C version too, but without the lowercase and character stripping goodness:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint isPalindrome( char * string )\n{\n char * i = string;\n char * p = string;\n while ( *++i ); while ( i &gt; p &amp;&amp; *p++ == *--i );\n return i &lt;= p &amp;&amp; *i++ == *--p;\n}\nint main( int argc, char **argv )\n{\n if ( argc != 2 )\n {\n fprintf( stderr, \"Usage: %s &lt;word&gt;\\n\", argv[0] );\n return -1;\n }\n fprintf( stdout, \"%s\\n\", isPalindrome( argv[1] ) ? \"yes\" : \"no\" );\n return 0;\n}\n</code></pre>\n\n<p>Well, that was fun - do I get the job ;^)</p>\n" }, { "answer_id": 52660, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>I'm seeing a lot of incorrect answers here. Any correct solution needs to ignore whitespace and punctuation (and any non-alphabetic characters actually) and needs to be case insensitive.</p>\n\n<p>A few good example test cases are:</p>\n\n<p>\"A man, a plan, a canal, Panama.\"</p>\n\n<p>\"A Toyota's a Toyota.\"</p>\n\n<p>\"A\"</p>\n\n<p>\"\"</p>\n\n<p>As well as some non-palindromes.</p>\n\n<p>Example solution in C# (note: empty and null strings are considered palindromes in this design, if this is not desired it's easy to change):</p>\n\n<pre><code>public static bool IsPalindrome(string palindromeCandidate)\n{\n if (string.IsNullOrEmpty(palindromeCandidate))\n {\n return true;\n }\n Regex nonAlphaChars = new Regex(\"[^a-z0-9]\");\n string alphaOnlyCandidate = nonAlphaChars.Replace(palindromeCandidate.ToLower(), \"\");\n if (string.IsNullOrEmpty(alphaOnlyCandidate))\n {\n return true;\n }\n int leftIndex = 0;\n int rightIndex = alphaOnlyCandidate.Length - 1;\n while (rightIndex &gt; leftIndex)\n {\n if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])\n {\n return false;\n }\n leftIndex++;\n rightIndex--;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52749, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": false, "text": "<p>A more Ruby-style rewrite of <a href=\"https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52328\">Hal's Ruby version</a>:</p>\n\n<pre><code>class String\n def palindrome?\n (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse\n end\nend\n</code></pre>\n\n<p>Now you can call <code>palindrome?</code> on any string.</p>\n" }, { "answer_id": 53009, "author": "Hostile", "author_id": 5323, "author_profile": "https://Stackoverflow.com/users/5323", "pm_score": 3, "selected": false, "text": "<p>C in the house. (not sure if you didn't want a C example here)</p>\n\n<pre><code>bool IsPalindrome(char *s)\n{\n int i,d;\n int length = strlen(s);\n char cf, cb;\n\n for(i=0, d=length-1 ; i &lt; length &amp;&amp; d &gt;= 0 ; i++ , d--)\n {\n while(cf= toupper(s[i]), (cf &lt; 'A' || cf &gt;'Z') &amp;&amp; i &lt; length-1)i++;\n while(cb= toupper(s[d]), (cb &lt; 'A' || cb &gt;'Z') &amp;&amp; d &gt; 0 )d--;\n if(cf != cb &amp;&amp; cf &gt;= 'A' &amp;&amp; cf &lt;= 'Z' &amp;&amp; cb &gt;= 'A' &amp;&amp; cb &lt;='Z')\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>That will return true for \"racecar\", \"Racecar\", \"race car\", \"racecar \", and \"RaCe cAr\". It would be easy to modify to include symbols or spaces as well, but I figure it's more useful to only count letters(and ignore case). This works for all palindromes I've found in the answers here, and I've been unable to trick it into false negatives/positives.</p>\n\n<p>Also, if you don't like bool in a \"C\" program, it could obviously return int, with return 1 and return 0 for true and false respectively.</p>\n" }, { "answer_id": 53055, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 1, "selected": false, "text": "<p>Perl:</p>\n\n<pre><code>sub is_palindrome($)\n{\n $s = lc(shift); # ignore case\n $s =~ s/\\W+//g; # consider only letters, digits, and '_'\n $s eq reverse $s;\n}\n</code></pre>\n\n<p>It ignores case and strips non-alphanumeric characters (it locale- and unicode- neutral).</p>\n" }, { "answer_id": 53148, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>Using Java, using <a href=\"http://commons.apache.org/\" rel=\"nofollow noreferrer\">Apache Commons</a> String Utils:</p>\n\n<pre><code>public boolean isPalindrome(String phrase) {\n phrase = phrase.toLowerCase().replaceAll(\"[^a-z]\", \"\");\n return StringUtils.reverse(phrase).equals(phrase);\n}\n</code></pre>\n" }, { "answer_id": 53215, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "<p>If we're looking for numbers and simple words, many correct answers have been given.</p>\n\n<p>However, if we're looking for what we generally see as palindromes in written language (e.g., \"A dog, a panic, in a pagoda!\"), the correct answer would be to iterate starting from both ends of the sentence, <em>skipping non-alphanumeric characters individually</em>, and returning false if any mismatches are found.</p>\n\n<pre><code>i = 0; j = length-1;\n\nwhile( true ) {\n while( i &lt; j &amp;&amp; !is_alphanumeric( str[i] ) ) i++;\n while( i &lt; j &amp;&amp; !is_alphanumeric( str[j] ) ) j--;\n\n if( i &gt;= j ) return true;\n\n if( tolower(string[i]) != tolower(string[j]) ) return false;\n i++; j--;\n}\n</code></pre>\n\n<p></p>\n\n<p>Of course, stripping out non-valid characters, reversing the resulting string and comparing it to the original one also works. It comes down to what type of language you're working on.</p>\n" }, { "answer_id": 53505, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 1, "selected": false, "text": "<p>I had to do this for a programming challenge, here's a snippet of my Haskell:</p>\n\n<pre><code>isPalindrome :: String -&gt; Bool\nisPalindrome n = (n == reverse n)\n</code></pre>\n" }, { "answer_id": 56204, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 1, "selected": false, "text": "<p>Python:</p>\n\n<pre><code>if s == s[::-1]: return True\n</code></pre>\n\n<p>Java:</p>\n\n<pre><code>if (s.Equals(s.Reverse())) { return true; }\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if (s == strrev(s)) return true;\n</code></pre>\n\n<p>Perl:</p>\n\n<pre><code>if (s == reverse(s)) { return true; }\n</code></pre>\n\n<p>Erlang:</p>\n\n<pre><code>string:equal(S, lists:reverse(S)).\n</code></pre>\n" }, { "answer_id": 58575, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "<p>OCaml:</p>\n\n<pre><code>let rec palindrome s =\n s = (tailrev s)\n</code></pre>\n\n<p><a href=\"http://www.cis.upenn.edu/~lhuang3/cse399-python/handouts/ocaml.ppt\" rel=\"nofollow noreferrer\">source</a></p>\n" }, { "answer_id": 59364, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 2, "selected": false, "text": "<p><strong>Lisp:</strong></p>\n\n<pre><code>(defun palindrome(x) (string= x (reverse x)))\n</code></pre>\n" }, { "answer_id": 63366, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 0, "selected": false, "text": "<pre><code>boolean IsPalindrome(string s) {\nreturn s = s.Reverse();\n}\n</code></pre>\n" }, { "answer_id": 68900, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "<p>Perl:</p>\n\n<pre><code>sub is_palindrome {\n my $s = lc shift; # normalize case\n $s =~ s/\\W//g; # strip non-word characters\n return $s eq reverse $s;\n}\n</code></pre>\n" }, { "answer_id": 77508, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "<p>An obfuscated C version:</p>\n\n<pre><code>int IsPalindrome (char *s)\n{\n char*a,*b,c=0;\n for(a=b=s;a&lt;=b;c=(c?c==1?c=(*a&amp;~32)-65&gt;25u?*++a,1:2:c==2?(*--b&amp;~32)-65&lt;26u?3:2:c==3?(*b-65&amp;~32)-(*a-65&amp;~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));\n return s!=0;\n}\n</code></pre>\n" }, { "answer_id": 77620, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>Note that in the above C++ solutions, there was some problems.</p>\n<p>One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting &quot;false&quot;.</p>\n<p>The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into &quot;T&quot;, it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator &lt;, the std::list was out of its scope.</p>\n<p>My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an <em>anything</em> that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of &quot;Anything&quot; as long as Anything was comparable through its operator = (build in types, as well as classes).</p>\n<p>Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e).</p>\n<p>Like king Leonidas would have said: <em>&quot;Templates ? This is C++ !!!&quot;</em></p>\n<p>So, in C++, there are at least 3 major ways to do it, each one leading to the other:</p>\n<h2>Solution A: In a c-like way</h2>\n<p>The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must &quot;cheat&quot; and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok...</p>\n<hr />\n<pre><code>bool isPalindromeA(const std::string &amp; p_strText)\n{\n if(p_strText.length() &lt; 2) return true ;\n const char * pStart = p_strText.c_str() ; \n const char * pEnd = pStart + p_strText.length() - 1 ; \n\n for(; pStart &lt; pEnd; ++pStart, --pEnd)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n }\n\n return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution B: A more &quot;C++&quot; version</h2>\n<p>Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed.</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeB(const T &amp; p_aText)\n{\n if(p_aText.empty()) return true ;\n typename T::size_type iStart = 0 ;\n typename T::size_type iEnd = p_aText.size() - 1 ;\n\n for(; iStart &lt; iEnd; ++iStart, --iEnd)\n {\n if(p_aText[iStart] != p_aText[iEnd])\n {\n return false ;\n }\n }\n\n return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution C: Template powah !</h2>\n<p>It will work with almost any unordered STL-like container with bidirectional iterators\nFor example, any std::basic_string, std::vector, std::deque, std::list, etc.\nSo, this function can be applied on all STL-like containers with the following conditions:\n1 - T is a container with bidirectional iterator\n2 - T's iterator points to a comparable type (through operator =)</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeC(const T &amp; p_aText)\n{\n if(p_aText.empty()) return true ;\n typename T::const_iterator pStart = p_aText.begin() ;\n typename T::const_iterator pEnd = p_aText.end() ;\n --pEnd ;\n\n while(true)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n\n if((pStart == pEnd) || (++pStart == pEnd))\n {\n return true ;\n }\n\n --pEnd ;\n }\n}\n</code></pre>\n<hr />\n" }, { "answer_id": 228706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>c++:</p>\n\n<pre><code>bool is_palindrome(const string &amp;s)\n{\n return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());\n}\n</code></pre>\n" }, { "answer_id": 228707, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 0, "selected": false, "text": "<p>There isn't a <em>single</em> solution on here which takes into account that a palindrome can also be based on word units, not just character units.</p>\n\n<p>Which means that none of the given solutions return true for palindromes like \"Girl, bathing on Bikini, eyeing boy, sees boy eyeing bikini on bathing girl\".</p>\n\n<p>Here's a hacked together version in C#. I'm sure it doesn't need the regexes, but it does work just as well with the above bikini palindrome as it does with \"A man, a plan, a canal-Panama!\".</p>\n\n<pre><code> static bool IsPalindrome(string text)\n {\n bool isPalindrome = IsCharacterPalindrome(text);\n if (!isPalindrome)\n {\n isPalindrome = IsPhrasePalindrome(text);\n }\n return isPalindrome;\n }\n\n static bool IsCharacterPalindrome(string text)\n {\n String clean = Regex.Replace(text.ToLower(), \"[^A-z0-9]\", String.Empty, RegexOptions.Compiled);\n bool isPalindrome = false;\n if (!String.IsNullOrEmpty(clean) &amp;&amp; clean.Length &gt; 1)\n {\n isPalindrome = true;\n for (int i = 0, count = clean.Length / 2 + 1; i &lt; count; i++)\n {\n if (clean[i] != clean[clean.Length - 1 - i])\n {\n isPalindrome = false; break;\n }\n }\n }\n return isPalindrome;\n }\n\n static bool IsPhrasePalindrome(string text)\n {\n bool isPalindrome = false;\n String clean = Regex.Replace(text.ToLower(), @\"[^A-z0-9\\s]\", \" \", RegexOptions.Compiled).Trim();\n String[] words = Regex.Split(clean, @\"\\s+\");\n if (words.Length &gt; 1)\n {\n isPalindrome = true;\n for (int i = 0, count = words.Length / 2 + 1; i &lt; count; i++)\n {\n if (words[i] != words[words.Length - 1 - i])\n {\n isPalindrome = false; break;\n }\n }\n }\n return isPalindrome;\n }\n</code></pre>\n" }, { "answer_id": 263449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I haven't seen any recursion yet, so here goes...</p>\n\n<pre><code>import re\n\nr = re.compile(\"[^0-9a-zA-Z]\")\n\ndef is_pal(s):\n\n def inner_pal(s):\n if len(s) == 0:\n return True\n elif s[0] == s[-1]:\n return inner_pal(s[1:-1])\n else:\n return False\n\n r = re.compile(\"[^0-9a-zA-Z]\")\n return inner_pal(r.sub(\"\", s).lower())\n</code></pre>\n" }, { "answer_id": 277721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is all good, but is there a way to do better algorithmically? I was once asked in a interview to recognize a palindrome in linear time and <em>constant space</em>.</p>\n\n<p>I couldn't think of anything then and I still can't. </p>\n\n<p>(If it helps, I asked the interviewer what the answer was. He said you can construct a pair of hash functions such that they hash a given string to the same value if and only if that string is a palindrome. I have no idea how you would actually make this pair of functions.)</p>\n" }, { "answer_id": 277727, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<h2>C++</h2>\n\n<pre><code>std::string a = \"god\";\nstd::string b = \"lol\";\n\nstd::cout &lt;&lt; (std::string(a.rbegin(), a.rend()) == a) &lt;&lt; \" \" \n &lt;&lt; (std::string(b.rbegin(), b.rend()) == b);\n</code></pre>\n\n<h2>Bash</h2>\n\n<pre><code>function ispalin { [ \"$( echo -n $1 | tac -rs . )\" = \"$1\" ]; }\necho \"$(ispalin god &amp;&amp; echo yes || echo no), $(ispalin lol &amp;&amp; echo yes || echo no)\"\n</code></pre>\n\n<h2>Gnu Awk</h2>\n\n<pre><code>/* obvious solution */\nfunction ispalin(cand, i) { \n for(i=0; i&lt;length(cand)/2; i++) \n if(substr(cand, length(cand)-i, 1) != substr(cand, i+1, 1)) \n return 0; \n return 1; \n}\n\n/* not so obvious solution. cough cough */\n{ \n orig = $0;\n while($0) { \n stuff = stuff gensub(/^.*(.)$/, \"\\\\1\", 1); \n $0 = gensub(/^(.*).$/, \"\\\\1\", 1); \n }\n print (stuff == orig); \n}\n</code></pre>\n\n<h2>Haskell</h2>\n\n<p>Some brain dead way doing it in Haskell</p>\n\n<pre><code>ispalin :: [Char] -&gt; Bool\nispalin a = a == (let xi (y:my) = (xi my) ++ [y]; xi [] = [] in \\x -&gt; xi x) a\n</code></pre>\n\n<h2>Plain English</h2>\n\n<p><code>\"Just reverse the string and if it is the same as before, it's a palindrome\"</code></p>\n" }, { "answer_id": 278003, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 0, "selected": false, "text": "<p>The solutions which strip out any chars that don't fall between A-Z or a-z are very English centric. Letters with diacritics such as à or é would be stripped! </p>\n\n<p>According to Wikipedia: </p>\n\n<blockquote>\n <p>The treatment of diacritics varies. In languages such as Czech and Spanish, letters with diacritics or accents (except tildes) are not given a separate place in the alphabet, and thus preserve the palindrome whether or not the repeated letter has an ornamentation. However, in Swedish and other Nordic languages, A and A with a ring (å) are distinct letters and must be mirrored exactly to be considered a true palindrome.</p>\n</blockquote>\n\n<p>So to cover many other languages it would be better to use collation to convert diacritical marks to their equivalent non diacritic or leave alone as appropriate and then strip whitespace and punctuation only before comparing.</p>\n" }, { "answer_id": 371523, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 0, "selected": false, "text": "<pre><code>set l = index of left most character in word\nset r = index of right most character in word\n\nloop while(l &lt; r)\nbegin\n if letter at l does not equal letter at r\n word is not palindrome\n else\n increase l and decrease r\nend\nword is palindrome\n</code></pre>\n" }, { "answer_id": 430317, "author": "Vadim Ferderer", "author_id": 24142, "author_profile": "https://Stackoverflow.com/users/24142", "pm_score": 0, "selected": false, "text": "<p>Efficient C++ version:</p>\n\n<pre><code>template&lt; typename Iterator &gt;\nbool is_palindrome( Iterator first, Iterator last, std::locale const&amp; loc = std::locale(\"\") )\n{\n if ( first == last )\n return true;\n\n for( --last; first &lt; last; ++first, --last )\n {\n while( ! std::isalnum( *first, loc ) &amp;&amp; first &lt; last )\n ++first;\n while( ! std::isalnum( *last, loc ) &amp;&amp; first &lt; last )\n --last;\n if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )\n return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 430363, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>Here are two more Perl versions, neither of which uses <code>reverse</code>. Both use the basic algorithm of comparing the first character of the string to the last, then discarding them and repeating the test, but they use different methods of getting at the individual characters (the first peels them off one at a time with a regex, the second <code>split</code>s the string into an array of characters).</p>\n\n<pre><code>#!/usr/bin/perl\n\nmy @strings = (\"A man, a plan, a canal, Panama.\", \"A Toyota's a Toyota.\", \n \"A\", \"\", \"As well as some non-palindromes.\");\n\nfor my $string (@strings) {\n print is_palindrome($string) ? \"'$string' is a palindrome (1)\\n\"\n : \"'$string' is not a palindrome (1)\\n\";\n print is_palindrome2($string) ? \"'$string' is a palindrome (2)\\n\"\n : \"'$string' is not a palindrome (2)\\n\";\n} \n\nsub is_palindrome {\n my $str = lc shift;\n $str =~ tr/a-z//cd;\n\n while ($str =~ s/^(.)(.*)(.)$/\\2/) {\n return unless $1 eq $3;\n }\n\n return 1;\n} \n\nsub is_palindrome2 {\n my $str = lc shift;\n $str =~ tr/a-z//cd;\n my @chars = split '', $str;\n\n while (@chars &amp;&amp; shift @chars eq pop @chars) {};\n\n return scalar @chars &lt;= 1;\n} \n</code></pre>\n" }, { "answer_id": 430393, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "<p>Easy mode in C#, only using Base Class Libraries</p>\n\n<p>Edit: just saw someone did Array.Reverse also </p>\n\n<pre><code>public bool IsPalindrome(string s)\n {\n if (String.IsNullOrEmpty(s))\n {\n return false;\n }\n\n else\n {\n char[] t = s.ToCharArray();\n Array.Reverse(t);\n string u = new string(t);\n if (s.ToLower() == u.ToLower())\n {\n return true;\n }\n }\n\n return false;\n }\n</code></pre>\n" }, { "answer_id": 430444, "author": "BBetances", "author_id": 53599, "author_profile": "https://Stackoverflow.com/users/53599", "pm_score": 0, "selected": false, "text": "<p>Here's another for C# that I used when doing a sample server control. It can be found in the book ASP.NET 3.5 Step by Step (MS Press). It's two methods, one to strip non-alphanumerics, and another to check for a palindrome.</p>\n\n<pre><code>protected string StripNonAlphanumerics(string str)\n{\n string strStripped = (String)str.Clone();\n if (str != null)\n {\n char[] rgc = strStripped.ToCharArray();\n int i = 0;\n foreach (char c in rgc)\n {\n if (char.IsLetterOrDigit(c))\n {\n i++;\n }\n else\n {\n strStripped = strStripped.Remove(i, 1);\n }\n }\n }\n return strStripped;\n}\nprotected bool CheckForPalindrome()\n{\n if (this.Text != null)\n {\n String strControlText = this.Text;\n String strTextToUpper = null;\n strTextToUpper = Text.ToUpper();\n strControlText =\n this.StripNonAlphanumerics(strTextToUpper);\n char[] rgcReverse = strControlText.ToCharArray();\n Array.Reverse(rgcReverse);\n String strReverse = new string(rgcReverse);\n if (strControlText == strReverse)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 430483, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 0, "selected": false, "text": "<p>Const-correct C/C++ pointer solution. Minimal operations in loop.</p>\n\n<pre><code>int IsPalindrome (const char *str)\n{\n const unsigned len = strlen(str);\n const char *end = &amp;str[len-1];\n while (str &lt; end)\n if (*str++ != *end--)\n return 0;\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 659809, "author": "Ascalonian", "author_id": 65230, "author_profile": "https://Stackoverflow.com/users/65230", "pm_score": 2, "selected": false, "text": "<p>A simple Java solution:</p>\n\n<pre><code>public boolean isPalindrome(String testString) {\n StringBuffer sb = new StringBuffer(testString);\n String reverseString = sb.reverse().toString();\n\n if(testString.equalsIgnoreCase(reverseString)) {\n return true;\n else {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 1039466, "author": "patjbs", "author_id": 79256, "author_profile": "https://Stackoverflow.com/users/79256", "pm_score": 1, "selected": false, "text": "<p>My 2c. Avoids overhead of full string reversal everytime, taking advantage of shortcircuiting to return as soon as the nature of the string is determined. Yes, you should condition your string first, but IMO that's the job of another function.</p>\n\n<p><strong>In C#</strong></p>\n\n<pre><code> /// &lt;summary&gt;\n /// Tests if a string is a palindrome\n /// &lt;/summary&gt;\n public static bool IsPalindrome(this String str)\n {\n if (str.Length == 0) return false;\n int index = 0;\n while (index &lt; str.Length / 2)\n if (str[index] != str[str.Length - ++index]) return false;\n\n return true;\n }\n</code></pre>\n" }, { "answer_id": 1039549, "author": "Matchu", "author_id": 107415, "author_profile": "https://Stackoverflow.com/users/107415", "pm_score": 2, "selected": false, "text": "<h2>Ruby:</h2>\n\n<pre><code>class String\n def is_palindrome?\n letters_only = gsub(/\\W/,'').downcase\n letters_only == letters_only.reverse\n end\nend\n\nputs 'abc'.is_palindrome? # =&gt; false\nputs 'aba'.is_palindrome? # =&gt; true\nputs \"Madam, I'm Adam.\".is_palindrome? # =&gt; true\n</code></pre>\n" }, { "answer_id": 1078441, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 0, "selected": false, "text": "<p><strong>Scala</strong></p>\n\n<pre><code>def pal(s:String) = Symbol(s) equals Symbol(s.reverse)\n</code></pre>\n" }, { "answer_id": 1115333, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><strong>Prolog</strong></p>\n</blockquote>\n\n<pre><code>palindrome(B, R) :-\npalindrome(B, R, []).\n\npalindrome([], R, R).\npalindrome([X|B], [X|R], T) :-\npalindrome(B, R, [X|T]).\n</code></pre>\n" }, { "answer_id": 2049311, "author": "Pritam Karmakar", "author_id": 208513, "author_profile": "https://Stackoverflow.com/users/208513", "pm_score": 0, "selected": false, "text": "<pre><code> public bool IsPalindrome(string s)\n {\n string formattedString = s.Replace(\" \", string.Empty).ToLower();\n for (int i = 0; i &lt; formattedString.Length / 2; i++)\n {\n if (formattedString[i] != formattedString[formattedString.Length - 1 - i])\n return false;\n }\n return true;\n }\n</code></pre>\n\n<p>This method will work for sting like \"Was it a rat I saw\". But I feel we need to eliminate special character through Regex.</p>\n" }, { "answer_id": 2751730, "author": "rockvista", "author_id": 1996230, "author_profile": "https://Stackoverflow.com/users/1996230", "pm_score": 0, "selected": false, "text": "<p>C# Version:</p>\n\n<p>Assumes MyString to be a char[], Method return after verification of the string, it ignores space and &lt;,>, but this can be extended to ignore more, probably impleemnt a regex match of ignore list.</p>\n\n<pre><code>public bool IsPalindrome()\n if (MyString.Length == 0)\n return false;\n\n int len = MyString.Length - 1;\n\n int first = 0;\n int second = 0;\n\n for (int i = 0, j = len; i &lt;= len / 2; i++, j--)\n {\n while (i&lt;j &amp;&amp; MyString[i] == ' ' || MyString[i] == ',')\n i++;\n\n while(j&gt;i &amp;&amp; MyString[j] == ' ' || MyString[j] == ',')\n j--;\n\n if ((i == len / 2) &amp;&amp; (i == j))\n return true;\n\n first = MyString[i] &gt;= 97 &amp;&amp; MyString[i] &lt;= 122 ? MyString[i] - 32 : MyString[i];\n second = MyString[j] &gt;= 97 &amp;&amp; MyString[j] &lt;= 122 ? MyString[j] - 32 : MyString[j];\n\n if (first != second)\n return false;\n }\n\n return true;\n }\n</code></pre>\n\n<p>Quick test cases</p>\n\n<p>negative\n1. ABCDA \n2. AB CBAG\n3. A#$BDA\n4. NULL/EMPTY</p>\n\n<p>positive\n1. ABCBA\n2. A, man a plan a canal,,Panama\n3. ABC BA\n4. M\n5. ACCB</p>\n\n<p>let me know any thoghts/errors.</p>\n" }, { "answer_id": 5130209, "author": "Micke", "author_id": 635969, "author_profile": "https://Stackoverflow.com/users/635969", "pm_score": 0, "selected": false, "text": "<p>How about this PHP example: </p>\n\n<pre><code>function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {\n $returnstrrev = \"returnstrrevverrtsnruter\";\n $verrtsnruter = $functionnoitcnuf;\n return (strrev ($verrtsnruter) == $functionnoitcnuf) ; \n}\n</code></pre>\n" }, { "answer_id": 5494118, "author": "Bubbles", "author_id": 631423, "author_profile": "https://Stackoverflow.com/users/631423", "pm_score": 0, "selected": false, "text": "<pre><code>public static boolean isPalindrome( String str ) {\n int count = str.length() ;\n int i, j = count - 1 ;\n for ( i = 0 ; i &lt; count ; i++ ) {\n if ( str.charAt(i) != str.charAt(j) ) return false ;\n if ( i == j ) return true ;\n j-- ;\n }\n return true ;\n}\n</code></pre>\n" }, { "answer_id": 8181718, "author": "Ram", "author_id": 50418, "author_profile": "https://Stackoverflow.com/users/50418", "pm_score": 1, "selected": false, "text": "<p>Erlang is awesome</p>\n\n<pre><code>palindrome(L) -&gt; palindrome(L,[]).\n\npalindrome([],_) -&gt; false;\npalindrome([_|[]],[]) -&gt; true;\npalindrome([_|L],L) -&gt; true;\npalindrome(L,L) -&gt; true;\npalindrome([H|T], Acc) -&gt; palindrome(T, [H|Acc]).\n</code></pre>\n" }, { "answer_id": 8672758, "author": "Mushimo", "author_id": 456206, "author_profile": "https://Stackoverflow.com/users/456206", "pm_score": 1, "selected": false, "text": "<p>No solution using JavaScript yet?</p>\n\n<pre><code>function palindrome(s) {\n var l = 0, r = s.length - 1;\n while (l &lt; r) if (s.charAt(left++) !== s.charAt(r--)) return false;\n return true\n}\n</code></pre>\n" }, { "answer_id": 8733562, "author": "Justin", "author_id": 950252, "author_profile": "https://Stackoverflow.com/users/950252", "pm_score": 0, "selected": false, "text": "<p>If you can use Java APIs and additional storage:</p>\n\n<pre><code>public static final boolean isPalindromeWithAdditionalStorage(String string) {\n String reversed = new StringBuilder(string).reverse().toString();\n return string.equals(reversed);\n}\n</code></pre>\n\n<p>In can need an in-place method for Java:</p>\n\n<pre><code>public static final boolean isPalindromeInPlace(String string) {\n char[] array = string.toCharArray();\n int length = array.length-1;\n int half = Math.round(array.length/2);\n char a,b;\n for (int i=length; i&gt;=half; i--) {\n a = array[length-i];\n b = array[i];\n if (a != b) return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 9305682, "author": "melsk", "author_id": 809694, "author_profile": "https://Stackoverflow.com/users/809694", "pm_score": 0, "selected": false, "text": "<p><b>Regular Approach:</b></p>\n\n<pre><code>flag = True // Assume palindrome is true\nfor i from 0 to n/2 \n { compare element[i] and element[n-i-1] // 0 to n-1\n if not equal set flag = False\n break }\nreturn flag\n</code></pre>\n\n<p>There is a better machine optimized method which uses XORs but has the same complexity <br/><br/>\n<b>XOR approach</b>:</p>\n\n<pre><code>n = length of string\nmid_element = element[n/2 +1]\nfor i from 0 to n\n{ t_xor = element[i] xor element[i+1] }\nif n is odd compare mid_element and t_xor\nelse check t_xor is zero\n</code></pre>\n" }, { "answer_id": 14772912, "author": "user2039532", "author_id": 2039532, "author_profile": "https://Stackoverflow.com/users/2039532", "pm_score": 0, "selected": false, "text": "<pre><code>public class palindrome {\npublic static void main(String[] args) {\n StringBuffer strBuf1 = new StringBuffer(\"malayalam\");\n StringBuffer strBuf2 = new StringBuffer(\"malayalam\");\n strBuf2.reverse();\n\n\n System.out.println(strBuf2);\n System.out.println((strBuf1.toString()).equals(strBuf2.toString()));\n if ((strBuf1.toString()).equals(strBuf2.toString()))\n System.out.println(\"palindrome\");\n else\n System.out.println(\"not a palindrome\");\n }\n} \n</code></pre>\n" }, { "answer_id": 14906430, "author": "Rhys Ulerich", "author_id": 103640, "author_profile": "https://Stackoverflow.com/users/103640", "pm_score": 0, "selected": false, "text": "<p>A case-insensitive, <code>const</code>-friendly version in plain C that ignores non-alphanumeric characters (e.g. whitespace / punctuation). It therefore will actually pass on classics like \"A man, a plan, a canal, Panama\".</p>\n\n<pre><code>int ispalin(const char *b)\n{\n const char *e = b;\n while (*++e);\n while (--e &gt;= b)\n {\n if (isalnum(*e))\n {\n while (*b &amp;&amp; !isalnum(*b)) ++b;\n if (toupper(*b++) != toupper(*e)) return 0;\n }\n }\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 19893643, "author": "Adrian Bratu", "author_id": 1161008, "author_profile": "https://Stackoverflow.com/users/1161008", "pm_score": 0, "selected": false, "text": "<p>The interviewer will be looking for some logic on how you will be approaching this problem:\nPlease consider the following java code:</p>\n\n<ol>\n<li>always check if the input string is null</li>\n<li>check your base cases.</li>\n<li>format your string accordingly (remove anything that is not a character/digit</li>\n<li>Most likely they do not want to see if you know the reverse function, and a comparison, but rather if you are able to answer the question using a loop and indexing.</li>\n<li><p>shortcut return as soon as you know your answer and do not waste resources for nothing.</p>\n\n<p>public static boolean isPalindrome(String s) {</p>\n\n<pre><code>if (s == null || s.length() == 0 || s.length() == 1)\n return false;\n\nString ss = s.toLowerCase().replaceAll(\"/[^a-z]/\", \"\");\n\nfor (int i = 0; i &lt; ss.length()/2; i++) \n if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i))\n return false;\nreturn true;\n</code></pre>\n\n<p>}</p></li>\n</ol>\n" }, { "answer_id": 23638086, "author": "sam_rox", "author_id": 3577754, "author_profile": "https://Stackoverflow.com/users/3577754", "pm_score": 0, "selected": false, "text": "<p>Java with stacks.</p>\n\n<pre><code>public class StackPalindrome {\n public boolean isPalindrome(String s) throws OverFlowException,EmptyStackException{\n boolean isPal=false;\n String pal=\"\";\n char letter;\n if (s==\" \")\n return true;\n else{ \n s=s.toLowerCase();\n for(int i=0;i&lt;s.length();i++){\n\n letter=s.charAt(i);\n\n char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};\n for(int j=0; j&lt;alphabet.length;j++){\n /*removing punctuations*/\n if ((String.valueOf(letter)).equals(String.valueOf(alphabet[j]))){\n pal +=letter;\n }\n\n }\n\n }\n int len=pal.length();\n char[] palArray=new char[len];\n for(int r=0;r&lt;len;r++){\n palArray[r]=pal.charAt(r);\n }\n ArrayStack palStack=new ArrayStack(len);\n for(int k=0;k&lt;palArray.length;k++){\n palStack.push(palArray[k]);\n }\n for (int i=0;i&lt;len;i++){\n\n if ((palStack.topAndpop()).equals(palArray[i]))\n isPal=true;\n else \n isPal=false;\n }\n return isPal;\n }\n}\npublic static void main (String args[]) throws EmptyStackException,OverFlowException{\n\n StackPalindrome s=new StackPalindrome();\n System.out.println(s.isPalindrome(\"“Ma,” Jerome raps pot top, “Spare more jam!”\"));\n}\n</code></pre>\n" }, { "answer_id": 24759363, "author": "Pavan tej", "author_id": 2063399, "author_profile": "https://Stackoverflow.com/users/2063399", "pm_score": 0, "selected": false, "text": "<pre><code>//Single program for Both String or Integer to check palindrome\n\n//In java with out using string functions like reverse and equals method also and display matching characters also\n\npackage com.practice;\n\nimport java.util.Scanner;\n\npublic class Pallindrome {\n\n public static void main(String args[]) {\n Scanner sc=new Scanner(System.in);\n int i=0,j=0,k,count=0;\n String input,temp;\n System.out.println(\"Enter the String or Integer\");\n input=sc.nextLine();\n temp=input;\n k=temp.length()-1;\n for(i=0;i&lt;=input.length()-1;i++) {\n if(input.charAt(j)==temp.charAt(k)) {\n count++;\n }\n //For matching characters\n j++;\n k--;\n }\n System.out.println(\"Matching Characters = \"+count);\n\n if(count==input.length()) {\n System.out.println(\"It's a pallindrome\");\n }\n else {\n System.out.println(\"It's not a pallindrome\");\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 29174567, "author": "arsho", "author_id": 3129414, "author_profile": "https://Stackoverflow.com/users/3129414", "pm_score": 1, "selected": false, "text": "<p>Simple <strong>JavaScript</strong> solution. Run code snippet for demo.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function checkPalindrome(line){\r\n reverse_line=line.split(\"\").reverse().join(\"\");\r\n return line==reverse_line;\r\n }\r\nalert(\"checkPalindrome(radar): \"+checkPalindrome(\"radar\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 29587590, "author": "Confuse", "author_id": 3886922, "author_profile": "https://Stackoverflow.com/users/3886922", "pm_score": 0, "selected": false, "text": "<pre><code>public static boolean isPalindrome(String str) {\n return str.equals(new StringBuilder(str).reverse().toString());\n}\n</code></pre>\n\n<p>for versions of Java earlier than 1.5,</p>\n\n<pre><code>public static boolean isPalindrome(String str) {\n return str.equals(new StringBuffer().append(str).reverse().toString());\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public static boolean istPalindrom(char[] word){\n int i1 = 0;\n int i2 = word.length - 1;\n while (i2 &gt; i1) {\n if (word[i1] != word[i2]) {\n return false;\n }\n ++i1;\n --i2;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 32550261, "author": "mockee", "author_id": 468712, "author_profile": "https://Stackoverflow.com/users/468712", "pm_score": 0, "selected": false, "text": "<pre><code>// JavaScript Version.\nfunction isPalindrome(str) { \n str = str.replace(/[^a-zA-Z]/g, '')\n return str.split('').reverse().join('').toUpperCase() === str.toUpperCase() \n}\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
**Definition:** *A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction* How to check if the given string is a palindrome? This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C. Looking for solutions in any and all languages possible.
**PHP sample**: ``` $string = "A man, a plan, a canal, Panama"; function is_palindrome($string) { $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string)); return $a==strrev($a); } ``` Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.
52,008
<p>I need to design a small project for generating excel reports in .NET, which will be sent to users to use.</p> <p>The excel reports will contain PivotTables.</p> <p>I don't have much experience with them, but I can think of three implementation alternatives:</p> <ol> <li>Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.</li> <li>Generate a small access database and send it along with the excel file, connect to it.</li> <li>Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.</li> </ol> <p>What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?</p>
[ { "answer_id": 52013, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 2, "selected": false, "text": "<pre><code>boolean isPalindrome(String str1) {\n //first strip out punctuation and spaces\n String stripped = str1.replaceAll(\"[^a-zA-Z0-9]\", \"\");\n return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());\n}\n</code></pre>\n\n<p>Java version</p>\n" }, { "answer_id": 52014, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 5, "selected": false, "text": "<p>Language agnostic meta-code then...</p>\n\n<pre><code>rev = StringReverse(originalString)\nreturn ( rev == originalString );\n</code></pre>\n" }, { "answer_id": 52015, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 2, "selected": false, "text": "<p>Here's my solution in c#</p>\n\n<pre><code>static bool isPalindrome(string s)\n{\n string allowedChars = \"abcdefghijklmnopqrstuvwxyz\"+\n \"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string compareString = String.Empty;\n string rev = string.Empty;\n\n for (int i = 0; i &lt;= s.Length - 1; i++)\n {\n char c = s[i];\n\n if (allowedChars.IndexOf(c) &gt; -1)\n {\n compareString += c;\n }\n }\n\n\n for (int i = compareString.Length - 1; i &gt;= 0; i--)\n {\n char c = compareString[i];\n rev += c;\n }\n\n return rev.Equals(compareString, \n StringComparison.CurrentCultureIgnoreCase);\n}\n</code></pre>\n" }, { "answer_id": 52021, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "<pre><code>Delphi\n\nfunction IsPalindrome(const s: string): boolean;\nvar\n i, j: integer;\nbegin\n Result := false;\n j := Length(s);\n for i := 1 to Length(s) div 2 do begin\n if s[i] &lt;&gt; s[j] then\n Exit;\n Dec(j);\n end;\n Result := true;\nend;\n</code></pre>\n" }, { "answer_id": 52023, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>Unoptimized Python:</p>\n\n<pre><code>&gt;&gt;&gt; def is_palindrome(s):\n... return s == s[::-1]\n</code></pre>\n" }, { "answer_id": 52028, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "<p>Here's a python way. Note: this isn't really that \"pythonic\" but it demonstrates the algorithm.</p>\n\n<pre><code>def IsPalindromeString(n):\n myLen = len(n)\n i = 0\n while i &lt;= myLen/2:\n if n[i] != n[myLen-1-i]:\n return False\n i += 1\n return True\n</code></pre>\n" }, { "answer_id": 52031, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 5, "selected": false, "text": "<p>Windows XP (might also work on 2000) or later BATCH script:</p>\n\n<pre><code>@echo off\n\ncall :is_palindrome %1\nif %ERRORLEVEL% == 0 (\n echo %1 is a palindrome\n) else (\n echo %1 is NOT a palindrome\n)\nexit /B 0\n\n:is_palindrome\n set word=%~1\n set reverse=\n call :reverse_chars \"%word%\"\n set return=1\n if \"$%word%\" == \"$%reverse%\" (\n set return=0\n )\nexit /B %return%\n\n:reverse_chars\n set chars=%~1\n set reverse=%chars:~0,1%%reverse%\n set chars=%chars:~1%\n if \"$%chars%\" == \"$\" (\n exit /B 0\n ) else (\n call :reverse_chars \"%chars%\"\n )\nexit /B 0\n</code></pre>\n" }, { "answer_id": 52034, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p>C#: LINQ</p>\n\n<pre><code>var str = \"a b a\";\nvar test = Enumerable.SequenceEqual(str.ToCharArray(), \n str.ToCharArray().Reverse());\n</code></pre>\n" }, { "answer_id": 52036, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 1, "selected": false, "text": "<p>Many ways to do it. I guess the key is to do it in the most efficient way possible (without looping the string). I would do it as a char array which can be reversed easily (using C#).</p>\n\n<pre><code>string mystring = \"abracadabra\";\n\nchar[] str = mystring.ToCharArray();\nArray.Reverse(str);\nstring revstring = new string(str);\n\nif (mystring.equals(revstring))\n{\n Console.WriteLine(\"String is a Palindrome\");\n}\n</code></pre>\n" }, { "answer_id": 52038, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "<p><strong>C#</strong> in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function.</p>\n\n<pre><code>boolean IsPalindrome(string s) {\n for (int i = 0; i &lt; s.Length / 2; i++)\n {\n if (s[i] != s[s.Length - 1 - i]) return false;\n }\n return true;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> removed unnecessary \"<code>+1</code>\" in loop condition and spent the saved comparison on removing the redundant Length comparison. Thanks to the commenters!</p>\n" }, { "answer_id": 52039, "author": "xanadont", "author_id": 1886, "author_profile": "https://Stackoverflow.com/users/1886", "pm_score": 3, "selected": false, "text": "<p>Using a good data structure usually helps impress the professor:</p>\n\n<p>Push half the chars onto a stack (Length / 2).<br />\nPop and compare each char until the first unmatch.<br />\nIf the stack has zero elements: palindrome.<br />\n*in the case of a string with an odd Length, throw out the middle char.</p>\n" }, { "answer_id": 52040, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Here's my solution, without using a strrev. Written in C#, but it will work in any language that has a string length function.</p>\n\n<pre><code>private static bool Pal(string s) {\n for (int i = 0; i &lt; s.Length; i++) {\n if (s[i] != s[s.Length - 1 - i]) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52041, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 2, "selected": false, "text": "<p>This Java code should work inside a <strong>boolean</strong> method:</p>\n\n<p><strong>Note</strong>: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made.</p>\n\n<pre><code>private static boolean doPal(String test) {\n for(int i = 0; i &lt; test.length() / 2; i++) {\n if(test.charAt(i) != test.charAt(test.length() - 1 - i)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52048, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 4, "selected": false, "text": "<p>Java solution:</p>\n\n<pre><code>public class QuickTest {\n\npublic static void main(String[] args) {\n check(\"AmanaplanacanalPanama\".toLowerCase());\n check(\"Hello World\".toLowerCase());\n}\n\npublic static void check(String aString) {\n System.out.print(aString + \": \");\n char[] chars = aString.toCharArray();\n for (int i = 0, j = (chars.length - 1); i &lt; (chars.length / 2); i++, j--) {\n if (chars[i] != chars[j]) {\n System.out.println(\"Not a palindrome!\");\n return;\n }\n }\n System.out.println(\"Found a palindrome!\");\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 52051, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": false, "text": "<p><strong>PHP sample</strong>:</p>\n\n<pre><code>$string = \"A man, a plan, a canal, Panama\";\n\nfunction is_palindrome($string)\n{\n $a = strtolower(preg_replace(\"/[^A-Za-z0-9]/\",\"\",$string));\n return $a==strrev($a);\n}\n</code></pre>\n\n<p>Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.</p>\n" }, { "answer_id": 52053, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 3, "selected": false, "text": "<p>EDIT: from the comments:</p>\n\n<pre><code>bool palindrome(std::string const&amp; s) \n{ \n return std::equal(s.begin(), s.end(), s.rbegin()); \n} \n</code></pre>\n\n<hr>\n\n<p>The c++ way.</p>\n\n<p>My naive implementation using the elegant iterators. In reality, you would probably check\nand stop once your forward iterator has past the halfway mark to your string.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\nbool palindrome(string foo)\n{\n string::iterator front;\n string::reverse_iterator back;\n bool is_palindrome = true;\n for(front = foo.begin(), back = foo.rbegin();\n is_palindrome &amp;&amp; front!= foo.end() &amp;&amp; back != foo.rend();\n ++front, ++back\n )\n {\n if(*front != *back)\n is_palindrome = false;\n }\n return is_palindrome;\n}\nint main()\n{\n string a = \"hi there\", b = \"laval\";\n\n cout &lt;&lt; \"String a: \\\"\" &lt;&lt; a &lt;&lt; \"\\\" is \" &lt;&lt; ((palindrome(a))? \"\" : \"not \") &lt;&lt; \"a palindrome.\" &lt;&lt;endl;\n cout &lt;&lt; \"String b: \\\"\" &lt;&lt; b &lt;&lt; \"\\\" is \" &lt;&lt; ((palindrome(b))? \"\" : \"not \") &lt;&lt; \"a palindrome.\" &lt;&lt;endl;\n\n}\n</code></pre>\n" }, { "answer_id": 52057, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.</p>\n\n<p><em>Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.</em></p>\n\n<pre><code>function TForm1.IsPalindrome(txt: string): boolean;\nvar\n i, halfway, len : integer;\nbegin\n Result := True;\n len := Length(txt);\n\n {\n special cases:\n an empty string is *never* a palindrome\n a 1-character string is *always* a palindrome\n }\n case len of\n 0 : Result := False;\n 1 : Result := True;\n else begin\n halfway := Round((len/2) - (1/2)); //if odd, round down to get 1/2way pt\n\n //scan half of our string, make sure it is mirrored on the other half\n for i := 1 to halfway do begin\n if txt[i] &lt;&gt; txt[len-(i-1)] then begin\n Result := False;\n Break;\n end; //if we found a non-mirrored character\n end; //for 1st half of string\n end; //else not a special case\n end; //case\nend;\n</code></pre>\n\n<p>And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.</p>\n\n<pre><code>private bool IsPalindrome(string txt) {\n int len = txt.Length;\n\n /*\n Special cases:\n An empty string is *never* a palindrome\n A 1-character string is *always* a palindrome\n */ \n switch (len) {\n case 0: return false;\n case 1: return true;\n } //switch\n int halfway = (len / 2);\n\n //scan half of our string, make sure it is mirrored on the other half\n for (int i = 0; i &lt; halfway; ++i) {\n if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {\n return false;\n } //if\n } //for\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52063, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>C#3 - This returns false as soon as a char counted from the beginning fails to match its equivalent at the end:</p>\n\n<pre><code>static bool IsPalindrome(this string input)\n{\n char[] letters = input.ToUpper().ToCharArray();\n\n int i = 0;\n while( i &lt; letters.Length / 2 )\n if( letters[i] != letters[letters.Length - ++i] )\n return false;\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52064, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p>Here's a Python version that deals with different cases, punctuation and whitespace.</p>\n\n<pre><code>import string\n\ndef is_palindrome(palindrome):\n letters = palindrome.translate(string.maketrans(\"\",\"\"),\n string.whitespace + string.punctuation).lower()\n return letters == letters[::-1]\n</code></pre>\n\n<p><strong>Edit:</strong> Shamelessly stole from <a href=\"https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52023\">Blair Conrad's</a> neater answer to remove the slightly clumsy list processing from my previous version. </p>\n" }, { "answer_id": 52138, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "<p>Three versions in Smalltalk, from dumbest to correct.</p>\n\n<hr>\n\n<p>In Smalltalk, <code>=</code> is the comparison operator:</p>\n\n<pre><code>isPalindrome: aString\n \"Dumbest.\"\n ^ aString reverse = aString\n</code></pre>\n\n<hr>\n\n<p>The message <code>#translateToLowercase</code> returns the string as lowercase:</p>\n\n<pre><code>isPalindrome: aString\n \"Case insensitive\"\n |lowercase|\n lowercase := aString translateToLowercase.\n ^ lowercase reverse = lowercase\n</code></pre>\n\n<hr>\n\n<p>And in Smalltalk, strings are part of the <code>Collection</code> framework, you can use the message <code>#select:thenCollect:</code>, so here's the last version:</p>\n\n<pre><code>isPalindrome: aString\n \"Case insensitive and keeping only alphabetic chars\n (blanks &amp; punctuation insensitive).\"\n |lowercaseLetters|\n lowercaseLetters := aString\n select: [:char | char isAlphabetic]\n thenCollect: [:char | char asLowercase]. \n ^ lowercaseLetters reverse = lowercaseLetters\n</code></pre>\n" }, { "answer_id": 52153, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Another C++ one. Optimized for speed and size.</p>\n\n<p><code><pre>bool is_palindrome(const std::string&amp; candidate) {\n for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left &lt; --right ; ++left)\n if (*left != *right)\n return false;\n return true;\n}</pre></code></p>\n" }, { "answer_id": 52328, "author": "kranzky", "author_id": 5442, "author_profile": "https://Stackoverflow.com/users/5442", "pm_score": 1, "selected": false, "text": "<p>In Ruby, converting to lowercase and stripping everything not alphabetic:</p>\n\n<pre><code>def isPalindrome( string )\n ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse\nend\n</code></pre>\n\n<p>But that feels like cheating, right? No pointers or anything! So here's a C version too, but without the lowercase and character stripping goodness:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint isPalindrome( char * string )\n{\n char * i = string;\n char * p = string;\n while ( *++i ); while ( i &gt; p &amp;&amp; *p++ == *--i );\n return i &lt;= p &amp;&amp; *i++ == *--p;\n}\nint main( int argc, char **argv )\n{\n if ( argc != 2 )\n {\n fprintf( stderr, \"Usage: %s &lt;word&gt;\\n\", argv[0] );\n return -1;\n }\n fprintf( stdout, \"%s\\n\", isPalindrome( argv[1] ) ? \"yes\" : \"no\" );\n return 0;\n}\n</code></pre>\n\n<p>Well, that was fun - do I get the job ;^)</p>\n" }, { "answer_id": 52660, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>I'm seeing a lot of incorrect answers here. Any correct solution needs to ignore whitespace and punctuation (and any non-alphabetic characters actually) and needs to be case insensitive.</p>\n\n<p>A few good example test cases are:</p>\n\n<p>\"A man, a plan, a canal, Panama.\"</p>\n\n<p>\"A Toyota's a Toyota.\"</p>\n\n<p>\"A\"</p>\n\n<p>\"\"</p>\n\n<p>As well as some non-palindromes.</p>\n\n<p>Example solution in C# (note: empty and null strings are considered palindromes in this design, if this is not desired it's easy to change):</p>\n\n<pre><code>public static bool IsPalindrome(string palindromeCandidate)\n{\n if (string.IsNullOrEmpty(palindromeCandidate))\n {\n return true;\n }\n Regex nonAlphaChars = new Regex(\"[^a-z0-9]\");\n string alphaOnlyCandidate = nonAlphaChars.Replace(palindromeCandidate.ToLower(), \"\");\n if (string.IsNullOrEmpty(alphaOnlyCandidate))\n {\n return true;\n }\n int leftIndex = 0;\n int rightIndex = alphaOnlyCandidate.Length - 1;\n while (rightIndex &gt; leftIndex)\n {\n if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])\n {\n return false;\n }\n leftIndex++;\n rightIndex--;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 52749, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": false, "text": "<p>A more Ruby-style rewrite of <a href=\"https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52328\">Hal's Ruby version</a>:</p>\n\n<pre><code>class String\n def palindrome?\n (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse\n end\nend\n</code></pre>\n\n<p>Now you can call <code>palindrome?</code> on any string.</p>\n" }, { "answer_id": 53009, "author": "Hostile", "author_id": 5323, "author_profile": "https://Stackoverflow.com/users/5323", "pm_score": 3, "selected": false, "text": "<p>C in the house. (not sure if you didn't want a C example here)</p>\n\n<pre><code>bool IsPalindrome(char *s)\n{\n int i,d;\n int length = strlen(s);\n char cf, cb;\n\n for(i=0, d=length-1 ; i &lt; length &amp;&amp; d &gt;= 0 ; i++ , d--)\n {\n while(cf= toupper(s[i]), (cf &lt; 'A' || cf &gt;'Z') &amp;&amp; i &lt; length-1)i++;\n while(cb= toupper(s[d]), (cb &lt; 'A' || cb &gt;'Z') &amp;&amp; d &gt; 0 )d--;\n if(cf != cb &amp;&amp; cf &gt;= 'A' &amp;&amp; cf &lt;= 'Z' &amp;&amp; cb &gt;= 'A' &amp;&amp; cb &lt;='Z')\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>That will return true for \"racecar\", \"Racecar\", \"race car\", \"racecar \", and \"RaCe cAr\". It would be easy to modify to include symbols or spaces as well, but I figure it's more useful to only count letters(and ignore case). This works for all palindromes I've found in the answers here, and I've been unable to trick it into false negatives/positives.</p>\n\n<p>Also, if you don't like bool in a \"C\" program, it could obviously return int, with return 1 and return 0 for true and false respectively.</p>\n" }, { "answer_id": 53055, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 1, "selected": false, "text": "<p>Perl:</p>\n\n<pre><code>sub is_palindrome($)\n{\n $s = lc(shift); # ignore case\n $s =~ s/\\W+//g; # consider only letters, digits, and '_'\n $s eq reverse $s;\n}\n</code></pre>\n\n<p>It ignores case and strips non-alphanumeric characters (it locale- and unicode- neutral).</p>\n" }, { "answer_id": 53148, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>Using Java, using <a href=\"http://commons.apache.org/\" rel=\"nofollow noreferrer\">Apache Commons</a> String Utils:</p>\n\n<pre><code>public boolean isPalindrome(String phrase) {\n phrase = phrase.toLowerCase().replaceAll(\"[^a-z]\", \"\");\n return StringUtils.reverse(phrase).equals(phrase);\n}\n</code></pre>\n" }, { "answer_id": 53215, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "<p>If we're looking for numbers and simple words, many correct answers have been given.</p>\n\n<p>However, if we're looking for what we generally see as palindromes in written language (e.g., \"A dog, a panic, in a pagoda!\"), the correct answer would be to iterate starting from both ends of the sentence, <em>skipping non-alphanumeric characters individually</em>, and returning false if any mismatches are found.</p>\n\n<pre><code>i = 0; j = length-1;\n\nwhile( true ) {\n while( i &lt; j &amp;&amp; !is_alphanumeric( str[i] ) ) i++;\n while( i &lt; j &amp;&amp; !is_alphanumeric( str[j] ) ) j--;\n\n if( i &gt;= j ) return true;\n\n if( tolower(string[i]) != tolower(string[j]) ) return false;\n i++; j--;\n}\n</code></pre>\n\n<p></p>\n\n<p>Of course, stripping out non-valid characters, reversing the resulting string and comparing it to the original one also works. It comes down to what type of language you're working on.</p>\n" }, { "answer_id": 53505, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 1, "selected": false, "text": "<p>I had to do this for a programming challenge, here's a snippet of my Haskell:</p>\n\n<pre><code>isPalindrome :: String -&gt; Bool\nisPalindrome n = (n == reverse n)\n</code></pre>\n" }, { "answer_id": 56204, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 1, "selected": false, "text": "<p>Python:</p>\n\n<pre><code>if s == s[::-1]: return True\n</code></pre>\n\n<p>Java:</p>\n\n<pre><code>if (s.Equals(s.Reverse())) { return true; }\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if (s == strrev(s)) return true;\n</code></pre>\n\n<p>Perl:</p>\n\n<pre><code>if (s == reverse(s)) { return true; }\n</code></pre>\n\n<p>Erlang:</p>\n\n<pre><code>string:equal(S, lists:reverse(S)).\n</code></pre>\n" }, { "answer_id": 58575, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "<p>OCaml:</p>\n\n<pre><code>let rec palindrome s =\n s = (tailrev s)\n</code></pre>\n\n<p><a href=\"http://www.cis.upenn.edu/~lhuang3/cse399-python/handouts/ocaml.ppt\" rel=\"nofollow noreferrer\">source</a></p>\n" }, { "answer_id": 59364, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 2, "selected": false, "text": "<p><strong>Lisp:</strong></p>\n\n<pre><code>(defun palindrome(x) (string= x (reverse x)))\n</code></pre>\n" }, { "answer_id": 63366, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 0, "selected": false, "text": "<pre><code>boolean IsPalindrome(string s) {\nreturn s = s.Reverse();\n}\n</code></pre>\n" }, { "answer_id": 68900, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "<p>Perl:</p>\n\n<pre><code>sub is_palindrome {\n my $s = lc shift; # normalize case\n $s =~ s/\\W//g; # strip non-word characters\n return $s eq reverse $s;\n}\n</code></pre>\n" }, { "answer_id": 77508, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "<p>An obfuscated C version:</p>\n\n<pre><code>int IsPalindrome (char *s)\n{\n char*a,*b,c=0;\n for(a=b=s;a&lt;=b;c=(c?c==1?c=(*a&amp;~32)-65&gt;25u?*++a,1:2:c==2?(*--b&amp;~32)-65&lt;26u?3:2:c==3?(*b-65&amp;~32)-(*a-65&amp;~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));\n return s!=0;\n}\n</code></pre>\n" }, { "answer_id": 77620, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>Note that in the above C++ solutions, there was some problems.</p>\n<p>One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting &quot;false&quot;.</p>\n<p>The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into &quot;T&quot;, it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator &lt;, the std::list was out of its scope.</p>\n<p>My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an <em>anything</em> that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of &quot;Anything&quot; as long as Anything was comparable through its operator = (build in types, as well as classes).</p>\n<p>Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e).</p>\n<p>Like king Leonidas would have said: <em>&quot;Templates ? This is C++ !!!&quot;</em></p>\n<p>So, in C++, there are at least 3 major ways to do it, each one leading to the other:</p>\n<h2>Solution A: In a c-like way</h2>\n<p>The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must &quot;cheat&quot; and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok...</p>\n<hr />\n<pre><code>bool isPalindromeA(const std::string &amp; p_strText)\n{\n if(p_strText.length() &lt; 2) return true ;\n const char * pStart = p_strText.c_str() ; \n const char * pEnd = pStart + p_strText.length() - 1 ; \n\n for(; pStart &lt; pEnd; ++pStart, --pEnd)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n }\n\n return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution B: A more &quot;C++&quot; version</h2>\n<p>Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed.</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeB(const T &amp; p_aText)\n{\n if(p_aText.empty()) return true ;\n typename T::size_type iStart = 0 ;\n typename T::size_type iEnd = p_aText.size() - 1 ;\n\n for(; iStart &lt; iEnd; ++iStart, --iEnd)\n {\n if(p_aText[iStart] != p_aText[iEnd])\n {\n return false ;\n }\n }\n\n return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution C: Template powah !</h2>\n<p>It will work with almost any unordered STL-like container with bidirectional iterators\nFor example, any std::basic_string, std::vector, std::deque, std::list, etc.\nSo, this function can be applied on all STL-like containers with the following conditions:\n1 - T is a container with bidirectional iterator\n2 - T's iterator points to a comparable type (through operator =)</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeC(const T &amp; p_aText)\n{\n if(p_aText.empty()) return true ;\n typename T::const_iterator pStart = p_aText.begin() ;\n typename T::const_iterator pEnd = p_aText.end() ;\n --pEnd ;\n\n while(true)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n\n if((pStart == pEnd) || (++pStart == pEnd))\n {\n return true ;\n }\n\n --pEnd ;\n }\n}\n</code></pre>\n<hr />\n" }, { "answer_id": 228706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>c++:</p>\n\n<pre><code>bool is_palindrome(const string &amp;s)\n{\n return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());\n}\n</code></pre>\n" }, { "answer_id": 228707, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 0, "selected": false, "text": "<p>There isn't a <em>single</em> solution on here which takes into account that a palindrome can also be based on word units, not just character units.</p>\n\n<p>Which means that none of the given solutions return true for palindromes like \"Girl, bathing on Bikini, eyeing boy, sees boy eyeing bikini on bathing girl\".</p>\n\n<p>Here's a hacked together version in C#. I'm sure it doesn't need the regexes, but it does work just as well with the above bikini palindrome as it does with \"A man, a plan, a canal-Panama!\".</p>\n\n<pre><code> static bool IsPalindrome(string text)\n {\n bool isPalindrome = IsCharacterPalindrome(text);\n if (!isPalindrome)\n {\n isPalindrome = IsPhrasePalindrome(text);\n }\n return isPalindrome;\n }\n\n static bool IsCharacterPalindrome(string text)\n {\n String clean = Regex.Replace(text.ToLower(), \"[^A-z0-9]\", String.Empty, RegexOptions.Compiled);\n bool isPalindrome = false;\n if (!String.IsNullOrEmpty(clean) &amp;&amp; clean.Length &gt; 1)\n {\n isPalindrome = true;\n for (int i = 0, count = clean.Length / 2 + 1; i &lt; count; i++)\n {\n if (clean[i] != clean[clean.Length - 1 - i])\n {\n isPalindrome = false; break;\n }\n }\n }\n return isPalindrome;\n }\n\n static bool IsPhrasePalindrome(string text)\n {\n bool isPalindrome = false;\n String clean = Regex.Replace(text.ToLower(), @\"[^A-z0-9\\s]\", \" \", RegexOptions.Compiled).Trim();\n String[] words = Regex.Split(clean, @\"\\s+\");\n if (words.Length &gt; 1)\n {\n isPalindrome = true;\n for (int i = 0, count = words.Length / 2 + 1; i &lt; count; i++)\n {\n if (words[i] != words[words.Length - 1 - i])\n {\n isPalindrome = false; break;\n }\n }\n }\n return isPalindrome;\n }\n</code></pre>\n" }, { "answer_id": 263449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I haven't seen any recursion yet, so here goes...</p>\n\n<pre><code>import re\n\nr = re.compile(\"[^0-9a-zA-Z]\")\n\ndef is_pal(s):\n\n def inner_pal(s):\n if len(s) == 0:\n return True\n elif s[0] == s[-1]:\n return inner_pal(s[1:-1])\n else:\n return False\n\n r = re.compile(\"[^0-9a-zA-Z]\")\n return inner_pal(r.sub(\"\", s).lower())\n</code></pre>\n" }, { "answer_id": 277721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is all good, but is there a way to do better algorithmically? I was once asked in a interview to recognize a palindrome in linear time and <em>constant space</em>.</p>\n\n<p>I couldn't think of anything then and I still can't. </p>\n\n<p>(If it helps, I asked the interviewer what the answer was. He said you can construct a pair of hash functions such that they hash a given string to the same value if and only if that string is a palindrome. I have no idea how you would actually make this pair of functions.)</p>\n" }, { "answer_id": 277727, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<h2>C++</h2>\n\n<pre><code>std::string a = \"god\";\nstd::string b = \"lol\";\n\nstd::cout &lt;&lt; (std::string(a.rbegin(), a.rend()) == a) &lt;&lt; \" \" \n &lt;&lt; (std::string(b.rbegin(), b.rend()) == b);\n</code></pre>\n\n<h2>Bash</h2>\n\n<pre><code>function ispalin { [ \"$( echo -n $1 | tac -rs . )\" = \"$1\" ]; }\necho \"$(ispalin god &amp;&amp; echo yes || echo no), $(ispalin lol &amp;&amp; echo yes || echo no)\"\n</code></pre>\n\n<h2>Gnu Awk</h2>\n\n<pre><code>/* obvious solution */\nfunction ispalin(cand, i) { \n for(i=0; i&lt;length(cand)/2; i++) \n if(substr(cand, length(cand)-i, 1) != substr(cand, i+1, 1)) \n return 0; \n return 1; \n}\n\n/* not so obvious solution. cough cough */\n{ \n orig = $0;\n while($0) { \n stuff = stuff gensub(/^.*(.)$/, \"\\\\1\", 1); \n $0 = gensub(/^(.*).$/, \"\\\\1\", 1); \n }\n print (stuff == orig); \n}\n</code></pre>\n\n<h2>Haskell</h2>\n\n<p>Some brain dead way doing it in Haskell</p>\n\n<pre><code>ispalin :: [Char] -&gt; Bool\nispalin a = a == (let xi (y:my) = (xi my) ++ [y]; xi [] = [] in \\x -&gt; xi x) a\n</code></pre>\n\n<h2>Plain English</h2>\n\n<p><code>\"Just reverse the string and if it is the same as before, it's a palindrome\"</code></p>\n" }, { "answer_id": 278003, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 0, "selected": false, "text": "<p>The solutions which strip out any chars that don't fall between A-Z or a-z are very English centric. Letters with diacritics such as à or é would be stripped! </p>\n\n<p>According to Wikipedia: </p>\n\n<blockquote>\n <p>The treatment of diacritics varies. In languages such as Czech and Spanish, letters with diacritics or accents (except tildes) are not given a separate place in the alphabet, and thus preserve the palindrome whether or not the repeated letter has an ornamentation. However, in Swedish and other Nordic languages, A and A with a ring (å) are distinct letters and must be mirrored exactly to be considered a true palindrome.</p>\n</blockquote>\n\n<p>So to cover many other languages it would be better to use collation to convert diacritical marks to their equivalent non diacritic or leave alone as appropriate and then strip whitespace and punctuation only before comparing.</p>\n" }, { "answer_id": 371523, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 0, "selected": false, "text": "<pre><code>set l = index of left most character in word\nset r = index of right most character in word\n\nloop while(l &lt; r)\nbegin\n if letter at l does not equal letter at r\n word is not palindrome\n else\n increase l and decrease r\nend\nword is palindrome\n</code></pre>\n" }, { "answer_id": 430317, "author": "Vadim Ferderer", "author_id": 24142, "author_profile": "https://Stackoverflow.com/users/24142", "pm_score": 0, "selected": false, "text": "<p>Efficient C++ version:</p>\n\n<pre><code>template&lt; typename Iterator &gt;\nbool is_palindrome( Iterator first, Iterator last, std::locale const&amp; loc = std::locale(\"\") )\n{\n if ( first == last )\n return true;\n\n for( --last; first &lt; last; ++first, --last )\n {\n while( ! std::isalnum( *first, loc ) &amp;&amp; first &lt; last )\n ++first;\n while( ! std::isalnum( *last, loc ) &amp;&amp; first &lt; last )\n --last;\n if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )\n return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 430363, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>Here are two more Perl versions, neither of which uses <code>reverse</code>. Both use the basic algorithm of comparing the first character of the string to the last, then discarding them and repeating the test, but they use different methods of getting at the individual characters (the first peels them off one at a time with a regex, the second <code>split</code>s the string into an array of characters).</p>\n\n<pre><code>#!/usr/bin/perl\n\nmy @strings = (\"A man, a plan, a canal, Panama.\", \"A Toyota's a Toyota.\", \n \"A\", \"\", \"As well as some non-palindromes.\");\n\nfor my $string (@strings) {\n print is_palindrome($string) ? \"'$string' is a palindrome (1)\\n\"\n : \"'$string' is not a palindrome (1)\\n\";\n print is_palindrome2($string) ? \"'$string' is a palindrome (2)\\n\"\n : \"'$string' is not a palindrome (2)\\n\";\n} \n\nsub is_palindrome {\n my $str = lc shift;\n $str =~ tr/a-z//cd;\n\n while ($str =~ s/^(.)(.*)(.)$/\\2/) {\n return unless $1 eq $3;\n }\n\n return 1;\n} \n\nsub is_palindrome2 {\n my $str = lc shift;\n $str =~ tr/a-z//cd;\n my @chars = split '', $str;\n\n while (@chars &amp;&amp; shift @chars eq pop @chars) {};\n\n return scalar @chars &lt;= 1;\n} \n</code></pre>\n" }, { "answer_id": 430393, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "<p>Easy mode in C#, only using Base Class Libraries</p>\n\n<p>Edit: just saw someone did Array.Reverse also </p>\n\n<pre><code>public bool IsPalindrome(string s)\n {\n if (String.IsNullOrEmpty(s))\n {\n return false;\n }\n\n else\n {\n char[] t = s.ToCharArray();\n Array.Reverse(t);\n string u = new string(t);\n if (s.ToLower() == u.ToLower())\n {\n return true;\n }\n }\n\n return false;\n }\n</code></pre>\n" }, { "answer_id": 430444, "author": "BBetances", "author_id": 53599, "author_profile": "https://Stackoverflow.com/users/53599", "pm_score": 0, "selected": false, "text": "<p>Here's another for C# that I used when doing a sample server control. It can be found in the book ASP.NET 3.5 Step by Step (MS Press). It's two methods, one to strip non-alphanumerics, and another to check for a palindrome.</p>\n\n<pre><code>protected string StripNonAlphanumerics(string str)\n{\n string strStripped = (String)str.Clone();\n if (str != null)\n {\n char[] rgc = strStripped.ToCharArray();\n int i = 0;\n foreach (char c in rgc)\n {\n if (char.IsLetterOrDigit(c))\n {\n i++;\n }\n else\n {\n strStripped = strStripped.Remove(i, 1);\n }\n }\n }\n return strStripped;\n}\nprotected bool CheckForPalindrome()\n{\n if (this.Text != null)\n {\n String strControlText = this.Text;\n String strTextToUpper = null;\n strTextToUpper = Text.ToUpper();\n strControlText =\n this.StripNonAlphanumerics(strTextToUpper);\n char[] rgcReverse = strControlText.ToCharArray();\n Array.Reverse(rgcReverse);\n String strReverse = new string(rgcReverse);\n if (strControlText == strReverse)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 430483, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 0, "selected": false, "text": "<p>Const-correct C/C++ pointer solution. Minimal operations in loop.</p>\n\n<pre><code>int IsPalindrome (const char *str)\n{\n const unsigned len = strlen(str);\n const char *end = &amp;str[len-1];\n while (str &lt; end)\n if (*str++ != *end--)\n return 0;\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 659809, "author": "Ascalonian", "author_id": 65230, "author_profile": "https://Stackoverflow.com/users/65230", "pm_score": 2, "selected": false, "text": "<p>A simple Java solution:</p>\n\n<pre><code>public boolean isPalindrome(String testString) {\n StringBuffer sb = new StringBuffer(testString);\n String reverseString = sb.reverse().toString();\n\n if(testString.equalsIgnoreCase(reverseString)) {\n return true;\n else {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 1039466, "author": "patjbs", "author_id": 79256, "author_profile": "https://Stackoverflow.com/users/79256", "pm_score": 1, "selected": false, "text": "<p>My 2c. Avoids overhead of full string reversal everytime, taking advantage of shortcircuiting to return as soon as the nature of the string is determined. Yes, you should condition your string first, but IMO that's the job of another function.</p>\n\n<p><strong>In C#</strong></p>\n\n<pre><code> /// &lt;summary&gt;\n /// Tests if a string is a palindrome\n /// &lt;/summary&gt;\n public static bool IsPalindrome(this String str)\n {\n if (str.Length == 0) return false;\n int index = 0;\n while (index &lt; str.Length / 2)\n if (str[index] != str[str.Length - ++index]) return false;\n\n return true;\n }\n</code></pre>\n" }, { "answer_id": 1039549, "author": "Matchu", "author_id": 107415, "author_profile": "https://Stackoverflow.com/users/107415", "pm_score": 2, "selected": false, "text": "<h2>Ruby:</h2>\n\n<pre><code>class String\n def is_palindrome?\n letters_only = gsub(/\\W/,'').downcase\n letters_only == letters_only.reverse\n end\nend\n\nputs 'abc'.is_palindrome? # =&gt; false\nputs 'aba'.is_palindrome? # =&gt; true\nputs \"Madam, I'm Adam.\".is_palindrome? # =&gt; true\n</code></pre>\n" }, { "answer_id": 1078441, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 0, "selected": false, "text": "<p><strong>Scala</strong></p>\n\n<pre><code>def pal(s:String) = Symbol(s) equals Symbol(s.reverse)\n</code></pre>\n" }, { "answer_id": 1115333, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><strong>Prolog</strong></p>\n</blockquote>\n\n<pre><code>palindrome(B, R) :-\npalindrome(B, R, []).\n\npalindrome([], R, R).\npalindrome([X|B], [X|R], T) :-\npalindrome(B, R, [X|T]).\n</code></pre>\n" }, { "answer_id": 2049311, "author": "Pritam Karmakar", "author_id": 208513, "author_profile": "https://Stackoverflow.com/users/208513", "pm_score": 0, "selected": false, "text": "<pre><code> public bool IsPalindrome(string s)\n {\n string formattedString = s.Replace(\" \", string.Empty).ToLower();\n for (int i = 0; i &lt; formattedString.Length / 2; i++)\n {\n if (formattedString[i] != formattedString[formattedString.Length - 1 - i])\n return false;\n }\n return true;\n }\n</code></pre>\n\n<p>This method will work for sting like \"Was it a rat I saw\". But I feel we need to eliminate special character through Regex.</p>\n" }, { "answer_id": 2751730, "author": "rockvista", "author_id": 1996230, "author_profile": "https://Stackoverflow.com/users/1996230", "pm_score": 0, "selected": false, "text": "<p>C# Version:</p>\n\n<p>Assumes MyString to be a char[], Method return after verification of the string, it ignores space and &lt;,>, but this can be extended to ignore more, probably impleemnt a regex match of ignore list.</p>\n\n<pre><code>public bool IsPalindrome()\n if (MyString.Length == 0)\n return false;\n\n int len = MyString.Length - 1;\n\n int first = 0;\n int second = 0;\n\n for (int i = 0, j = len; i &lt;= len / 2; i++, j--)\n {\n while (i&lt;j &amp;&amp; MyString[i] == ' ' || MyString[i] == ',')\n i++;\n\n while(j&gt;i &amp;&amp; MyString[j] == ' ' || MyString[j] == ',')\n j--;\n\n if ((i == len / 2) &amp;&amp; (i == j))\n return true;\n\n first = MyString[i] &gt;= 97 &amp;&amp; MyString[i] &lt;= 122 ? MyString[i] - 32 : MyString[i];\n second = MyString[j] &gt;= 97 &amp;&amp; MyString[j] &lt;= 122 ? MyString[j] - 32 : MyString[j];\n\n if (first != second)\n return false;\n }\n\n return true;\n }\n</code></pre>\n\n<p>Quick test cases</p>\n\n<p>negative\n1. ABCDA \n2. AB CBAG\n3. A#$BDA\n4. NULL/EMPTY</p>\n\n<p>positive\n1. ABCBA\n2. A, man a plan a canal,,Panama\n3. ABC BA\n4. M\n5. ACCB</p>\n\n<p>let me know any thoghts/errors.</p>\n" }, { "answer_id": 5130209, "author": "Micke", "author_id": 635969, "author_profile": "https://Stackoverflow.com/users/635969", "pm_score": 0, "selected": false, "text": "<p>How about this PHP example: </p>\n\n<pre><code>function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {\n $returnstrrev = \"returnstrrevverrtsnruter\";\n $verrtsnruter = $functionnoitcnuf;\n return (strrev ($verrtsnruter) == $functionnoitcnuf) ; \n}\n</code></pre>\n" }, { "answer_id": 5494118, "author": "Bubbles", "author_id": 631423, "author_profile": "https://Stackoverflow.com/users/631423", "pm_score": 0, "selected": false, "text": "<pre><code>public static boolean isPalindrome( String str ) {\n int count = str.length() ;\n int i, j = count - 1 ;\n for ( i = 0 ; i &lt; count ; i++ ) {\n if ( str.charAt(i) != str.charAt(j) ) return false ;\n if ( i == j ) return true ;\n j-- ;\n }\n return true ;\n}\n</code></pre>\n" }, { "answer_id": 8181718, "author": "Ram", "author_id": 50418, "author_profile": "https://Stackoverflow.com/users/50418", "pm_score": 1, "selected": false, "text": "<p>Erlang is awesome</p>\n\n<pre><code>palindrome(L) -&gt; palindrome(L,[]).\n\npalindrome([],_) -&gt; false;\npalindrome([_|[]],[]) -&gt; true;\npalindrome([_|L],L) -&gt; true;\npalindrome(L,L) -&gt; true;\npalindrome([H|T], Acc) -&gt; palindrome(T, [H|Acc]).\n</code></pre>\n" }, { "answer_id": 8672758, "author": "Mushimo", "author_id": 456206, "author_profile": "https://Stackoverflow.com/users/456206", "pm_score": 1, "selected": false, "text": "<p>No solution using JavaScript yet?</p>\n\n<pre><code>function palindrome(s) {\n var l = 0, r = s.length - 1;\n while (l &lt; r) if (s.charAt(left++) !== s.charAt(r--)) return false;\n return true\n}\n</code></pre>\n" }, { "answer_id": 8733562, "author": "Justin", "author_id": 950252, "author_profile": "https://Stackoverflow.com/users/950252", "pm_score": 0, "selected": false, "text": "<p>If you can use Java APIs and additional storage:</p>\n\n<pre><code>public static final boolean isPalindromeWithAdditionalStorage(String string) {\n String reversed = new StringBuilder(string).reverse().toString();\n return string.equals(reversed);\n}\n</code></pre>\n\n<p>In can need an in-place method for Java:</p>\n\n<pre><code>public static final boolean isPalindromeInPlace(String string) {\n char[] array = string.toCharArray();\n int length = array.length-1;\n int half = Math.round(array.length/2);\n char a,b;\n for (int i=length; i&gt;=half; i--) {\n a = array[length-i];\n b = array[i];\n if (a != b) return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 9305682, "author": "melsk", "author_id": 809694, "author_profile": "https://Stackoverflow.com/users/809694", "pm_score": 0, "selected": false, "text": "<p><b>Regular Approach:</b></p>\n\n<pre><code>flag = True // Assume palindrome is true\nfor i from 0 to n/2 \n { compare element[i] and element[n-i-1] // 0 to n-1\n if not equal set flag = False\n break }\nreturn flag\n</code></pre>\n\n<p>There is a better machine optimized method which uses XORs but has the same complexity <br/><br/>\n<b>XOR approach</b>:</p>\n\n<pre><code>n = length of string\nmid_element = element[n/2 +1]\nfor i from 0 to n\n{ t_xor = element[i] xor element[i+1] }\nif n is odd compare mid_element and t_xor\nelse check t_xor is zero\n</code></pre>\n" }, { "answer_id": 14772912, "author": "user2039532", "author_id": 2039532, "author_profile": "https://Stackoverflow.com/users/2039532", "pm_score": 0, "selected": false, "text": "<pre><code>public class palindrome {\npublic static void main(String[] args) {\n StringBuffer strBuf1 = new StringBuffer(\"malayalam\");\n StringBuffer strBuf2 = new StringBuffer(\"malayalam\");\n strBuf2.reverse();\n\n\n System.out.println(strBuf2);\n System.out.println((strBuf1.toString()).equals(strBuf2.toString()));\n if ((strBuf1.toString()).equals(strBuf2.toString()))\n System.out.println(\"palindrome\");\n else\n System.out.println(\"not a palindrome\");\n }\n} \n</code></pre>\n" }, { "answer_id": 14906430, "author": "Rhys Ulerich", "author_id": 103640, "author_profile": "https://Stackoverflow.com/users/103640", "pm_score": 0, "selected": false, "text": "<p>A case-insensitive, <code>const</code>-friendly version in plain C that ignores non-alphanumeric characters (e.g. whitespace / punctuation). It therefore will actually pass on classics like \"A man, a plan, a canal, Panama\".</p>\n\n<pre><code>int ispalin(const char *b)\n{\n const char *e = b;\n while (*++e);\n while (--e &gt;= b)\n {\n if (isalnum(*e))\n {\n while (*b &amp;&amp; !isalnum(*b)) ++b;\n if (toupper(*b++) != toupper(*e)) return 0;\n }\n }\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 19893643, "author": "Adrian Bratu", "author_id": 1161008, "author_profile": "https://Stackoverflow.com/users/1161008", "pm_score": 0, "selected": false, "text": "<p>The interviewer will be looking for some logic on how you will be approaching this problem:\nPlease consider the following java code:</p>\n\n<ol>\n<li>always check if the input string is null</li>\n<li>check your base cases.</li>\n<li>format your string accordingly (remove anything that is not a character/digit</li>\n<li>Most likely they do not want to see if you know the reverse function, and a comparison, but rather if you are able to answer the question using a loop and indexing.</li>\n<li><p>shortcut return as soon as you know your answer and do not waste resources for nothing.</p>\n\n<p>public static boolean isPalindrome(String s) {</p>\n\n<pre><code>if (s == null || s.length() == 0 || s.length() == 1)\n return false;\n\nString ss = s.toLowerCase().replaceAll(\"/[^a-z]/\", \"\");\n\nfor (int i = 0; i &lt; ss.length()/2; i++) \n if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i))\n return false;\nreturn true;\n</code></pre>\n\n<p>}</p></li>\n</ol>\n" }, { "answer_id": 23638086, "author": "sam_rox", "author_id": 3577754, "author_profile": "https://Stackoverflow.com/users/3577754", "pm_score": 0, "selected": false, "text": "<p>Java with stacks.</p>\n\n<pre><code>public class StackPalindrome {\n public boolean isPalindrome(String s) throws OverFlowException,EmptyStackException{\n boolean isPal=false;\n String pal=\"\";\n char letter;\n if (s==\" \")\n return true;\n else{ \n s=s.toLowerCase();\n for(int i=0;i&lt;s.length();i++){\n\n letter=s.charAt(i);\n\n char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};\n for(int j=0; j&lt;alphabet.length;j++){\n /*removing punctuations*/\n if ((String.valueOf(letter)).equals(String.valueOf(alphabet[j]))){\n pal +=letter;\n }\n\n }\n\n }\n int len=pal.length();\n char[] palArray=new char[len];\n for(int r=0;r&lt;len;r++){\n palArray[r]=pal.charAt(r);\n }\n ArrayStack palStack=new ArrayStack(len);\n for(int k=0;k&lt;palArray.length;k++){\n palStack.push(palArray[k]);\n }\n for (int i=0;i&lt;len;i++){\n\n if ((palStack.topAndpop()).equals(palArray[i]))\n isPal=true;\n else \n isPal=false;\n }\n return isPal;\n }\n}\npublic static void main (String args[]) throws EmptyStackException,OverFlowException{\n\n StackPalindrome s=new StackPalindrome();\n System.out.println(s.isPalindrome(\"“Ma,” Jerome raps pot top, “Spare more jam!”\"));\n}\n</code></pre>\n" }, { "answer_id": 24759363, "author": "Pavan tej", "author_id": 2063399, "author_profile": "https://Stackoverflow.com/users/2063399", "pm_score": 0, "selected": false, "text": "<pre><code>//Single program for Both String or Integer to check palindrome\n\n//In java with out using string functions like reverse and equals method also and display matching characters also\n\npackage com.practice;\n\nimport java.util.Scanner;\n\npublic class Pallindrome {\n\n public static void main(String args[]) {\n Scanner sc=new Scanner(System.in);\n int i=0,j=0,k,count=0;\n String input,temp;\n System.out.println(\"Enter the String or Integer\");\n input=sc.nextLine();\n temp=input;\n k=temp.length()-1;\n for(i=0;i&lt;=input.length()-1;i++) {\n if(input.charAt(j)==temp.charAt(k)) {\n count++;\n }\n //For matching characters\n j++;\n k--;\n }\n System.out.println(\"Matching Characters = \"+count);\n\n if(count==input.length()) {\n System.out.println(\"It's a pallindrome\");\n }\n else {\n System.out.println(\"It's not a pallindrome\");\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 29174567, "author": "arsho", "author_id": 3129414, "author_profile": "https://Stackoverflow.com/users/3129414", "pm_score": 1, "selected": false, "text": "<p>Simple <strong>JavaScript</strong> solution. Run code snippet for demo.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function checkPalindrome(line){\r\n reverse_line=line.split(\"\").reverse().join(\"\");\r\n return line==reverse_line;\r\n }\r\nalert(\"checkPalindrome(radar): \"+checkPalindrome(\"radar\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 29587590, "author": "Confuse", "author_id": 3886922, "author_profile": "https://Stackoverflow.com/users/3886922", "pm_score": 0, "selected": false, "text": "<pre><code>public static boolean isPalindrome(String str) {\n return str.equals(new StringBuilder(str).reverse().toString());\n}\n</code></pre>\n\n<p>for versions of Java earlier than 1.5,</p>\n\n<pre><code>public static boolean isPalindrome(String str) {\n return str.equals(new StringBuffer().append(str).reverse().toString());\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public static boolean istPalindrom(char[] word){\n int i1 = 0;\n int i2 = word.length - 1;\n while (i2 &gt; i1) {\n if (word[i1] != word[i2]) {\n return false;\n }\n ++i1;\n --i2;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 32550261, "author": "mockee", "author_id": 468712, "author_profile": "https://Stackoverflow.com/users/468712", "pm_score": 0, "selected": false, "text": "<pre><code>// JavaScript Version.\nfunction isPalindrome(str) { \n str = str.replace(/[^a-zA-Z]/g, '')\n return str.split('').reverse().join('').toUpperCase() === str.toUpperCase() \n}\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I need to design a small project for generating excel reports in .NET, which will be sent to users to use. The excel reports will contain PivotTables. I don't have much experience with them, but I can think of three implementation alternatives: 1. Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data. 2. Generate a small access database and send it along with the excel file, connect to it. 3. Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think. What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?
**PHP sample**: ``` $string = "A man, a plan, a canal, Panama"; function is_palindrome($string) { $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string)); return $a==strrev($a); } ``` Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.
52,080
<p>How can I build a loop in JavaScript?</p>
[ { "answer_id": 52083, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<p>A loop in JavaScript looks like this:</p>\n\n<pre><code>for (var = startvalue; var &lt;= endvalue; var = var + increment) {\n // code to be executed\n}\n</code></pre>\n" }, { "answer_id": 52088, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 1, "selected": false, "text": "<p>Here is an example of a for loop:</p>\n\n<p>We have an array of items <strong>nodes</strong>.</p>\n\n<pre><code>for(var i = 0; i&lt; nodes.length; i++){\n var node = nodes[i];\n alert(node);\n}\n</code></pre>\n" }, { "answer_id": 52101, "author": "georgebrock", "author_id": 5168, "author_profile": "https://Stackoverflow.com/users/5168", "pm_score": 6, "selected": true, "text": "<p><strong>For loops</strong></p>\n\n<pre><code>for (i = startValue; i &lt;= endValue; i++) {\n // Before the loop: i is set to startValue\n // After each iteration of the loop: i++ is executed\n // The loop continues as long as i &lt;= endValue is true\n}\n</code></pre>\n\n<p><strong>For...in loops</strong></p>\n\n<pre><code>for (i in things) {\n // If things is an array, i will usually contain the array keys *not advised*\n // If things is an object, i will contain the member names\n // Either way, access values using: things[i]\n}\n</code></pre>\n\n<p>It is bad practice to use <code>for...in</code> loops to itterate over arrays. It goes against the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">ECMA 262</a> standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by <a href=\"http://www.prototypejs.org/api/array\" rel=\"noreferrer\">Prototype</a>.\n<em>(Thanks to <a href=\"https://stackoverflow.com/users/7679/chase-seibert\">Chase Seibert</a> for pointing this out in the comments)</em></p>\n\n<p><strong>While loops</strong></p>\n\n<pre><code>while (myCondition) {\n // The loop will continue until myCondition is false\n}\n</code></pre>\n" }, { "answer_id": 32355895, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "<p>Aside form the build-in loops (<code>while() ...</code>, <code>do ... while()</code>, <code>for() ...</code>), there is a structure of self calling function, also known as <strong>recursion</strong> to create a loop without the three build-in loop structures.</p>\n\n<p>Consider the following:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// set the initial value\r\nvar loopCounter = 3;\r\n\r\n// the body of the loop\r\nfunction loop() {\r\n\r\n // this is only to show something, done in the loop\r\n document.write(loopCounter + '&lt;br&gt;');\r\n\r\n // decrease the loopCounter, to prevent running forever\r\n loopCounter--;\r\n\r\n // test loopCounter and if truthy call loop() again \r\n loopCounter &amp;&amp; loop();\r\n}\r\n\r\n// invoke the loop\r\nloop();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Needless to say that this structure is often used in combination with a return value, so this is a small example how to deal with value that is not in the first time available, but at the end of the recursion:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function f(n) {\r\n // return values for 3 to 1\r\n // n -n ~-n !~-n +!~-n return\r\n // conv int neg bitnot not number \r\n // 3 -3 2 false 0 3 * f(2)\r\n // 2 -2 1 false 0 2 * f(1)\r\n // 1 -1 0 true 1 1\r\n // so it takes a positive integer and do some conversion like changed sign, apply\r\n // bitwise not, do logical not and cast it to number. if this value is then\r\n // truthy, then return the value. if not, then return the product of the given\r\n // value and the return value of the call with the decreased number\r\n return +!~-n || n * f(n - 1);\r\n}\r\n\r\ndocument.write(f(7));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
How can I build a loop in JavaScript?
**For loops** ``` for (i = startValue; i <= endValue; i++) { // Before the loop: i is set to startValue // After each iteration of the loop: i++ is executed // The loop continues as long as i <= endValue is true } ``` **For...in loops** ``` for (i in things) { // If things is an array, i will usually contain the array keys *not advised* // If things is an object, i will contain the member names // Either way, access values using: things[i] } ``` It is bad practice to use `for...in` loops to itterate over arrays. It goes against the [ECMA 262](http://www.ecma-international.org/publications/standards/Ecma-262.htm) standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by [Prototype](http://www.prototypejs.org/api/array). *(Thanks to [Chase Seibert](https://stackoverflow.com/users/7679/chase-seibert) for pointing this out in the comments)* **While loops** ``` while (myCondition) { // The loop will continue until myCondition is false } ```
52,084
<p>There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG. </p> <pre><code>&lt;contact&gt; &lt;refno&gt;123456&lt;/refno&gt; &lt;special&gt;a piece of custom data&lt;/special&gt; &lt;/contact&gt; </code></pre> <p>The tags below <code>contact</code> can be different for each contact, and I must query these fragments alongside the relational data columns in the same table.</p> <p>I have used constructions like:</p> <pre><code>SELECT c.id AS ContactID,c.ContactName as ForeName, c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref, INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid AND pcm.participantid=2140 WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1 </code></pre> <p>This method works ok but, it takes a while for the Server to respond. I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for.</p> <p>Does anyone know a better way to query XML columns??</p>
[ { "answer_id": 52097, "author": "Paulj", "author_id": 5433, "author_profile": "https://Stackoverflow.com/users/5433", "pm_score": 2, "selected": true, "text": "<p>I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration...\n<a href=\"http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4</a></p>\n" }, { "answer_id": 52152, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>In addition to the page mentioned by @pauljette, this page has good performance optimization advice:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms345118.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms345118.aspx</a></p>\n\n<p>There's a lot you can do to speed up the performance of XML queries, but it will never be as good as properly indexed relational data. If you are selecting one document and then querying inside just that one, you can do pretty well, but when your query needs to scan through a bunch of similar documents looking for something, it's sort of like a key lookup in a relational query plan (that is, <em>slow</em>).</p>\n" }, { "answer_id": 52464, "author": "Tina Marie", "author_id": 4666, "author_profile": "https://Stackoverflow.com/users/4666", "pm_score": 2, "selected": false, "text": "<p>If you are doing one write and a lot of reads, take the parsing hit at write time, and get that data into some format that is more query-able. A first suggestion would be to parse them into a related but separate table, with name/value/contactID columns.</p>\n" }, { "answer_id": 60377, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 0, "selected": false, "text": "<p>If you have a XSD for your Xml then you can import that into your database and you can then build indexes for your Xml data.</p>\n" }, { "answer_id": 21453759, "author": "Shailesh", "author_id": 1241943, "author_profile": "https://Stackoverflow.com/users/1241943", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<p>SELECT * FROM conversionupdatelog WHERE \nconvert(XML,colName).value('(/leads/lead/@LeadID=''[email protected]'')[1]', 'varchar(max)')='true'</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197/" ]
There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG. ``` <contact> <refno>123456</refno> <special>a piece of custom data</special> </contact> ``` The tags below `contact` can be different for each contact, and I must query these fragments alongside the relational data columns in the same table. I have used constructions like: ``` SELECT c.id AS ContactID,c.ContactName as ForeName, c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref, INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid AND pcm.participantid=2140 WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1 ``` This method works ok but, it takes a while for the Server to respond. I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for. Does anyone know a better way to query XML columns??
I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration... <http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4>
52,160
<p>How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?</p> <p>i.e. something like:</p> <pre><code>If Typeof(foobar) = "CommandButton" Then ... </code></pre> <p><strong>/EDIT:</strong> to clarify, I need to check on Dynamically Typed objects. An example:</p> <pre><code>Dim y As Object Set y = CreateObject("SomeType") Debug.Print( &lt;The type name of&gt; y) </code></pre> <p>Where the output would be "CommandButton"</p>
[ { "answer_id": 52181, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "<p>This should prove difficult, since in VB6 all objects are COM (<code>IDispatch</code>) things. Thus they are only an interface.</p>\n\n<p><code>TypeOf(object) is class</code> probably only does a COM get_interface call (I forgot the exact method name, sorry).</p>\n" }, { "answer_id": 52243, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 4, "selected": true, "text": "<p>I think what you are looking for is TypeName rather than TypeOf.</p>\n\n<pre><code>If TypeName(foobar) = \"CommandButton\" Then\n DoSomething\nEnd If\n</code></pre>\n\n<p>Edit: What do you mean Dynamic Objects? Do you mean objects created with\nCreateObject(\"\"), cause that should still work.</p>\n\n<p>Edit: </p>\n\n<pre><code>Private Sub Command1_Click()\n Dim oObject As Object\n Set oObject = CreateObject(\"Scripting.FileSystemObject\")\n Debug.Print \"Object Type: \" &amp; TypeName(oObject)\nEnd Sub\n</code></pre>\n\n<p>Outputs</p>\n\n<p><code>Object Type: FileSystemObject</code></p>\n" }, { "answer_id": 52255, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "<p>I don't have a copy of VB6 to hand, but I think you need the </p>\n\n<pre><code>Typename()\n</code></pre>\n\n<p>function... I can see it in Excel VBA, so it's probably in the same runtime. Interestingly, the help seems to suggest that it shouldn't work for a user-defined type, but that's about the only way I ever <em>do</em> use it.</p>\n\n<p>Excerpt from the help file:</p>\n\n<blockquote>\n <p>TypeName Function</p>\n \n <p>Returns a String that provides information about a variable.</p>\n \n <p>Syntax</p>\n \n <p>TypeName(varname)</p>\n \n <p>The required varname argument is a\n Variant containing any variable except\n a variable of a user-defined type.</p>\n</blockquote>\n" }, { "answer_id": 156240, "author": "sharvell", "author_id": 23095, "author_profile": "https://Stackoverflow.com/users/23095", "pm_score": 2, "selected": false, "text": "<p>TypeName is what you want... Here is some example output:</p>\n\n<p>VB6 Code:</p>\n\n<pre><code>Private Sub cmdCommand1_Click()\nDim a As Variant\nDim b As Variant\nDim c As Object\nDim d As Object\nDim e As Boolean\n\na = \"\"\nb = 3\nSet c = Me.cmdCommand1\nSet d = CreateObject(\"Project1.Class1\")\ne = False\n\nDebug.Print TypeName(a)\nDebug.Print TypeName(b)\nDebug.Print TypeName(c)\nDebug.Print TypeName(d)\nDebug.Print TypeName(e)\nEnd Sub\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>String\nInteger\nCommandButton\nClass1\nBoolean\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime? i.e. something like: ``` If Typeof(foobar) = "CommandButton" Then ... ``` **/EDIT:** to clarify, I need to check on Dynamically Typed objects. An example: ``` Dim y As Object Set y = CreateObject("SomeType") Debug.Print( <The type name of> y) ``` Where the output would be "CommandButton"
I think what you are looking for is TypeName rather than TypeOf. ``` If TypeName(foobar) = "CommandButton" Then DoSomething End If ``` Edit: What do you mean Dynamic Objects? Do you mean objects created with CreateObject(""), cause that should still work. Edit: ``` Private Sub Command1_Click() Dim oObject As Object Set oObject = CreateObject("Scripting.FileSystemObject") Debug.Print "Object Type: " & TypeName(oObject) End Sub ``` Outputs `Object Type: FileSystemObject`
52,213
<p>When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.</p> <p>Is there a way, in HTTP headers or equivalents, to change this behaviour?</p>
[ { "answer_id": 52221, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 2, "selected": false, "text": "<p>You could call the reset() method of the forms object from the body load event of your html document to clear the forms.</p>\n\n<p>h1. References</p>\n\n<ul>\n<li>MSDN reset Method - <a href=\"http://msdn.microsoft.com/en-us/library/ms536721(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms536721(VS.85).aspx</a></li>\n<li><a href=\"http://developer.mozilla.org/en/DOM/form.reset\" rel=\"nofollow noreferrer\">Mozilla developer center form.reset</a></li>\n</ul>\n" }, { "answer_id": 52225, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 0, "selected": false, "text": "<p>I wonder, if you set the page not to be cached through meta tags, will that fix the problem? <a href=\"http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html\" rel=\"nofollow noreferrer\">http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html</a> If it does, it'll have the benefit of working on browser's with Javascript disabled.</p>\n" }, { "answer_id": 52226, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 6, "selected": true, "text": "<pre><code>&lt;input autocomplete=\"off\"&gt;\n</code></pre>\n" }, { "answer_id": 52229, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p>This should do the trick:</p>\n\n<pre><code>&lt;body onload=\"document.FormName.reset();\"&gt;\n</code></pre>\n\n<p>Replace FormName with the name of your form and then all the fields will be reset when the user clicks refresh in his browser.</p>\n\n<p>Or if you only want to reset some fields, add this to the bottom of your page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n document.getElementById('field1').value ='';\n document.getElementById('field2').value ='';\n document.getElementById('field3').value ='';\n&lt;/script&gt;\n</code></pre>\n\n<p>That will reset the fields every time a user enters the page, including refreshes</p>\n" }, { "answer_id": 86505, "author": "ThoriumBR", "author_id": 16545, "author_profile": "https://Stackoverflow.com/users/16545", "pm_score": 0, "selected": false, "text": "<p>The data on forms are not part of w3c specification. It's a browser feature to make your life easy. So, if you don't want to keep the data after reloads, you can set all form's values to null after loading it, as Espo said.\nEven if the page is not cached, it will display the data on the form, because the data aren't part of the page's html code.\nYou can try this too (don't know if it will work):</p>\n\n<pre><code>&lt;input type=\"text\" name=\"foo\" value=\"\"&gt;\n</code></pre>\n" }, { "answer_id": 1812985, "author": "Fabien", "author_id": 21132, "author_profile": "https://Stackoverflow.com/users/21132", "pm_score": 2, "selected": false, "text": "<p>Add the autocomplete attribute set to \"off\" to the inputs you don't want to be refreshed.\nFor instance:</p>\n\n<pre><code>&lt;input type=\"text\" name=\"pin\" autocomplete=\"off\" /&gt;\n</code></pre>\n\n<p>see\n<a href=\"http://www.w3.org/Submission/web-forms2/#the-autocomplete\" rel=\"nofollow noreferrer\">the W3C reference</a></p>\n\n<p>although not mentioned in the reference, it works also with checkboxes, at least on firefox.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000/" ]
When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience. Is there a way, in HTTP headers or equivalents, to change this behaviour?
``` <input autocomplete="off"> ```
52,234
<p>Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?</p> <p>If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?</p>
[ { "answer_id": 52242, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 7, "selected": true, "text": "<pre><code>tf diff /shelveset:shelveset /format:unified\n</code></pre>\n\n<p><strong>Edit:</strong> This writes to standard output. You can pipe the output to a file.</p>\n\n<p>For more options, see <a href=\"http://msdn.microsoft.com/en-us/library/6fd7dc73%28v=vs.100%29.aspx\" rel=\"noreferrer\">Difference Command</a>.</p>\n" }, { "answer_id": 80807, "author": "jwanagel", "author_id": 15118, "author_profile": "https://Stackoverflow.com/users/15118", "pm_score": 2, "selected": false, "text": "<p>Because TFS doesn't natively support patch files, the most common thing I see people do on CodePlex is simply zip the modified files and upload the zip. The project coordinator then does a diff against their own checkout.</p>\n\n<p>However since CodePlex also supports TortoiseSVN, more and more people are using that to create their patch files.</p>\n" }, { "answer_id": 25836689, "author": "Greg Bray", "author_id": 17373, "author_profile": "https://Stackoverflow.com/users/17373", "pm_score": 0, "selected": false, "text": "<p>I wrote a blog post about a similar issue where I used the TF.exe command and 7Zip to <a href=\"http://codeblog.theg2.net/2014/09/create-tfs-patch-file-with-pending.html\" rel=\"nofollow\">create a TFS patch file</a> that could then be applied on another TFS server or workspace. I posted the the Powershell scripts at <a href=\"https://github.com/gbrayut/CodeBlog/tree/master/20140914_TFS\" rel=\"nofollow\">Github</a>, which can be used to Zip up any pending changes on one workspace and then apply them to a different server. It would have to be modified to use a changeset instead of pending changes, but that shouldn't be too difficult to accomplish.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible? If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?
``` tf diff /shelveset:shelveset /format:unified ``` **Edit:** This writes to standard output. You can pipe the output to a file. For more options, see [Difference Command](http://msdn.microsoft.com/en-us/library/6fd7dc73%28v=vs.100%29.aspx).
52,238
<p>How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?</p> <p>An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.</p>
[ { "answer_id": 52250, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": false, "text": "<p>You can use Prototype's <code>addClassName</code> and <code>removeClassName</code> methods.</p>\n\n<p>Create a CSS class \"hilight\" that you'll apply to the hilighted <code>&lt;tr&gt;</code>'s. Then run this code on page load:</p>\n\n<pre><code>var rows = $$('tbody tr'); \nfor (var i = 0; i &lt; rows.length; i++) { \n rows[i].onmouseover = function() { $(this).addClassName('hilight'); } \n rows[i].onmouseout = function() { $(this).removeClassName('hilight'); } \n}\n</code></pre>\n" }, { "answer_id": 52253, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;table id=\"mytable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;Foo&lt;/td&gt;&lt;td&gt;Bar&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Bork&lt;/td&gt;&lt;td&gt;Bork&lt;/td&gt;&lt;/tr&gt;\n\n &lt;/tbody&gt;\n&lt;/table&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n\n$$('#mytable tr').each(function(item) {\n item.observe('mouseover', function() {\n item.setStyle({ backgroundColor: '#ddd' });\n });\n item.observe('mouseout', function() {\n item.setStyle({backgroundColor: '#fff' });\n });\n});\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 52258, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 1, "selected": false, "text": "<p>You can do something to each row, like so:</p>\n\n<pre><code>$('tableId').getElementsBySelector('tr').each(function (row) {\n ...\n});\n</code></pre>\n\n<p>So, in the body of that function, you have access to each row, one at a time, in the 'row' variable. You can then call Event.observe(row, ...)</p>\n\n<p>So, something like this might work:</p>\n\n<pre><code>$('tableId').getElementsBySelector('tr').each(function (row) {\n Event.observe(row, 'mouseover', function () {...do hightlight code...});\n});\n</code></pre>\n" }, { "answer_id": 52273, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "<p>I made a slight change to <a href=\"https://stackoverflow.com/questions/52238/how-can-i-highlight-a-table-row-using-prototype#52253\">@swilliams</a> code.</p>\n\n<pre><code>$$('#thetable tr:not(#headRow)').each(\n</code></pre>\n\n<p>This lets me have a table with a header row that <strong>doesn't</strong> get highlighted.</p>\n\n<pre><code>&lt;tr id=\"headRow\"&gt;\n &lt;th&gt;Header 1&lt;/th&gt;\n&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 143014, "author": "Fczbkk", "author_id": 22920, "author_profile": "https://Stackoverflow.com/users/22920", "pm_score": 2, "selected": false, "text": "<p>A little bit generic solution:</p>\n\n<p>Let's say I want to have a simple way to make tables with rows that will highlight when I put mouse pointer over them. In ideal world this would be very easy, with just one simple CSS rule:</p>\n\n<pre><code>tr:hover { background: red; }\n</code></pre>\n\n<p>Unfortunately, older versions of IE don't support :hover selector on elements other than A. So we have to use JavaScript.</p>\n\n<p>In that case, I will define a table class \"highlightable\" to mark tables that should have hoverable rows. I will make the background switching by adding and removing the class \"highlight\" on the table row.</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>table.highlightable tr.highlight { background: red; }\n</code></pre>\n\n<p><strong>JavaScript (using Prototype)</strong></p>\n\n<pre><code>// when document loads\ndocument.observe( 'dom:loaded', function() {\n // find all rows in highlightable table\n $$( 'table.highlightable tr' ).each( function( row ) {\n // add/remove class \"highlight\" when mouse enters/leaves\n row.observe( 'mouseover', function( evt ) { evt.element().addClassName( 'highlight' ) } );\n row.observe( 'mouseout', function( evt ) { evt.element().removeClassName( 'highlight' ) } );\n } );\n} )\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<p>All you have to do now is to add class \"highlightable\" to any table you want:</p>\n\n<pre><code>&lt;table class=\"highlightable\"&gt;\n ...\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 2371048, "author": "Zloi", "author_id": 285270, "author_profile": "https://Stackoverflow.com/users/285270", "pm_score": 0, "selected": false, "text": "<p>I found ab interesting solution for Rows background, the rows highlighting on mouse over, without JS. Here is <a href=\"http://www.sopov.com/joomla-wordpress-tips-and-tricks/70-how-highlight-table-row-background.html\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>Works in all browsers. For IE6/7/8 ...</p>\n\n<pre><code>tr{ position: relative; }\ntd{ background-image: none } \n</code></pre>\n\n<p>And for Safari I use negative background position for each TD.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3920/" ]
How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag? An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.
``` <table id="mytable"> <tbody> <tr><td>Foo</td><td>Bar</td></tr> <tr><td>Bork</td><td>Bork</td></tr> </tbody> </table> <script type="text/javascript"> $$('#mytable tr').each(function(item) { item.observe('mouseover', function() { item.setStyle({ backgroundColor: '#ddd' }); }); item.observe('mouseout', function() { item.setStyle({backgroundColor: '#fff' }); }); }); </script> ```
52,239
<p>We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords?</p>
[ { "answer_id": 52244, "author": "Paul Hargreaves", "author_id": 5330, "author_profile": "https://Stackoverflow.com/users/5330", "pm_score": 6, "selected": true, "text": "<p>Have you tried logging into Linux as your installed Oracle user then</p>\n\n<pre><code>sqlplus \"/ as sysdba\"\n</code></pre>\n\n<p>When you log in you'll be able to change your password.</p>\n\n<pre><code>alter user sys identified by &lt;new password&gt;;\n</code></pre>\n\n<p>Good luck :)</p>\n" }, { "answer_id": 34349844, "author": "Lalit Kumar B", "author_id": 3989608, "author_profile": "https://Stackoverflow.com/users/3989608", "pm_score": 1, "selected": false, "text": "<p>You can connect to the database locally using the combination of environment variables:</p>\n\n<ul>\n<li><strong>ORACLE_HOME</strong> </li>\n<li><strong>ORACLE_SID</strong> .</li>\n</ul>\n\n<p>Depending on your <strong>OS</strong>:</p>\n\n<p><strong>Unix/Linux:</strong></p>\n\n<pre><code>export ORACLE_HOME=&lt;oracle_home_directory_till_db_home&gt;\nexport PATH=$PATH:$ORACLE_HOME/bin\nexport ORACLE_SID=&lt;your_oracle_sid&gt;\nSQLPLUS / AS SYSDBA\n</code></pre>\n\n<p><strong>Windows</strong></p>\n\n<pre><code>set ORACLE_HOME=&lt;oracle_home_path_till_db_home&gt;\nset PATH=%PATH%||%ORACLE_HOME%\\bin\nset ORACLE_SID=&lt;your_oracle_sid&gt;\nSQLPLUS / AS SYSDBA\n</code></pre>\n\n<p>Once connected, you could then <strong>alter the user</strong> to <strong>modify the password</strong>:</p>\n\n<pre><code>ALTER USER username IDENTIFIED BY password;\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords?
Have you tried logging into Linux as your installed Oracle user then ``` sqlplus "/ as sysdba" ``` When you log in you'll be able to change your password. ``` alter user sys identified by <new password>; ``` Good luck :)
52,286
<p>Wrote the following in PowersHell as a quick iTunes demonstration:</p> <pre><code>$iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource foreach ($PList in $LibrarySource.Playlists) { write-host $PList.name } </code></pre> <p>This works well and pulls back a list of playlist names. However on trying to close iTunes a warning appears</p> <blockquote> <p>One or more applications are using the iTunes scripting interface. Are you sure you want to quit?</p> </blockquote> <p>Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?</p> <pre><code>Itunes 7.7.1, Windows XP </code></pre>
[ { "answer_id": 52309, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 3, "selected": true, "text": "<p>Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.</p>\n\n<pre><code>\n [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)\n [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)\n</code></pre>\n\n<p>I also run my scripts the majority of time from a shortcut, not from the powershell prompt. </p>\n\n<p>Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message.</p>\n\n<p>One method of running your script from powershell, is to prefix your script with powershell.</p>\n\n<pre><code>powershell .\\scriptname.ps1</code></pre>\n\n<p>The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.</p>\n" }, { "answer_id": 54003, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 0, "selected": false, "text": "<p>You should be able to set $itunes to $null. Alternatively, $itunes should have a quit method you can call. $itunes.quit()</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330/" ]
Wrote the following in PowersHell as a quick iTunes demonstration: ``` $iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource foreach ($PList in $LibrarySource.Playlists) { write-host $PList.name } ``` This works well and pulls back a list of playlist names. However on trying to close iTunes a warning appears > > One or more applications are using the iTunes scripting interface. Are you sure you want to quit? > > > Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it? ``` Itunes 7.7.1, Windows XP ```
Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET. ``` [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource) [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes) ``` I also run my scripts the majority of time from a shortcut, not from the powershell prompt. Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message. One method of running your script from powershell, is to prefix your script with powershell. ``` powershell .\scriptname.ps1 ``` The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.
52,313
<p>This question is kind of an add-on to this <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why">question</a></p> <p>In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) </p> <pre><code>switch (month) { case 0: add something to month totals case 1: add something to month totals case 2: add something to month totals default: break; } </code></pre> <p>Is there a logical alternative to this in C# without having to write out a ton of if statements?</p> <pre><code>if (month &lt;= 0) add something to month if (month &lt;= 1) add something to month if (month &lt;= 2) add something to month .... etc </code></pre>
[ { "answer_id": 52314, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "<p>There is already a question addressing this topic:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why\">C# switch statement limitations - why?</a></p>\n\n<p>EDIT:</p>\n\n<p>My main purpose in pointing that out, gentlebeasts, is that two questions of near-identical name add confusion to the pool of questions. </p>\n" }, { "answer_id": 52318, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 5, "selected": true, "text": "<p>Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design.</p>\n\n<p>Instead, what if you implemented the Specification pattern to see if something matched, and then act on it?</p>\n\n<pre><code>foreach(MonthSpecification spec in this.MonthSpecifications)\n{\n if(spec.IsSatisfiedBy(month))\n spec.Perform(month);\n}\n</code></pre>\n\n<p>then you can just add up different specs that match what you're trying to do.</p>\n\n<p>It's hard to tell what your domain is, so my example might be a little contrived.</p>\n" }, { "answer_id": 52323, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>Are you adding constants? If so, maybe something like this would work(C syntax):</p>\n\n<pre><code>const int addToTotals[] = {123, 456, ..., 789};\n\nfor(i=month;i&lt;12;i++)\n totals += addToTotals[i];\n</code></pre>\n\n<p>You can do a similar thing with variable or function pointers if you need more complex statements than add constant to totals for each month following.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 52388, "author": "jwarzech", "author_id": 3111, "author_profile": "https://Stackoverflow.com/users/3111", "pm_score": 3, "selected": false, "text": "<p>In C# switch statements you can fall through cases only if there is no statement for the case you want to fall through</p>\n\n<pre><code>switch(myVar)\n{\n case 1:\n case 2: // Case 1 or 2 get here\n break;\n}\n</code></pre>\n\n<p>However if you want to fall through with a statement you must use the dreaded GOTO</p>\n\n<pre><code>switch(myVar)\n {\n case 1: // Case 1 statement\n goto case 2;\n case 2: // Case 1 or 2 get here\n break;\n }\n</code></pre>\n" }, { "answer_id": 2564325, "author": "svv", "author_id": 307360, "author_profile": "https://Stackoverflow.com/users/307360", "pm_score": 0, "selected": false, "text": "<p>Write the switch cases in reverse order</p>\n\n<pre><code>case 2:\n\ncase 1:\n\ncase 0:\n\nbreak;\n\n\ndefault:\n</code></pre>\n\n<p>Hope that helps!</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4144/" ]
This question is kind of an add-on to this [question](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why) In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) ``` switch (month) { case 0: add something to month totals case 1: add something to month totals case 2: add something to month totals default: break; } ``` Is there a logical alternative to this in C# without having to write out a ton of if statements? ``` if (month <= 0) add something to month if (month <= 1) add something to month if (month <= 2) add something to month .... etc ```
Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design. Instead, what if you implemented the Specification pattern to see if something matched, and then act on it? ``` foreach(MonthSpecification spec in this.MonthSpecifications) { if(spec.IsSatisfiedBy(month)) spec.Perform(month); } ``` then you can just add up different specs that match what you're trying to do. It's hard to tell what your domain is, so my example might be a little contrived.
52,315
<p>We have some input data that sometimes appears with &amp;nbsp characters on the end.</p> <p>The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.</p> <p>Ltrim and Rtrim don't remove the characters, so we're forced to do something like:</p> <pre><code>UPDATE myTable SET myColumn = replace(myColumn,char(160),'') WHERE charindex(char(160),myColumn) &gt; 0 </code></pre> <p>This works for the &amp;nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?</p>
[ { "answer_id": 52327, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://www.lazydba.com/sql/1__4390.html\" rel=\"noreferrer\">This page</a> has a sample of how you can remove non-alphanumeric chars:</p>\n\n<pre><code>-- Put something like this into a user function:\nDECLARE @cString VARCHAR(32)\nDECLARE @nPos INTEGER\nSELECT @cString = '90$%45623 *6%}~:@'\nSELECT @nPos = PATINDEX('%[^0-9]%', @cString)\n\nWHILE @nPos &gt; 0\nBEGIN\nSELECT @cString = STUFF(@cString, @nPos, 1, '')\nSELECT @nPos = PATINDEX('%[^0-9]%', @cString)\nEND\n\nSELECT @cString \n</code></pre>\n" }, { "answer_id": 52348, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "<p>How is the table being populated? While it is possible to scrub this in sql a better approach would be to change the column type to int and scrub the data before it's loaded into the database (SSIS). Is this an option?</p>\n" }, { "answer_id": 879018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This will remove all non alphanumeric chracters</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnRemoveBadCharacter]\n(\n @BadString nvarchar(20)\n)\nRETURNS nvarchar(20)\nAS\nBEGIN\n\n DECLARE @nPos INTEGER\n SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)\n\n WHILE @nPos &gt; 0\n BEGIN\n SELECT @BadString = STUFF(@BadString, @nPos, 1, '')\n SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)\n END\n\n RETURN @BadString\nEND\n</code></pre>\n\n<p>Use the function like:</p>\n\n<pre><code>UPDATE TableToUpdate\nSET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate)\nWHERE whatever\n</code></pre>\n" }, { "answer_id": 28970617, "author": "BrandonNeiger", "author_id": 4655121, "author_profile": "https://Stackoverflow.com/users/4655121", "pm_score": 0, "selected": false, "text": "<p>For large datasets I have had better luck with this function that checks the ASCII value. I have added options to keep only alpha, numeric or alphanumeric based on the parameters.</p>\n\n<pre><code>--CleanType 1 - Remove all non alpanumeric\n-- 2 - Remove only alpha\n-- 3 - Remove only numeric\nCREATE FUNCTION [dbo].[fnCleanString] (\n @InputString varchar(8000)\n , @CleanType int \n , @LeaveSpaces bit \n) RETURNS varchar(8000)\nAS \nBEGIN\n\n -- // Declare variables\n -- ===========================================================\n DECLARE @Length int\n , @CurLength int = 1\n , @ReturnString varchar(8000)=''\n\n SELECT @Length = len(@InputString)\n\n -- // Begin looping through each char checking ASCII value\n -- ===========================================================\n WHILE (@CurLength &lt;= (@Length+1))\n BEGIN\n IF (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 48 and 57 AND @CleanType in (1,3) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 65 and 90 AND @CleanType in (1,2) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 97 and 122 AND @CleanType in (1,2) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) = 32 AND @LeaveSpaces = 1 )\n BEGIN\n SET @ReturnString = @ReturnString + SUBSTRING(@InputString,@CurLength,1)\n END\n SET @CurLength = @CurLength + 1\n END\n\n RETURN @ReturnString\nEND\n</code></pre>\n" }, { "answer_id": 35891879, "author": "Tobi Adeyemi", "author_id": 6039441, "author_profile": "https://Stackoverflow.com/users/6039441", "pm_score": 0, "selected": false, "text": "<p>If the mobile could start with a Plus(+) I will use the function like this</p>\n\n<pre><code>CREATE FUNCTION [dbo].[Mobile_NoAlpha](@Mobile VARCHAR(1000)) \nRETURNS VARCHAR(1000) \nAS \nBEGIN\n DECLARE @StartsWithPlus BIT = 0\n\n --check if the mobile starts with a plus(+)\n IF LEFT(@Mobile, 1) = '+'\n BEGIN\n SET @StartsWithPlus = 1\n\n --Take out the plus before using the regex to eliminate invalid characters\n SET @Mobile = RIGHT(@Mobile, LEN(@Mobile)-1) \n END\n\n WHILE PatIndex('%[^0-9]%', @Mobile) &gt; 0 \n SET @Mobile = Stuff(@Mobile, PatIndex('%[^0-9]%', @Mobile), 1, '') \n\n IF @StartsWithPlus = 1\n SET @Mobile = '+' + @Mobile\n RETURN @Mobile \nEND\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5202/" ]
We have some input data that sometimes appears with &nbsp characters on the end. The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters. Ltrim and Rtrim don't remove the characters, so we're forced to do something like: ``` UPDATE myTable SET myColumn = replace(myColumn,char(160),'') WHERE charindex(char(160),myColumn) > 0 ``` This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?
[This page](http://www.lazydba.com/sql/1__4390.html) has a sample of how you can remove non-alphanumeric chars: ``` -- Put something like this into a user function: DECLARE @cString VARCHAR(32) DECLARE @nPos INTEGER SELECT @cString = '90$%45623 *6%}~:@' SELECT @nPos = PATINDEX('%[^0-9]%', @cString) WHILE @nPos > 0 BEGIN SELECT @cString = STUFF(@cString, @nPos, 1, '') SELECT @nPos = PATINDEX('%[^0-9]%', @cString) END SELECT @cString ```
52,321
<p>Using the obsolete System.Web.Mail sending email works fine, here's the code snippet:</p> <pre><code> Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String) Try Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage Message.To = recipent Message.From = from Message.Subject = subject Message.Body = body Message.BodyFormat = MailFormat.Html Try SmtpMail.SmtpServer = MAIL_SERVER SmtpMail.Send(Message) Catch ehttp As System.Web.HttpException critical_error("Email sending failed, reason: " + ehttp.ToString) End Try Catch e As System.Exception critical_error(e, "send() in Util_Email") End Try End Sub </code></pre> <p>and here's the updated version:</p> <pre><code>Dim mailMessage As New System.Net.Mail.MailMessage() mailMessage.From = New System.Net.Mail.MailAddress(from) mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent)) mailMessage.Subject = subject mailMessage.Body = body mailMessage.IsBodyHtml = True mailMessage.Priority = System.Net.Mail.MailPriority.Normal Try Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER) smtp.Send(mailMessage) Catch ex As Exception MsgBox(ex.ToString) End Try </code></pre> <p>I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions?</p> <p>There are no exceptions that are thrown back.</p>
[ { "answer_id": 52361, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 0, "selected": false, "text": "<p>Have you tried adding </p>\n\n<pre><code>smtp.UseDefaultCredentials = True \n</code></pre>\n\n<p>before the send?</p>\n\n<p>Also, what happens if you try changing:</p>\n\n<pre><code>mailMessage.From = New System.Net.Mail.MailAddress(from)\nmailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>mailMessage.From = New System.Net.Mail.MailAddress(from,recipent)\n</code></pre>\n\n<p>-- Kevin Fairchild</p>\n" }, { "answer_id": 52369, "author": "Robin Minto", "author_id": 1456, "author_profile": "https://Stackoverflow.com/users/1456", "pm_score": 1, "selected": true, "text": "<p>I've tested your code and my mail is sent successfully. Assuming that you're using the same parameters for the old code, I would suggest that your mail server (MAIL_SERVER) is accepting the message and there's a delay in processing or it considers it spam and discards it.</p>\n<p>I would suggest sending a message using a third way (telnet if you're feeling brave) and see if that is successful.</p>\n<p>EDIT: I note (from your subsequent answer) that specifying the port has helped somewhat. You've not said if you're using port 25 (SMTP) or port 587 (Submission) or something else. If you're not doing it already, using the sumission port may also help solve your problem.</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol\" rel=\"nofollow noreferrer\">Wikipedia</a> and <a href=\"https://www.rfc-editor.org/rfc/rfc4409\" rel=\"nofollow noreferrer\">rfc4409</a> have more details.</p>\n" }, { "answer_id": 52371, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>Are you setting the credentials for the E-Mail?</p>\n\n<pre><code>smtp.Credentials = New Net.NetworkCredential(\"[email protected]\", \"password\")\n</code></pre>\n\n<p>I had this error, however I believe it threw an exception.</p>\n" }, { "answer_id": 52374, "author": "pete blair", "author_id": 5119, "author_profile": "https://Stackoverflow.com/users/5119", "pm_score": 1, "selected": false, "text": "<p>The System.Net.Mail library uses the config files to store the settings so you may just need to add a section like this</p>\n\n<pre><code> &lt;system.net&gt;\n &lt;mailSettings&gt;\n &lt;smtp from=\"[email protected]\"&gt;\n &lt;network host=\"smtpserver1\" port=\"25\" userName=\"username\" password=\"secret\" defaultCredentials=\"true\" /&gt;\n &lt;/smtp&gt;\n &lt;/mailSettings&gt;\n &lt;/system.net&gt;\n</code></pre>\n" }, { "answer_id": 52407, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>Everything you are doing is correct. Here's the things i would check.</p>\n\n<ol>\n<li>Double check that the SMTP service in IIS is running right.</li>\n<li>Make sure it's not getting flagged as spam.</li>\n</ol>\n\n<p>those are usually the biggest culprits whenever we have had issues w/ sending email.</p>\n\n<p>Also, just noticed you are doing MsgBox(ex.Message). I believe they blocked MessageBox from working asp.net in a service pack, so it might be erroring out, you just might not know it. check your event log.</p>\n" }, { "answer_id": 52435, "author": "DoryuX", "author_id": 4827, "author_profile": "https://Stackoverflow.com/users/4827", "pm_score": 0, "selected": false, "text": "<p>I added the port number for the mail server and it started working sporadically, it seems that it was a problem with the server and a delay in sending the messages. Thanks for your answers, they were all helpful!</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4827/" ]
Using the obsolete System.Web.Mail sending email works fine, here's the code snippet: ``` Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String) Try Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage Message.To = recipent Message.From = from Message.Subject = subject Message.Body = body Message.BodyFormat = MailFormat.Html Try SmtpMail.SmtpServer = MAIL_SERVER SmtpMail.Send(Message) Catch ehttp As System.Web.HttpException critical_error("Email sending failed, reason: " + ehttp.ToString) End Try Catch e As System.Exception critical_error(e, "send() in Util_Email") End Try End Sub ``` and here's the updated version: ``` Dim mailMessage As New System.Net.Mail.MailMessage() mailMessage.From = New System.Net.Mail.MailAddress(from) mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent)) mailMessage.Subject = subject mailMessage.Body = body mailMessage.IsBodyHtml = True mailMessage.Priority = System.Net.Mail.MailPriority.Normal Try Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER) smtp.Send(mailMessage) Catch ex As Exception MsgBox(ex.ToString) End Try ``` I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions? There are no exceptions that are thrown back.
I've tested your code and my mail is sent successfully. Assuming that you're using the same parameters for the old code, I would suggest that your mail server (MAIL\_SERVER) is accepting the message and there's a delay in processing or it considers it spam and discards it. I would suggest sending a message using a third way (telnet if you're feeling brave) and see if that is successful. EDIT: I note (from your subsequent answer) that specifying the port has helped somewhat. You've not said if you're using port 25 (SMTP) or port 587 (Submission) or something else. If you're not doing it already, using the sumission port may also help solve your problem. [Wikipedia](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol) and [rfc4409](https://www.rfc-editor.org/rfc/rfc4409) have more details.
52,353
<p>I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause <code>OutOfMemoryError</code>s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a <code>VM</code>?</p> <p>Right now, I have code that says read up to <strong>32,000 rows</strong>, but I'd also like to have code that says read as many rows as possible until I've used <strong>32MB</strong> of memory. Maybe that is a different question, but I'd still like to know. </p>
[ { "answer_id": 52362, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": -1, "selected": false, "text": "<p>I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a costly thing to do. There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.</p>\n\n<p>One way you could do it is to serialize the thing to a File and look at the size of the file, like this:</p>\n\n<pre><code>Serializable myObject;\nObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (\"obj.ser\"));\noos.write (myObject);\noos.close ();\n</code></pre>\n\n<p>Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.</p>\n\n<p>Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean &amp; byte = 1 byte, short &amp; char = 2 bytes, etc.), working your way down the membership hierarchy. But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.</p>\n" }, { "answer_id": 52377, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.</p>\n\n<p>If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs.</p>\n" }, { "answer_id": 52391, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": false, "text": "<p>If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:</p>\n\n<pre><code>// Get current size of heap in bytes\nlong heapSize = Runtime.getRuntime().totalMemory();\n\n// Get maximum size of heap in bytes. The heap cannot grow beyond this size.\n// Any attempt will result in an OutOfMemoryException.\nlong heapMaxSize = Runtime.getRuntime().maxMemory();\n\n// Get amount of free memory within the heap in bytes. This size will increase\n// after garbage collection and decrease as new objects are created.\nlong heapFreeSize = Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>edit: I thought this might be helpful as the question author also stated he would like to have logic that handles \"read as many rows as possible until I've used 32MB of memory.\"</p>\n" }, { "answer_id": 52393, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "<p>You have to walk the objects using reflection. Be careful as you do:</p>\n\n<ul>\n<li>Just allocating an object has some overhead in the JVM. The amount varies by JVM so you might make this value a parameter. At least make it a constant (8 bytes?) and apply to anything allocated.</li>\n<li>Just because <code>byte</code> is theoretically 1 byte doesn't mean it takes just one in memory.</li>\n<li>There will be loops in object references, so you'll need to keep a <code>HashMap</code> or somesuch <em>using object-equals as the comparator</em> to eliminate infinite loops.</li>\n</ul>\n\n<p>@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.</p>\n" }, { "answer_id": 52395, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "<p>You have to measure it with a tool, or estimate it by hand, and it depends on the JVM you are using.</p>\n\n<p>There is some fixed overhead per object. It's JVM-specific, but I usually estimate 40 bytes. Then you have to look at the members of the class. Object references are 4 (8) bytes in a 32-bit (64-bit) JVM. Primitive types are: </p>\n\n<ul>\n<li>boolean and byte: 1 byte</li>\n<li>char and short: 2 bytes</li>\n<li>int and float: 4 bytes</li>\n<li>long and double: 8 bytes</li>\n</ul>\n\n<p>Arrays follow the same rules; that is, it's an object reference so that takes 4 (or 8) bytes in your object, and then its length multiplied by the size of its element.</p>\n\n<p>Trying to do it programmatically with calls to <code>Runtime.freeMemory()</code> just doesn't give you much accuracy, because of asynchronous calls to the garbage collector, etc. Profiling the heap with -Xrunhprof or other tools will give you the most accurate results.</p>\n" }, { "answer_id": 52401, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 6, "selected": false, "text": "<p>Firstly \"the size of an object\" isn't a well-defined concept in Java. You could mean the object itself, with just its members, the Object and all objects it refers to (the reference graph). You could mean the size in memory or the size on disk. And the JVM is allowed to optimise things like Strings.</p>\n\n<p>So the only correct way is to ask the JVM, with a good profiler (I use <a href=\"http://www.yourkit.com\" rel=\"noreferrer\">YourKit</a>), which probably isn't what you want.</p>\n\n<p>However, from the description above it sounds like each row will be self-contained, and not have a big dependency tree, so the serialization method will probably be a good approximation on most JVMs. The easiest way to do this is as follows:</p>\n\n<pre><code> Serializable ser;\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(ser);\n oos.close();\n return baos.size();\n</code></pre>\n\n<p>Remember that if you have objects with common references this <em>will not</em> give the correct result, and size of serialization will not always match size in memory, but it is a good approximation. The code will be a bit more efficient if you initialise the ByteArrayOutputStream size to a sensible value.</p>\n" }, { "answer_id": 52568, "author": "Boris Terzic", "author_id": 1996, "author_profile": "https://Stackoverflow.com/users/1996", "pm_score": 6, "selected": false, "text": "<p>Some years back Javaworld had <a href=\"https://www.infoworld.com/article/2077408/sizeof-for-java.html\" rel=\"noreferrer\">an article on determining the size of composite and potentially nested Java objects</a>, they basically walk through creating a sizeof() implementation in Java. The approach basically builds on other work where people experimentally identified the size of primitives and typical Java objects and then apply that knowledge to a method that recursively walks an object graph to tally the total size.</p>\n<p>It is always going to be somewhat less accurate than a native C implementation simply because of the things going on behind the scenes of a class but it should be a good indicator.</p>\n<p>Alternatively a SourceForge project appropriately called <a href=\"http://sourceforge.net/projects/sizeof\" rel=\"noreferrer\">sizeof</a> that offers a Java5 library with a sizeof() implementation.</p>\n<p>P.S. Do not use the serialization approach, there is no correlation between the size of a serialized object and the amount of memory it consumes when live.</p>\n" }, { "answer_id": 52682, "author": "Stefan Karlsson", "author_id": 5438, "author_profile": "https://Stackoverflow.com/users/5438", "pm_score": 10, "selected": true, "text": "<p>You can use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html\" rel=\"noreferrer\"><code>java.lang.instrument</code> package</a>.</p>\n<p>Compile and put this class in a JAR:</p>\n<pre><code>import java.lang.instrument.Instrumentation;\n\npublic class ObjectSizeFetcher {\n private static Instrumentation instrumentation;\n\n public static void premain(String args, Instrumentation inst) {\n instrumentation = inst;\n }\n\n public static long getObjectSize(Object o) {\n return instrumentation.getObjectSize(o);\n }\n}\n</code></pre>\n<p>Add the following to your <code>MANIFEST.MF</code>:</p>\n<pre><code>Premain-Class: ObjectSizeFetcher\n</code></pre>\n<p>Use the <code>getObjectSize()</code> method:</p>\n<pre><code>public class C {\n private int x;\n private int y;\n\n public static void main(String [] args) {\n System.out.println(ObjectSizeFetcher.getObjectSize(new C()));\n }\n}\n</code></pre>\n<p>Invoke with:</p>\n<pre><code>java -javaagent:ObjectSizeFetcherAgent.jar C\n</code></pre>\n" }, { "answer_id": 10587479, "author": "Miguel Gamboa", "author_id": 1140754, "author_profile": "https://Stackoverflow.com/users/1140754", "pm_score": 3, "selected": false, "text": "<p>The <code>java.lang.instrument.Instrumentation</code> class provides a nice way to get the size of a Java Object, but it requires you to define a <code>premain</code> and run your program with a java agent. This is very boring when you do not need any agent and then you have to provide a dummy Jar agent to your application.</p>\n\n<p>So I got an alternative solution using the <code>Unsafe</code> class from the <code>sun.misc</code>. So, considering the objects heap alignment according to the processor architecture and calculating the maximum field offset, you can measure the size of a Java Object. In the example below I use an auxiliary class <code>UtilUnsafe</code> to get a reference to the <code>sun.misc.Unsafe</code> object.</p>\n\n<pre><code>private static final int NR_BITS = Integer.valueOf(System.getProperty(\"sun.arch.data.model\"));\nprivate static final int BYTE = 8;\nprivate static final int WORD = NR_BITS/BYTE;\nprivate static final int MIN_SIZE = 16; \n\npublic static int sizeOf(Class src){\n //\n // Get the instance fields of src class\n // \n List&lt;Field&gt; instanceFields = new LinkedList&lt;Field&gt;();\n do{\n if(src == Object.class) return MIN_SIZE;\n for (Field f : src.getDeclaredFields()) {\n if((f.getModifiers() &amp; Modifier.STATIC) == 0){\n instanceFields.add(f);\n }\n }\n src = src.getSuperclass();\n }while(instanceFields.isEmpty());\n //\n // Get the field with the maximum offset\n // \n long maxOffset = 0;\n for (Field f : instanceFields) {\n long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f);\n if(offset &gt; maxOffset) maxOffset = offset; \n }\n return (((int)maxOffset/WORD) + 1)*WORD; \n}\nclass UtilUnsafe {\n public static final sun.misc.Unsafe UNSAFE;\n\n static {\n Object theUnsafe = null;\n Exception exception = null;\n try {\n Class&lt;?&gt; uc = Class.forName(\"sun.misc.Unsafe\");\n Field f = uc.getDeclaredField(\"theUnsafe\");\n f.setAccessible(true);\n theUnsafe = f.get(uc);\n } catch (Exception e) { exception = e; }\n UNSAFE = (sun.misc.Unsafe) theUnsafe;\n if (UNSAFE == null) throw new Error(\"Could not obtain access to sun.misc.Unsafe\", exception);\n }\n private UtilUnsafe() { }\n}\n</code></pre>\n" }, { "answer_id": 15815016, "author": "JZeeb", "author_id": 161142, "author_profile": "https://Stackoverflow.com/users/161142", "pm_score": 0, "selected": false, "text": "<p>You could generate a heap dump (with jmap, for example) and then analyze the output to find object sizes. This is an offline solution, but you can examine shallow and deep sizes, etc.</p>\n" }, { "answer_id": 18645101, "author": "PNS", "author_id": 834316, "author_profile": "https://Stackoverflow.com/users/834316", "pm_score": 3, "selected": false, "text": "<p>There is also the <strong>Memory Measurer</strong> tool (formerly at <a href=\"http://code.google.com/p/memory-measurer/\" rel=\"nofollow noreferrer\">Google Code</a>, now on <a href=\"https://github.com/DimitrisAndreou/memory-measurer\" rel=\"nofollow noreferrer\">GitHub</a>), which is simple and published under the commercial-friendly <strong>Apache 2.0 license</strong>, as discussed in a <a href=\"https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java\">similar question</a>.</p>\n\n<p>It, too, requires a command-line argument to the java interpreter if you want to measure memory byte consumption, but otherwise seems to work just fine, at least in the scenarios I have used it.</p>\n" }, { "answer_id": 20014332, "author": "Jason C", "author_id": 616460, "author_profile": "https://Stackoverflow.com/users/616460", "pm_score": 2, "selected": false, "text": "<p>I wrote a quick test once to estimate on the fly:</p>\n\n<pre><code>public class Test1 {\n\n // non-static nested\n class Nested { }\n\n // static nested\n static class StaticNested { }\n\n static long getFreeMemory () {\n // waits for free memory measurement to stabilize\n long init = Runtime.getRuntime().freeMemory(), init2;\n int count = 0;\n do {\n System.out.println(\"waiting...\" + init);\n System.gc();\n try { Thread.sleep(250); } catch (Exception x) { }\n init2 = init;\n init = Runtime.getRuntime().freeMemory();\n if (init == init2) ++ count; else count = 0;\n } while (count &lt; 5);\n System.out.println(\"ok...\" + init);\n return init;\n }\n\n Test1 () throws InterruptedException {\n\n Object[] s = new Object[10000];\n Object[] n = new Object[10000];\n Object[] t = new Object[10000];\n\n long init = getFreeMemory();\n\n //for (int j = 0; j &lt; 10000; ++ j)\n // s[j] = new Separate();\n\n long afters = getFreeMemory();\n\n for (int j = 0; j &lt; 10000; ++ j)\n n[j] = new Nested();\n\n long aftersn = getFreeMemory();\n\n for (int j = 0; j &lt; 10000; ++ j)\n t[j] = new StaticNested();\n\n long aftersnt = getFreeMemory();\n\n System.out.println(\"separate: \" + -(afters - init) + \" each=\" + -(afters - init) / 10000);\n System.out.println(\"nested: \" + -(aftersn - afters) + \" each=\" + -(aftersn - afters) / 10000);\n System.out.println(\"static nested: \" + -(aftersnt - aftersn) + \" each=\" + -(aftersnt - aftersn) / 10000);\n\n }\n\n public static void main (String[] args) throws InterruptedException {\n new Test1();\n }\n\n}\n</code></pre>\n\n<p>General concept is allocate objects and measure change in free heap space. The key being <code>getFreeMemory()</code>, which <strong>requests GC runs and waits for the reported free heap size to stabilize</strong>. The output of the above is:</p>\n\n<pre><code>nested: 160000 each=16\nstatic nested: 160000 each=16\n</code></pre>\n\n<p>Which is what we expect, given alignment behavior and possible heap block header overhead.</p>\n\n<p>The instrumentation method detailed in the accepted answer here the most accurate. The method I described is accurate but only under controlled conditions where no other threads are creating/discarding objects.</p>\n" }, { "answer_id": 23511330, "author": "user835199", "author_id": 835199, "author_profile": "https://Stackoverflow.com/users/835199", "pm_score": 1, "selected": false, "text": "<pre><code>long heapSizeBefore = Runtime.getRuntime().totalMemory();\n\n// Code for object construction\n...\nlong heapSizeAfter = Runtime.getRuntime().totalMemory();\nlong size = heapSizeAfter - heapSizeBefore;\n</code></pre>\n\n<p>size gives you the increase in memory usage of the jvm due to object creation and that typically is the size of the object.</p>\n" }, { "answer_id": 24423089, "author": "dlaudams", "author_id": 3777283, "author_profile": "https://Stackoverflow.com/users/3777283", "pm_score": 2, "selected": false, "text": "<p>Here is a utility I made using some of the linked examples to handle 32-bit, 64-bit and 64-bit with compressed OOP. It uses <code>sun.misc.Unsafe</code>.</p>\n\n<p>It uses <code>Unsafe.addressSize()</code> to get the size of a native pointer and <code>Unsafe.arrayIndexScale( Object[].class )</code> for the size of a Java reference.</p>\n\n<p>It uses the field offset of a known class to work out the base size of an object.</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.IdentityHashMap;\nimport java.util.Stack;\nimport sun.misc.Unsafe;\n\n/** Usage: \n * MemoryUtil.sizeOf( object )\n * MemoryUtil.deepSizeOf( object )\n * MemoryUtil.ADDRESS_MODE\n */\npublic class MemoryUtil\n{\n private MemoryUtil()\n {\n }\n\n public static enum AddressMode\n {\n /** Unknown address mode. Size calculations may be unreliable. */\n UNKNOWN,\n /** 32-bit address mode using 32-bit references. */\n MEM_32BIT,\n /** 64-bit address mode using 64-bit references. */\n MEM_64BIT,\n /** 64-bit address mode using 32-bit compressed references. */\n MEM_64BIT_COMPRESSED_OOPS\n }\n\n /** The detected runtime address mode. */\n public static final AddressMode ADDRESS_MODE;\n\n private static final Unsafe UNSAFE;\n\n private static final long ADDRESS_SIZE; // The size in bytes of a native pointer: 4 for 32 bit, 8 for 64 bit\n private static final long REFERENCE_SIZE; // The size of a Java reference: 4 for 32 bit, 4 for 64 bit compressed oops, 8 for 64 bit\n private static final long OBJECT_BASE_SIZE; // The minimum size of an Object: 8 for 32 bit, 12 for 64 bit compressed oops, 16 for 64 bit\n private static final long OBJECT_ALIGNMENT = 8;\n\n /** Use the offset of a known field to determine the minimum size of an object. */\n private static final Object HELPER_OBJECT = new Object() { byte b; };\n\n\n static\n {\n try\n {\n // Use reflection to get a reference to the 'Unsafe' object.\n Field f = Unsafe.class.getDeclaredField( \"theUnsafe\" );\n f.setAccessible( true );\n UNSAFE = (Unsafe) f.get( null );\n\n OBJECT_BASE_SIZE = UNSAFE.objectFieldOffset( HELPER_OBJECT.getClass().getDeclaredField( \"b\" ) );\n\n ADDRESS_SIZE = UNSAFE.addressSize();\n REFERENCE_SIZE = UNSAFE.arrayIndexScale( Object[].class );\n\n if( ADDRESS_SIZE == 4 )\n {\n ADDRESS_MODE = AddressMode.MEM_32BIT;\n }\n else if( ADDRESS_SIZE == 8 &amp;&amp; REFERENCE_SIZE == 8 )\n {\n ADDRESS_MODE = AddressMode.MEM_64BIT;\n }\n else if( ADDRESS_SIZE == 8 &amp;&amp; REFERENCE_SIZE == 4 )\n {\n ADDRESS_MODE = AddressMode.MEM_64BIT_COMPRESSED_OOPS;\n }\n else\n {\n ADDRESS_MODE = AddressMode.UNKNOWN;\n }\n }\n catch( Exception e )\n {\n throw new Error( e );\n }\n }\n\n\n /** Return the size of the object excluding any referenced objects. */\n public static long shallowSizeOf( final Object object )\n {\n Class&lt;?&gt; objectClass = object.getClass();\n if( objectClass.isArray() )\n {\n // Array size is base offset + length * element size\n long size = UNSAFE.arrayBaseOffset( objectClass )\n + UNSAFE.arrayIndexScale( objectClass ) * Array.getLength( object );\n return padSize( size );\n }\n else\n {\n // Object size is the largest field offset padded out to 8 bytes\n long size = OBJECT_BASE_SIZE;\n do\n {\n for( Field field : objectClass.getDeclaredFields() )\n {\n if( (field.getModifiers() &amp; Modifier.STATIC) == 0 )\n {\n long offset = UNSAFE.objectFieldOffset( field );\n if( offset &gt;= size )\n {\n size = offset + 1; // Field size is between 1 and PAD_SIZE bytes. Padding will round up to padding size.\n }\n }\n }\n objectClass = objectClass.getSuperclass();\n }\n while( objectClass != null );\n\n return padSize( size );\n }\n }\n\n\n private static final long padSize( final long size )\n {\n return (size + (OBJECT_ALIGNMENT - 1)) &amp; ~(OBJECT_ALIGNMENT - 1);\n }\n\n\n /** Return the size of the object including any referenced objects. */\n public static long deepSizeOf( final Object object )\n {\n IdentityHashMap&lt;Object,Object&gt; visited = new IdentityHashMap&lt;Object,Object&gt;();\n Stack&lt;Object&gt; stack = new Stack&lt;Object&gt;();\n if( object != null ) stack.push( object );\n\n long size = 0;\n while( !stack.isEmpty() )\n {\n size += internalSizeOf( stack.pop(), stack, visited );\n }\n return size;\n }\n\n\n private static long internalSizeOf( final Object object, final Stack&lt;Object&gt; stack, final IdentityHashMap&lt;Object,Object&gt; visited )\n {\n // Scan for object references and add to stack\n Class&lt;?&gt; c = object.getClass();\n if( c.isArray() &amp;&amp; !c.getComponentType().isPrimitive() )\n {\n // Add unseen array elements to stack\n for( int i = Array.getLength( object ) - 1; i &gt;= 0; i-- )\n {\n Object val = Array.get( object, i );\n if( val != null &amp;&amp; visited.put( val, val ) == null )\n {\n stack.add( val );\n }\n }\n }\n else\n {\n // Add unseen object references to the stack\n for( ; c != null; c = c.getSuperclass() )\n {\n for( Field field : c.getDeclaredFields() )\n {\n if( (field.getModifiers() &amp; Modifier.STATIC) == 0 \n &amp;&amp; !field.getType().isPrimitive() )\n {\n field.setAccessible( true );\n try\n {\n Object val = field.get( object );\n if( val != null &amp;&amp; visited.put( val, val ) == null )\n {\n stack.add( val );\n }\n }\n catch( IllegalArgumentException e )\n {\n throw new RuntimeException( e );\n }\n catch( IllegalAccessException e )\n {\n throw new RuntimeException( e );\n }\n }\n }\n }\n }\n\n return shallowSizeOf( object );\n }\n}\n</code></pre>\n" }, { "answer_id": 26407668, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 1, "selected": false, "text": "<p>My answer is based on the code supplied by Nick. That code measures total amount of bytes which are occupied by the serialized object. So this actually measures serialization stuff + plain object memory footprint (just serialize for example <code>int</code> and you will see that total amount of serialized bytes is not <code>4</code>). So if you want to get raw byte number used exactly for your object - you need to modify that code a bit. Like so:</p>\n\n<pre><code>import java.io.ByteArrayOutputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\npublic class ObjectSizeCalculator {\n private Object getFirstObjectReference(Object o) {\n String objectType = o.getClass().getTypeName();\n\n if (objectType.substring(objectType.length()-2).equals(\"[]\")) {\n try {\n if (objectType.equals(\"java.lang.Object[]\"))\n return ((Object[])o)[0];\n else if (objectType.equals(\"int[]\"))\n return ((int[])o)[0];\n else\n throw new RuntimeException(\"Not Implemented !\");\n } catch (IndexOutOfBoundsException e) {\n return null;\n }\n }\n\n return o;\n } \n\n public int getObjectSizeInBytes(Object o) {\n final String STRING_JAVA_TYPE_NAME = \"java.lang.String\";\n\n if (o == null)\n return 0;\n\n String objectType = o.getClass().getTypeName();\n boolean isArray = objectType.substring(objectType.length()-2).equals(\"[]\");\n\n Object objRef = getFirstObjectReference(o);\n if (objRef != null &amp;&amp; !(objRef instanceof Serializable))\n throw new RuntimeException(\"Object must be serializable for measuring it's memory footprint using this method !\");\n\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(o);\n oos.close();\n byte[] bytes = baos.toByteArray();\n\n for (int i = bytes.length - 1, j = 0; i != 0; i--, j++) {\n if (objectType != STRING_JAVA_TYPE_NAME) {\n if (bytes[i] == 112)\n if (isArray)\n return j - 4;\n else\n return j;\n } else {\n if (bytes[i] == 0)\n return j - 1;\n }\n }\n } catch (Exception e) {\n return -1;\n }\n\n return -1;\n } \n\n}\n</code></pre>\n\n<p>I've tested this solution with primitive types, String, and on some trivial classes. There may be not covered cases also.</p>\n\n<p><br><strong>UPDATE:</strong> Example modified to support memory footprint calculation of array objects.</p>\n" }, { "answer_id": 28825937, "author": "Kanagavelu Sugumar", "author_id": 912319, "author_profile": "https://Stackoverflow.com/users/912319", "pm_score": 1, "selected": false, "text": "<p>This answer is not related to Object size, but when you are using array to accommodate the objects; how much memory size it will allocate for the object.</p>\n\n<p>So arrays, list, or map all those collection won't be going to store objects really (only at the time of primitives, real object memory size is needed), it will store only references for those objects. </p>\n\n<p>Now the <code>Used heap memory = sizeOfObj + sizeOfRef (* 4 bytes) in collection</code></p>\n\n<ul>\n<li>(4/8 bytes) depends on (32/64 bit) OS</li>\n</ul>\n\n<p><strong>PRIMITIVES</strong></p>\n\n<pre><code>int [] intArray = new int [1]; will require 4 bytes.\nlong [] longArray = new long [1]; will require 8 bytes.\n</code></pre>\n\n<p><strong>OBJECTS</strong></p>\n\n<pre><code>Object[] objectArray = new Object[1]; will require 4 bytes. The object can be any user defined Object.\nLong [] longArray = new Long [1]; will require 4 bytes.\n</code></pre>\n\n<p>I mean to say all the object REFERENCE needs only 4 bytes of memory. It may be String reference OR Double object reference, But depends on object creation the memory needed will vary.</p>\n\n<p>e.g) If i create object for the below class <code>ReferenceMemoryTest</code> then 4 + 4 + 4 = 12 bytes of memory will be created. The memory may differ when you are trying to initialize the references.</p>\n\n<pre><code> class ReferenceMemoryTest {\n public String refStr;\n public Object refObj;\n public Double refDoub; \n}\n</code></pre>\n\n<p>So when are creating object/reference array, all its contents will be occupied with NULL references. And we know each reference requires 4 bytes.</p>\n\n<p>And finally, memory allocation for the below code is 20 bytes.</p>\n\n<p>ReferenceMemoryTest ref1 = new ReferenceMemoryTest(); ( 4(ref1) + 12 = 16 bytes)\nReferenceMemoryTest ref2 = ref1; ( 4(ref2) + 16 = 20 bytes)</p>\n" }, { "answer_id": 28900509, "author": "rich", "author_id": 180416, "author_profile": "https://Stackoverflow.com/users/180416", "pm_score": 5, "selected": false, "text": "<p>Much of the other answers provide shallow sizes - e.g. the size of a HashMap without any of the keys or values, which isn't likely what you want.</p>\n\n<p>The jamm project uses the java.lang.instrumentation package above but walks the tree and so can give you the deep memory use.</p>\n\n<pre><code>new MemoryMeter().measureDeep(myHashMap);\n</code></pre>\n\n<p><a href=\"https://github.com/jbellis/jamm\" rel=\"noreferrer\">https://github.com/jbellis/jamm</a></p>\n\n<blockquote>\n <p>To use MemoryMeter, start the JVM with \"-javaagent:/jamm.jar\"</p>\n</blockquote>\n" }, { "answer_id": 29431949, "author": "reallynice", "author_id": 1504300, "author_profile": "https://Stackoverflow.com/users/1504300", "pm_score": 2, "selected": false, "text": "<p>Without having to mess with instrumentation and so on, and if you don't need to know the byte-exact size of an object, you could go with the following approach:</p>\n\n<pre><code>System.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n\ndo your job here\n\nSystem.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>This way you read the used memory before and after, and calling the GC just before getting the used memory you lower the \"noise\" almost to 0.</p>\n\n<p>For a more reliable result you can run your job n times, and then divide the used memory by n, obtaining how much memory one run takes. Even more, you can run the whole thing more times and make an average.</p>\n" }, { "answer_id": 29536817, "author": "Attila Szegedi", "author_id": 131552, "author_profile": "https://Stackoverflow.com/users/131552", "pm_score": 5, "selected": false, "text": "<p>Back when I worked at Twitter, I wrote a utility for calculating deep object size. It takes into account different memory models (32-bit, compressed oops, 64-bit), padding, subclass padding, works correctly on circular data structures and arrays. You can just compile this one .java file; it has no external dependencies:</p>\n\n<p><a href=\"https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java\" rel=\"noreferrer\">https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java</a></p>\n" }, { "answer_id": 30021105, "author": "Jeffrey Bosboom", "author_id": 3614835, "author_profile": "https://Stackoverflow.com/users/3614835", "pm_score": 7, "selected": false, "text": "<p>You should use <a href=\"http://openjdk.java.net/projects/code-tools/jol/\" rel=\"noreferrer\">jol</a>, a tool developed as part of the OpenJDK project.</p>\n\n<blockquote>\n <p>JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc.</p>\n</blockquote>\n\n<p>To get the sizes of primitives, references and array elements, use <code>VMSupport.vmDetails()</code>. On Oracle JDK 1.8.0_40 running on 64-bit Windows (used for all following examples), this method returns</p>\n\n<pre><code>Running 64-bit HotSpot VM.\nUsing compressed oop with 0-bit shift.\nUsing compressed klass with 3-bit shift.\nObjects are 8 bytes aligned.\nField sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\nArray element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\n</code></pre>\n\n<p>You can get the shallow size of an object instance using <code>ClassLayout.parseClass(Foo.class).toPrintable()</code> (optionally passing an instance to <code>toPrintable</code>). This is only the space consumed by a single instance of that class; it does not include any other objects referenced by that class. It <em>does</em> include VM overhead for the object header, field alignment and padding. For <code>java.util.regex.Pattern</code>:</p>\n\n<pre><code>java.util.regex.Pattern object internals:\n OFFSET SIZE TYPE DESCRIPTION VALUE\n 0 4 (object header) 01 00 00 00 (0000 0001 0000 0000 0000 0000 0000 0000)\n 4 4 (object header) 00 00 00 00 (0000 0000 0000 0000 0000 0000 0000 0000)\n 8 4 (object header) cb cf 00 20 (1100 1011 1100 1111 0000 0000 0010 0000)\n 12 4 int Pattern.flags 0\n 16 4 int Pattern.capturingGroupCount 1\n 20 4 int Pattern.localCount 0\n 24 4 int Pattern.cursor 48\n 28 4 int Pattern.patternLength 0\n 32 1 boolean Pattern.compiled true\n 33 1 boolean Pattern.hasSupplementary false\n 34 2 (alignment/padding gap) N/A\n 36 4 String Pattern.pattern (object)\n 40 4 String Pattern.normalizedPattern (object)\n 44 4 Node Pattern.root (object)\n 48 4 Node Pattern.matchRoot (object)\n 52 4 int[] Pattern.buffer null\n 56 4 Map Pattern.namedGroups null\n 60 4 GroupHead[] Pattern.groupNodes null\n 64 4 int[] Pattern.temp null\n 68 4 (loss due to the next object alignment)\nInstance size: 72 bytes (reported by Instrumentation API)\nSpace losses: 2 bytes internal + 4 bytes external = 6 bytes total\n</code></pre>\n\n<p>You can get a summary view of the deep size of an object instance using <code>GraphLayout.parseInstance(obj).toFootprint()</code>. Of course, some objects in the footprint might be shared (also referenced from other objects), so it is an overapproximation of the space that could be reclaimed when that object is garbage collected. For the result of <code>Pattern.compile(\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$\")</code> (taken from <a href=\"https://stackoverflow.com/a/719543/3614835\">this answer</a>), jol reports a total footprint of 1840 bytes, of which only 72 are the Pattern instance itself.</p>\n\n<pre><code>java.util.regex.Pattern instance footprint:\n COUNT AVG SUM DESCRIPTION\n 1 112 112 [C\n 3 272 816 [Z\n 1 24 24 java.lang.String\n 1 72 72 java.util.regex.Pattern\n 9 24 216 java.util.regex.Pattern$1\n 13 24 312 java.util.regex.Pattern$5\n 1 16 16 java.util.regex.Pattern$Begin\n 3 24 72 java.util.regex.Pattern$BitClass\n 3 32 96 java.util.regex.Pattern$Curly\n 1 24 24 java.util.regex.Pattern$Dollar\n 1 16 16 java.util.regex.Pattern$LastNode\n 1 16 16 java.util.regex.Pattern$Node\n 2 24 48 java.util.regex.Pattern$Single\n 40 1840 (total)\n</code></pre>\n\n<p>If you instead use <code>GraphLayout.parseInstance(obj).toPrintable()</code>, jol will tell you the address, size, type, value and path of field dereferences to each referenced object, though that's usually too much detail to be useful. For the ongoing pattern example, you might get the following. (Addresses will likely change between runs.)</p>\n\n<pre><code>java.util.regex.Pattern object externals:\n ADDRESS SIZE TYPE PATH VALUE\n d5e5f290 16 java.util.regex.Pattern$Node .root.next.atom.next (object)\n d5e5f2a0 120 (something else) (somewhere else) (something else)\n d5e5f318 16 java.util.regex.Pattern$LastNode .root.next.next.next.next.next.next.next (object)\n d5e5f328 21664 (something else) (somewhere else) (something else)\n d5e647c8 24 java.lang.String .pattern (object)\n d5e647e0 112 [C .pattern.value [^, [, a, -, z, A, -, Z, 0, -, 9, _, ., +, -, ], +, @, [, a, -, z, A, -, Z, 0, -, 9, -, ], +, \\, ., [, a, -, z, A, -, Z, 0, -, 9, -, ., ], +, $]\n d5e64850 448 (something else) (somewhere else) (something else)\n d5e64a10 72 java.util.regex.Pattern (object)\n d5e64a58 416 (something else) (somewhere else) (something else)\n d5e64bf8 16 java.util.regex.Pattern$Begin .root (object)\n d5e64c08 24 java.util.regex.Pattern$BitClass .root.next.atom.val$rhs (object)\n d5e64c20 272 [Z .root.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e64d30 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64d48 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e64d60 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64d78 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e64d90 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64da8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e64dc0 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs (object)\n d5e64dd8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs (object)\n d5e64df0 24 java.util.regex.Pattern$5 .root.next.atom (object)\n d5e64e08 32 java.util.regex.Pattern$Curly .root.next (object)\n d5e64e28 24 java.util.regex.Pattern$Single .root.next.next (object)\n d5e64e40 24 java.util.regex.Pattern$BitClass .root.next.next.next.atom.val$rhs (object)\n d5e64e58 272 [Z .root.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e64f68 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e64f80 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n d5e64f98 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs.val$lhs (object)\n d5e64fb0 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$rhs (object)\n d5e64fc8 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs (object)\n d5e64fe0 24 java.util.regex.Pattern$5 .root.next.next.next.atom (object)\n d5e64ff8 32 java.util.regex.Pattern$Curly .root.next.next.next (object)\n d5e65018 24 java.util.regex.Pattern$Single .root.next.next.next.next (object)\n d5e65030 24 java.util.regex.Pattern$BitClass .root.next.next.next.next.next.atom.val$rhs (object)\n d5e65048 272 [Z .root.next.next.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e65158 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e65170 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e65188 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e651a0 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n d5e651b8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs (object)\n d5e651d0 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs (object)\n d5e651e8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom (object)\n d5e65200 32 java.util.regex.Pattern$Curly .root.next.next.next.next.next (object)\n d5e65220 120 (something else) (somewhere else) (something else)\n d5e65298 24 java.util.regex.Pattern$Dollar .root.next.next.next.next.next.next (object)\n</code></pre>\n\n<p>The \"(something else)\" entries <a href=\"https://stackoverflow.com/questions/30021092/what-is-something-else-in-jol-graphlayout-output\">describe other objects in the heap that are not part of this object graph</a>.</p>\n\n<p>The best jol documentation is the <a href=\"http://hg.openjdk.java.net/code-tools/jol/file/tip/jol-samples/src/main/java/org/openjdk/jol/samples/\" rel=\"noreferrer\">jol samples</a> in the jol repository. The samples demonstrate common jol operations and show how you can use jol to analyze VM and garbage collector internals.</p>\n" }, { "answer_id": 39406536, "author": "Tom", "author_id": 1762932, "author_profile": "https://Stackoverflow.com/users/1762932", "pm_score": 7, "selected": false, "text": "<p>I accidentally found a java class\n\"jdk.nashorn.internal.ir.debug.ObjectSizeCalculator\", already in jdk, \nwhich is easy to use and seems quite useful for determining the size of an object.</p>\n\n<pre><code>System.out.println(ObjectSizeCalculator.getObjectSize(new gnu.trove.map.hash.TObjectIntHashMap&lt;String&gt;(12000, 0.6f, -1)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new HashMap&lt;String, Integer&gt;(100000)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(3));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 }));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[100]));\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>164192\n48\n16\n48\n416\n</code></pre>\n" }, { "answer_id": 47848790, "author": "Sai Kiran", "author_id": 7706962, "author_profile": "https://Stackoverflow.com/users/7706962", "pm_score": -1, "selected": false, "text": "<p>For JSONObject the below code can help you.</p>\n\n<pre><code>`JSONObject.toString().getBytes(\"UTF-8\").length`\n</code></pre>\n\n<p>returns size in bytes</p>\n\n<p>I checked it with my JSONArray object by writing it to a file. It is giving object size.</p>\n" }, { "answer_id": 49449106, "author": "ACV", "author_id": 912829, "author_profile": "https://Stackoverflow.com/users/912829", "pm_score": 2, "selected": false, "text": "<p>Just use java visual VM. </p>\n\n<p>It has everything you need to profile and debug memory problems. </p>\n\n<p>It also has a OQL (Object Query Language) console which allows you to do many useful things, one of which being <code>sizeof(o)</code></p>\n" }, { "answer_id": 55404104, "author": "Ali Dehghani", "author_id": 1393484, "author_profile": "https://Stackoverflow.com/users/1393484", "pm_score": 0, "selected": false, "text": "<p>Suppose I declare a class named <code>Complex</code> like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Complex {\n\n private final long real;\n private final long imaginary;\n\n // omitted\n}\n\n</code></pre>\n\n<p>In order to see how much memory is allocated to live instances of this class:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ jmap -histo:live &lt;pid&gt; | grep Complex\n\n num #instances #bytes class name (module)\n-------------------------------------------------------\n 327: 1 32 Complex\n</code></pre>\n" }, { "answer_id": 56783991, "author": "David Ryan", "author_id": 5307079, "author_profile": "https://Stackoverflow.com/users/5307079", "pm_score": 2, "selected": false, "text": "<p>I was looking for a runtime calculation of an object size that met the following requirements:</p>\n<ul>\n<li>Available at runtime with no need to include instrumentation.</li>\n<li>Works with Java 9+ without access to Unsafe.</li>\n<li>Is based on the Class only. Not a deep sizeOf that takes into consideration string lengths, array lengths, etc.</li>\n</ul>\n<p>The following is based on the core code of the original java specialists article (<a href=\"https://www.javaspecialists.eu/archive/Issue078.html\" rel=\"nofollow noreferrer\">https://www.javaspecialists.eu/archive/Issue078.html</a>) and a few bits from the Unsafe version in another answer to this question.</p>\n<p>I hope someone finds it useful.</p>\n<pre><code>public class JavaSize {\n\n private static final int NR_BITS = Integer.valueOf(System.getProperty(&quot;sun.arch.data.model&quot;));\n private static final int BYTE = 8;\n private static final int WORD = NR_BITS / BYTE;\n private static final int HEADER_SIZE = 8;\n\n public static int sizeOf(Class&lt;?&gt; clazz) {\n int result = 0;\n\n while (clazz != null) {\n Field[] fields = clazz.getDeclaredFields();\n for (int i = 0; i &lt; fields.length; i++) {\n if (!Modifier.isStatic(fields[i].getModifiers())) {\n if (fields[i].getType().isPrimitive()) {\n Class&lt;?&gt; primitiveClass = fields[i].getType();\n if (primitiveClass == boolean.class || primitiveClass == byte.class) {\n result += 1;\n } else if (primitiveClass == short.class) {\n result += 2;\n } else if (primitiveClass == int.class || primitiveClass == float.class) {\n result += 4;\n } else if (primitiveClass == double.class || primitiveClass == long.class) {\n result += 8;\n }\n\n } else {\n // assume compressed references.\n result += 4;\n }\n }\n }\n\n clazz = clazz.getSuperclass();\n\n // round up to the nearest WORD length.\n if ((result % WORD) != 0) {\n result += WORD - (result % WORD);\n }\n }\n\n result += HEADER_SIZE;\n\n return result;\n }\n }\n</code></pre>\n" }, { "answer_id": 61397323, "author": "simon04", "author_id": 205629, "author_profile": "https://Stackoverflow.com/users/205629", "pm_score": 4, "selected": false, "text": "<p>When using JetBrains IntelliJ, first enable \"Attach memory agent\" in File | Settings | Build, Execution, Deployment | Debugger.</p>\n\n<p>When debugging, right-click a variable of interest and choose \"Calculate Retained Size\": <a href=\"https://i.stack.imgur.com/TvMel.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TvMel.png\" alt=\"Calculate Retained Size\"></a></p>\n" }, { "answer_id": 71230694, "author": "Maurice", "author_id": 6351733, "author_profile": "https://Stackoverflow.com/users/6351733", "pm_score": 0, "selected": false, "text": "<p>If your application has the <a href=\"https://www.baeldung.com/java-commons-lang-3\" rel=\"nofollow noreferrer\">Apache commons lang library</a> as a dependency or is using the <a href=\"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/SerializationUtils.html\" rel=\"nofollow noreferrer\">Spring framework</a> then you can also use the <code>SerializationUtils</code> class to quickly find out the approximate byte size of any given object.</p>\n<pre><code>byte[] data = SerializationUtils.serialize(user);\nSystem.out.println(&quot;Approximate object size in bytes &quot; + data.length);\n</code></pre>\n" }, { "answer_id": 71683336, "author": "granadaCoder", "author_id": 214977, "author_profile": "https://Stackoverflow.com/users/214977", "pm_score": 2, "selected": false, "text": "<p>A possible year 2022 answer.</p>\n<p><a href=\"https://github.com/ehcache/sizeof\" rel=\"nofollow noreferrer\">https://github.com/ehcache/sizeof</a></p>\n<p><a href=\"https://mvnrepository.com/artifact/org.ehcache/sizeof\" rel=\"nofollow noreferrer\">https://mvnrepository.com/artifact/org.ehcache/sizeof</a></p>\n<p><a href=\"https://mvnrepository.com/artifact/org.ehcache/sizeof/0.4.0\" rel=\"nofollow noreferrer\">https://mvnrepository.com/artifact/org.ehcache/sizeof/0.4.0</a></p>\n<p>Version 0.4.0 has only a (compile) dependency on</p>\n<p><a href=\"https://mvnrepository.com/artifact/org.slf4j/slf4j-api\" rel=\"nofollow noreferrer\">https://mvnrepository.com/artifact/org.slf4j/slf4j-api</a></p>\n<p>which is a good thing.</p>\n<p>Sample code:</p>\n<pre><code>//import org.ehcache.sizeof.SizeOf;\n\nSizeOf sizeOf = SizeOf.newInstance(); // (1)\nlong shallowSize = sizeOf.sizeOf(someObject); // (2)\nlong deepSize = sizeOf.deepSizeOf(someObject); // (3)\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5074/" ]
I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause `OutOfMemoryError`s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a `VM`? Right now, I have code that says read up to **32,000 rows**, but I'd also like to have code that says read as many rows as possible until I've used **32MB** of memory. Maybe that is a different question, but I'd still like to know.
You can use the [`java.lang.instrument` package](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html). Compile and put this class in a JAR: ``` import java.lang.instrument.Instrumentation; public class ObjectSizeFetcher { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } public static long getObjectSize(Object o) { return instrumentation.getObjectSize(o); } } ``` Add the following to your `MANIFEST.MF`: ``` Premain-Class: ObjectSizeFetcher ``` Use the `getObjectSize()` method: ``` public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); } } ``` Invoke with: ``` java -javaagent:ObjectSizeFetcherAgent.jar C ```
52,356
<p>I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table.</p> <p>There must be a simple way of doing this. Something like:</p> <pre><code>INSERT INTO database1.myTable columnINeed SELECT columnINeed from database2.myTable </code></pre>
[ { "answer_id": 52368, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 0, "selected": false, "text": "<p>insert into Test2.dbo.MyTable (MyValue) select MyValue from Test1.dbo.MyTable</p>\n\n<p>This is assuming a great deal. First that the destination database is empty. Second that the other columns are nullable. You may need an update instead. To do that you will need to have a common key.</p>\n" }, { "answer_id": 52376, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 2, "selected": false, "text": "<p>There is a simple way very much like this as long as both databases are on the same server. The fully qualified name is dbname.owner.table - normally the owner is dbo and there is a shortcut for \".dbo.\" which is \"..\", so...</p>\n\n<pre><code>INSERT INTO Datbase1..MyTable\n (ColumnList)\nSELECT FieldsIWant\n FROM Database2..MyTable\n</code></pre>\n" }, { "answer_id": 52389, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 4, "selected": true, "text": "<p>Inserting won't do it since it'll attempt to insert new rows at the end of the table. What it sounds like your trying to do is add a column to the end of existing rows.</p>\n\n<p>I'm not sure if the syntax is exactly right but, if I understood you then this will do what you're after.</p>\n\n<ol>\n<li><p>Create the column allowing nulls in database2.</p></li>\n<li><p>Perform an update:</p>\n\n<p>UPDATE database2.dbo.tablename\nSET database2.dbo.tablename.colname = database1.dbo.tablename.colname\nFROM database2.dbo.tablename INNER JOIN database1.dbo.tablename ON database2.dbo.tablename.keycol = database1.dbo.tablename.keycol</p></li>\n</ol>\n" }, { "answer_id": 52405, "author": "Carl", "author_id": 5449, "author_profile": "https://Stackoverflow.com/users/5449", "pm_score": 1, "selected": false, "text": "<p>You could also use a cursor. Assuming you want to iterate all the records in the first table and populate the second table with new rows then something like this would be the way to go:</p>\n\n<pre><code>DECLARE @FirstField nvarchar(100)\n\nDECLARE ACursor CURSOR FOR\nSELECT FirstField FROM FirstTable \n\nOPEN ACursor\nFETCH NEXT FROM ACursor INTO @FirstField\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\n INSERT INTO SecondTable ( SecondField ) VALUES ( @FirstField )\n\n FETCH NEXT FROM ACursor INTO @FirstField\n\nEND\n\nCLOSE ACursor \nDEALLOCATE ACursor\n</code></pre>\n" }, { "answer_id": 52421, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "<p>first create the column if it doesn't exist:</p>\n\n<pre><code>ALTER TABLE database2..targetTable\nADD targetColumn int null -- or whatever column definition is needed\n</code></pre>\n\n<p>and since you're using Sql Server 2005 you can use the new <a href=\"http://msdn.microsoft.com/en-us/library/bb510625.aspx\" rel=\"nofollow noreferrer\">MERGE</a> statement.\n<strong>The <a href=\"http://msdn.microsoft.com/en-us/library/bb510625.aspx\" rel=\"nofollow noreferrer\">MERGE</a> statement has the advantage of being able to treat all situations in one statement</strong> like missing rows from source (can do inserts), missing rows from destination (can do deletes), matching rows (can do updates), and everything is done atomically in a single transaction. Example:</p>\n\n<pre><code>MERGE database2..targetTable AS t\nUSING (SELECT sourceColumn FROM sourceDatabase1..sourceTable) as s\nON t.PrimaryKeyCol = s.PrimaryKeyCol -- or whatever the match should be bassed on\nWHEN MATCHED THEN \n UPDATE SET t.targetColumn = s.sourceColumn\nWHEN NOT MATCHED THEN\n INSERT (targetColumn, [other columns ...]) VALUES (s.sourceColumn, [other values ..])\n</code></pre>\n\n<p>The MERGE statement was introduced to solve cases like yours and I recommend using it, it's much more powerful than solutions using multiple sql batch statements that basically accomplish the same thing MERGE does in one statement without the added complexity.</p>\n" }, { "answer_id": 343535, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>MERGE is only available in SQL 2008 NOT SQL 2005</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433/" ]
I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table. There must be a simple way of doing this. Something like: ``` INSERT INTO database1.myTable columnINeed SELECT columnINeed from database2.myTable ```
Inserting won't do it since it'll attempt to insert new rows at the end of the table. What it sounds like your trying to do is add a column to the end of existing rows. I'm not sure if the syntax is exactly right but, if I understood you then this will do what you're after. 1. Create the column allowing nulls in database2. 2. Perform an update: UPDATE database2.dbo.tablename SET database2.dbo.tablename.colname = database1.dbo.tablename.colname FROM database2.dbo.tablename INNER JOIN database1.dbo.tablename ON database2.dbo.tablename.keycol = database1.dbo.tablename.keycol
52,357
<p>I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.</p> <p>I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".</p> <ul> <li>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</li> <li>Is the only difference between clog and cerr the buffering?</li> <li>How should I implement (or find) a more robust logging facility (links please)?</li> </ul>
[ { "answer_id": 52365, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</p>\n</blockquote>\n\n<p>Yes. You want the <a href=\"http://www.cplusplus.com/reference/iostream/ios/rdbuf.html\" rel=\"noreferrer\"><code>rdbuf</code></a> function.</p>\n\n<pre><code>ofstream ofs(\"logfile\");\ncout.rdbuf(ofs.rdbuf());\ncout &lt;&lt; \"Goes to file.\" &lt;&lt; endl;\n</code></pre>\n\n<blockquote>\n <p>Is the only difference between clog and cerr the buffering?</p>\n</blockquote>\n\n<p>As far as I know, yes.</p>\n" }, { "answer_id": 52381, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 4, "selected": false, "text": "<p>If you're in a posix shell environment (I'm really thinking of bash), you can redirect any \nfile descriptor to any other file descriptor, so to redirect, you can just:</p>\n\n<pre><code>$ myprogram 2&gt;&amp;5 \n</code></pre>\n\n<p>to redirect stderr to the file represented by fd=5.</p>\n\n<p>Edit: on second thought, I like @Konrad Rudolph's answer about redirection better. rdbuf() is a more coherent and portable way to do it.</p>\n\n<p>As for logging, well...I start with the Boost library for all things C++ that isn't in the std library. Behold: <a href=\"http://www.torjo.com/log2/index.html\" rel=\"nofollow noreferrer\">Boost Logging v2</a></p>\n\n<p><strong>Edit</strong>: Boost Logging is <em>not</em> part of the Boost Libraries; it has been reviewed, but not accepted.</p>\n\n<p><strong>Edit</strong>: 2 years later, back in May 2010, Boost did accept a logging library, now called <a href=\"http://boost-log.sourceforge.net/libs/log/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost.Log</a>.</p>\n\n<p>Of course, there are alternatives:</p>\n\n<ul>\n<li><a href=\"http://log4cpp.sourceforge.net/\" rel=\"nofollow noreferrer\">Log4Cpp</a> (a log4j-style API for C++)</li>\n<li><a href=\"http://logging.apache.org/log4cxx/index.html\" rel=\"nofollow noreferrer\">Log4Cxx</a> (Apache-sponsored log4j-style API)</li>\n<li><a href=\"http://pantheios.sourceforge.net/\" rel=\"nofollow noreferrer\">Pantheios</a> (defunct? last time I tried I couldn't get it to build on a recent compiler)</li>\n<li><a href=\"https://github.com/google/glog\" rel=\"nofollow noreferrer\">Google's GLog</a> (hat-tip @SuperElectric)</li>\n</ul>\n\n<p>There's also the Windows Event logger.</p>\n\n<p>And a couple of articles that may be of use:</p>\n\n<ul>\n<li><a href=\"http://www.ddj.com/cpp/201804215\" rel=\"nofollow noreferrer\">Logging in C++ (Dr. Dobbs)</a></li>\n<li><a href=\"http://developers.sun.com/solaris/articles/logging.html\" rel=\"nofollow noreferrer\">Logging and Tracing Simplified (Sun)</a></li>\n</ul>\n" }, { "answer_id": 4476129, "author": "unixman83", "author_id": 504239, "author_profile": "https://Stackoverflow.com/users/504239", "pm_score": 1, "selected": false, "text": "<h2>Basic Logger</h2>\n\n<pre><code>#define myerr(e) {CriticalSectionLocker crit; std::cerr &lt;&lt; e &lt;&lt; std::endl;}\n</code></pre>\n\n<p>Used as <code>myerr(\"ERR: \" &lt;&lt; message);</code> or <code>myerr(\"WARN: \" &lt;&lt; message &lt;&lt; code &lt;&lt; etc);</code></p>\n\n<p>Is very effective.</p>\n\n<p>Then do:</p>\n\n<pre><code>./programname.exe 2&gt; ./stderr.log\nperl parsestderr.pl stderr.log\n</code></pre>\n\n<p><strong>or just parse stderr.log by hand</strong></p>\n\n<p>I admit this is not for <em>extremely</em> performance critical code. But who writes that anyway.</p>\n" }, { "answer_id": 56308274, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Since there are several answers here about redirection, I will add <a href=\"http://wordaligned.org/articles/cpp-streambufs\" rel=\"noreferrer\">this nice gem</a> I stumbled across recently about redirection:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n\nclass redirecter\n{\npublic:\n redirecter(std::ostream &amp; dst, std::ostream &amp; src)\n : src(src), sbuf(src.rdbuf(dst.rdbuf())) {}\n ~redirecter() { src.rdbuf(sbuf); }\nprivate:\n std::ostream &amp; src;\n std::streambuf * const sbuf;\n};\n\nvoid hello_world()\n{\n std::cout &lt;&lt; \"Hello, world!\\n\";\n}\n\nint main()\n{\n std::ofstream log(\"hello-world.log\");\n redirecter redirect(log, std::cout);\n hello_world();\n return 0;\n}\n</code></pre>\n\n<p>It's basically a redirection class that allows you to redirect any two streams, and restore it when you're finished.</p>\n" }, { "answer_id": 57314550, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "<h2>Redirections</h2>\n<p>Konrad Rudolph answer is good in regard to how to redirect the <code>std::clog</code> (<code>std::wclog</code>).</p>\n<p>Other answers tell you about various possibilities such as using a command line redirect such as <code>2&gt;output.log</code>. With Unix you can also create a file and add another output to your commands with something like <code>3&gt;output.log</code>. In your program you then have to use <code>fd</code> number 3 to print the logs. You can continue to print to <code>stdout</code> and <code>stderr</code> normally. The Visual Studio IDE has a similar feature with their <code>CDebug</code> command, which sends its output to the IDE output window.</p>\n<blockquote>\n<p><code>stderr</code> is the same as <code>stdout</code>?</p>\n</blockquote>\n<p>This is generally true, but under Unix you can setup the <code>stderr</code> to <code>/dev/console</code> which means that it goes to another <code>tty</code> (a.k.a. terminal). It's rarely used these days. I had it that way on IRIX. I would open a separate X-Window and see errors in it.</p>\n<p>Also many people send error messages to <code>/dev/null</code>. On the command line you write:</p>\n<pre><code>command ...args... 2&gt;/dev/null\n</code></pre>\n<h2>syslog</h2>\n<p>One thing not mentioned, under Unix, you also have <code>syslog()</code>.</p>\n<p>The newest versions under Linux (and probably Mac OS/X) does a lot more than it used to. Especially, it can use the identity and some other parameters to redirect the logs to a specific file (i.e. <code>mail.log</code>). The syslog mechanism can be used between computers, so logs from computer A can be sent to computer B. And of course you can filter logs in various ways, especially by severity.</p>\n<p>The <code>syslog()</code> is also very simple to use:</p>\n<pre><code>syslog(LOG_ERR, &quot;message #%d&quot;, count++);\n</code></pre>\n<p>It offers 8 levels (or severity), a format a la <code>printf()</code>, and a list of arguments for the format.</p>\n<p>Programmatically, you may tweak a few things if you first call the <code>openlog()</code> function. You must call it before your first call to <code>syslog()</code>.</p>\n<p>As mentioned by unixman83, you may want to use a macro instead. That way you can include some parameters to your messages without having to repeat them over and over again. Maybe something like this (see <a href=\"https://en.wikipedia.org/wiki/Variadic_macro\" rel=\"nofollow noreferrer\">Variadic Macro</a>):</p>\n<pre><code>// (not tested... requires msg to be a string literal)\n#define LOG(lvl, msg, ...) \\\n syslog(lvl, msg &quot; (in &quot; __FILE__ &quot;:%d)&quot;, __VA_ARGS__, __LINE__)\n</code></pre>\n<p>You may also find <code>__func__</code> useful.</p>\n<p>The redirection, filtering, etc. is done by creating configuration files. Here is <a href=\"https://github.com/m2osw/snapwebsites/blob/master/snapbounce/conf/02-mail.conf\" rel=\"nofollow noreferrer\">an example</a> from my snapwebsites project:</p>\n<pre><code>mail.err /var/log/mail/mail.err\nmail.* /var/log/mail/mail.log\n&amp; stop\n</code></pre>\n<p>I install the file under <code>/etc/rsyslog.d/</code> and run:</p>\n<pre><code>invoke-rc.d rsyslog restart\n</code></pre>\n<p>so the <code>syslog</code> server handles that change and saves any mail related logs to those folders.</p>\n<p><em>Note: I also have to create the <code>/var/log/mail</code> folder and the files inside the folder to make sure it all works right (because otherwise the mail daemon may not have enough permissions.)</em></p>\n<h2>snaplogger (a little plug)</h2>\n<p>I've used <a href=\"https://github.com/log4cplus/log4cplus\" rel=\"nofollow noreferrer\">log4cplus</a>, which, since version 1.2.x, is quite good. I have three cons about it, though:</p>\n<ol>\n<li>it requires me to completely clear everything if I want to call <code>fork();</code> somehow it does not survive a <code>fork();</code> call properly... (at least in the version I had it used a thread)</li>\n<li>the configuration files (<code>.properties</code>) are not easy to manage in my environment where I like the administrators to make changes without modifying the original</li>\n<li>it uses C++03 and we are now in 2019... I'd like to have at least C++11</li>\n</ol>\n<p>Because of that, and especially because of point (1), I wrote my own version called <a href=\"https://github.com/m2osw/snaplogger\" rel=\"nofollow noreferrer\">snaplogger</a>. This is not exactly a standalone project, though. I use many other projects from the snapcpp environment (it's much easier to just get snapcpp and run the <code>bin/build-snap</code> script or just <a href=\"https://launchpad.net/%7Esnapcpp/+archive/ubuntu/ppa\" rel=\"nofollow noreferrer\">get the binaries from launchpad</a>.)</p>\n<p>The advantage of using a logger such as snaplogger or log4cplus is that you generally can define any number of destinations and many other parameters (such as the severity level as offered by <code>syslog()</code>). The log4cplus is capable of sending its output to many different places: files, syslog, MS-Windows log system, console, a server, etc. Check out the appenders in those two projects to have an idea of the list of possibilities. The interesting factor here is that any log can be sent to all the destinations. This is useful to have a file named all.log where all your services send their logs. This allows to understand certain bugs which would not be as easy with separate log files when running many services in parallel.</p>\n<p>Here is a simple example in a snaplogger configuration file:</p>\n<pre><code>[all]\ntype=file\nlock=true\nfilename=/var/log/snapwebsites/all.log\n\n[file]\nlock=false\nfilename=/var/log/snapwebsites/firewall.log\n</code></pre>\n<p>Notice that for the <code>all.log</code> file I require a lock so multiple writers do not mangle the logs between each others. It's not necessary for the <code>[file]</code> section because I only have one process (no threads) for that one.</p>\n<p>Both offer you a way to add your own appenders. So for example if you have a Qt application with an output window, you could write an appender to send the output of the <code>SNAP_LOG_ERROR()</code> calls to that window.</p>\n<p><code>snaplogger</code> also offers you a way to extend the variable support in messages (also called the format.) For example, I can insert the date using the <code>${date}</code> variable. Then I can tweak it with a parameter. To only output the year, I use <code>${date:year}</code>. This variable parameter support is also extensible.</p>\n<p><code>snaplogger</code> can filter the output by severity (like syslog), by a regex, and by <em>component</em>. We have a <code>normal</code> and a <code>secure</code> component, the default is <code>normal</code>. I want logs sent to the <code>secure</code> component to be written to secure files. This means in a sub-directory which is way more protected than the normal logs that most admins can review. When I run my HTTP services, some times I send information such as the last 3 digits of a credit card. I prefer to have those in a secure log. It could also be password related errors. Anything I deem to be a security risk in a log, really. Again, components are extensible so you can have your own.</p>\n" }, { "answer_id": 62689338, "author": "Apteryx", "author_id": 7420896, "author_profile": "https://Stackoverflow.com/users/7420896", "pm_score": 2, "selected": false, "text": "<p>One little point about the redirecter class. It needs to be destroyed properly, and only once. The destructor will ensure this will happen if the function it is declared in actually returns, and the object itself is never copied.</p>\n<p>To ensure it can't be copied, provide private copy and assignment operators:</p>\n<pre><code>class redirecter\n{\npublic:\n redirecter(std::ostream &amp; src, std::ostream &amp; dst)\n : src_(src), sbuf(src.rdbuf(dst.rdbuf())) {}\n ~redirecter() { src.rdbuf(sbuf); }\nprivate:\n std::ostream &amp; src_;\n std::streambuf * const sbuf_;\n // Prevent copying. \n redirecter( const redirecter&amp; );\n redirecter&amp; operator=( const redirecter&amp; );\n};\n</code></pre>\n<p>I'm using this technique by redirecting std::clog to a log file in my main(). To ensure that main() actually returns, I place the guts of main() in a try/catch block. Then elsewhere in my program, where I might call exit(), I throw an exception instead. This returns control to main() which can then execute a return statement.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4662/" ]
I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr. I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)". * Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? * Is the only difference between clog and cerr the buffering? * How should I implement (or find) a more robust logging facility (links please)?
> > Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? > > > Yes. You want the [`rdbuf`](http://www.cplusplus.com/reference/iostream/ios/rdbuf.html) function. ``` ofstream ofs("logfile"); cout.rdbuf(ofs.rdbuf()); cout << "Goes to file." << endl; ``` > > Is the only difference between clog and cerr the buffering? > > > As far as I know, yes.
52,400
<p>I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q &amp; A's to be useful.</p> <p>I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. </p> <p>Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. </p>
[ { "answer_id": 52413, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 1, "selected": false, "text": "<p>At first blush it sounds more like you have two different types of users and they have different access levels. This could be solved by inheritance (PowerUser, User) or by containing a security object or token that sets the level for the user. </p>\n\n<p>If you don't like inheritance as a rule, you could use a State pattern on the application, Decorate the user objects (Shudder) or possibly add strategy patterns for differing security levels. But I think it's a little early yet, I don't normally apply patterns until I have a firm idea of how the item will grown and be maintained.</p>\n" }, { "answer_id": 52481, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 3, "selected": true, "text": "<p>Table driven designs can be effective. \nSteve Maguire had few nice examples in <em>Writing</em> <em>Solid</em> <em>Code</em> .</p>\n\n<p>They are also a great way to capture tests, see <a href=\"http://fit.c2.com/\" rel=\"nofollow noreferrer\">fit</a> .</p>\n\n<p>In your case something like:</p>\n\n<pre><code>Field1ReadonlyRules = {\n 'user class 1' : True,\n 'user class 2' : False\n}\n\nfield1.readOnly = Field1ReadonlyRules[ someUser.userClass ]\n</code></pre>\n\n<p>As an aside you probably want to model <em>both</em> users and user classes/roles/groups instead of combining them.\nA user typically captures <em>who</em> (authentication) while groups/roles capture <em>what</em> (permissions, capabilities)</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q & A's to be useful. I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either.
Table driven designs can be effective. Steve Maguire had few nice examples in *Writing* *Solid* *Code* . They are also a great way to capture tests, see [fit](http://fit.c2.com/) . In your case something like: ``` Field1ReadonlyRules = { 'user class 1' : True, 'user class 2' : False } field1.readOnly = Field1ReadonlyRules[ someUser.userClass ] ``` As an aside you probably want to model *both* users and user classes/roles/groups instead of combining them. A user typically captures *who* (authentication) while groups/roles capture *what* (permissions, capabilities)
52,430
<p>I've got the following rough structure:</p> <pre><code>Object -&gt; Object Revisions -&gt; Data </code></pre> <p>The Data can be shared between several Objects.</p> <p>What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set.</p> <p>I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... </p> <p>Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? </p> <p>I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well.</p>
[ { "answer_id": 52455, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 2, "selected": false, "text": "<p>Here is example SQL. If you have an Identity column, you can use this instead of \"ActivityDate\".</p>\n\n<pre><code>SELECT DATEDIFF(HOUR, prev.ActivityDate, curr.ActivityDate)\n FROM MyTable curr\n JOIN MyTable prev\n ON prev.ObjectID = curr.ObjectID\n WHERE prev.ActivityDate =\n (SELECT MAX(maxtbl.ActivityDate)\n FROM MyTable maxtbl\n WHERE maxtbl.ObjectID = curr.ObjectID\n AND maxtbl.ActivityDate &lt; curr.ActivityDate)\n</code></pre>\n\n<p>I could remove \"prev\", but have it there assuming you need IDs from it for deleting.</p>\n" }, { "answer_id": 52522, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 0, "selected": false, "text": "<p>Hrmm, interesting challenge. I think you can do it without a self-join if you use the new-to-2005 pivot functionality.</p>\n" }, { "answer_id": 52706, "author": "ddowns", "author_id": 5201, "author_profile": "https://Stackoverflow.com/users/5201", "pm_score": 0, "selected": false, "text": "<p>Here's what I've got so far, I wanted to give this a little more time before accepting an answer.</p>\n\n<pre><code>DECLARE @IDs TABLE \n(\n ID int , \n DateBetween int\n)\n\nDECLARE @OID int\nSET @OID = 6150\n\n-- Grab the revisions, calc the datediff, and insert into temp table var.\n\nINSERT @IDs\nSELECT ID, \n DATEDIFF(dd, \n (SELECT MAX(ActiveDate) \n FROM ObjectRevisionHistory \n WHERE ObjectID=@OID AND \n ActiveDate &lt; ORH.ActiveDate), ActiveDate) \nFROM ObjectRevisionHistory ORH \nWHERE ObjectID=@OID\n\n\n-- Hard set DateBetween for special case revisions to always keep\n\n UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MIN(ID) FROM @IDs)\n\n UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MAX(ID) FROM @IDs)\n\n UPDATE @IDs SET DateBetween = 1000 \n WHERE ID=(SELECT ID \n FROM ObjectRevisionHistory \n WHERE ObjectID=@OID AND Active=1)\n\n\n-- Select out IDs for however I need them\n\n SELECT * FROM @IDs\n SELECT * FROM @IDs WHERE DateBetween &lt; 2\n SELECT * FROM @IDs WHERE DateBetween &gt; 2\n</code></pre>\n\n<p>I'm looking to extend this so that I can keep at maximum so many revisions, and prune off the older ones while still keeping the first, last, and active. Should be easy enough through select top and order by clauses, um... and tossing in ActiveDate into the temp table.</p>\n\n<p>I got Peter's example to work, but took that and modified it into a subselect. I messed around with both and the sql trace shows the subselect doing less reads. But it does work and I'll vote him up when I get my rep high enough.</p>\n" }, { "answer_id": 21113658, "author": "cs981khx", "author_id": 3193950, "author_profile": "https://Stackoverflow.com/users/3193950", "pm_score": 2, "selected": true, "text": "<p>If the identity column is sequential you can use this approach:</p>\n\n<p><code>SELECT curr.*, DATEDIFF(MINUTE, prev.EventDateTime,curr.EventDateTime) Duration FROM DWLog curr join DWLog prev on prev.EventID = curr.EventID - 1</code></p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5201/" ]
I've got the following rough structure: ``` Object -> Object Revisions -> Data ``` The Data can be shared between several Objects. What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set. I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well.
If the identity column is sequential you can use this approach: `SELECT curr.*, DATEDIFF(MINUTE, prev.EventDateTime,curr.EventDateTime) Duration FROM DWLog curr join DWLog prev on prev.EventID = curr.EventID - 1`
52,438
<p>I've been doing c# for a long time, and have never come across an easy way to just new up a hash.</p> <p>I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.</p> <pre><code>{ "whatever" =&gt; {i =&gt; 1}; "and then something else" =&gt; {j =&gt; 2}}; </code></pre>
[ { "answer_id": 52443, "author": "Wheelie", "author_id": 1131, "author_profile": "https://Stackoverflow.com/users/1131", "pm_score": 6, "selected": true, "text": "<p>If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.</p>\n\n<p>This example is based on the <a href=\"http://msdn.microsoft.com/en-us/library/bb531208.aspx\" rel=\"noreferrer\">MSDN Example</a></p>\n\n<pre><code>var students = new Dictionary&lt;int, StudentName&gt;()\n{\n { 111, new StudentName {FirstName=\"Sachin\", LastName=\"Karnik\", ID=211}},\n { 112, new StudentName {FirstName=\"Dina\", LastName=\"Salimzianova\", ID=317, }},\n { 113, new StudentName {FirstName=\"Andy\", LastName=\"Ruth\", ID=198, }}\n};\n</code></pre>\n" }, { "answer_id": 52503, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 3, "selected": false, "text": "<p>When I'm not able to use C# 3.0, I use a helper function that translates a set of parameters into a dictionary.</p>\n\n<pre><code>public IDictionary&lt;KeyType, ValueType&gt; Dict&lt;KeyType, ValueType&gt;(params object[] data)\n{\n Dictionary&lt;KeyType, ValueType&gt; dict = new Dictionary&lt;KeyType, ValueType&gt;((data == null ? 0 :data.Length / 2));\n if (data == null || data.Length == 0) return dict;\n\n KeyType key = default(KeyType);\n ValueType value = default(ValueType);\n\n for (int i = 0; i &lt; data.Length; i++)\n {\n if (i % 2 == 0)\n key = (KeyType) data[i];\n else\n {\n value = (ValueType) data[i];\n dict.Add(key, value);\n }\n }\n\n return dict;\n}\n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>IDictionary&lt;string,object&gt; myDictionary = Dict&lt;string,object&gt;(\n \"foo\", 50,\n \"bar\", 100\n);\n</code></pre>\n" }, { "answer_id": 1863840, "author": "Quadriceps Hexa", "author_id": 226777, "author_profile": "https://Stackoverflow.com/users/226777", "pm_score": -1, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Dictionary\n{\n class Program\n {\n static void Main(string[] args)\n {\n Program p = new Program(); \n Dictionary&lt;object, object &gt; d = p.Dic&lt;object, object&gt;(\"Age\",32,\"Height\",177,\"wrest\",36);//(un)comment\n //Dictionary&lt;object, object&gt; d = p.Dic&lt;object, object&gt;();//(un)comment\n\n foreach(object o in d)\n {\n Console.WriteLine(\" {0}\",o.ToString());\n }\n Console.ReadLine(); \n }\n\n public Dictionary&lt;K, V&gt; Dic&lt;K, V&gt;(params object[] data)\n { \n //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null;\n if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary&lt;K,V&gt;(1){{ (K)new Object(), (V)new object()}};\n\n Dictionary&lt;K, V&gt; dc = new Dictionary&lt;K, V&gt;(data.Length / 2);\n int i = 0;\n while (i &lt; data.Length)\n {\n dc.Add((K)data[i], (V)data[++i]);\n i++; \n }\n return dc; \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 45072305, "author": "Matthew Lock", "author_id": 74585, "author_profile": "https://Stackoverflow.com/users/74585", "pm_score": 1, "selected": false, "text": "<p>Since C# 3.0 (.NET 3.5) hashtable literals can be specified like so:</p>\n\n<pre><code>var ht = new Hashtable {\n { \"whatever\", new Hashtable {\n {\"i\", 1} \n } },\n { \"and then something else\", new Hashtable { \n {\"j\", 2}\n } }\n};\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
I've been doing c# for a long time, and have never come across an easy way to just new up a hash. I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls. ``` { "whatever" => {i => 1}; "and then something else" => {j => 2}}; ```
If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement. This example is based on the [MSDN Example](http://msdn.microsoft.com/en-us/library/bb531208.aspx) ``` var students = new Dictionary<int, StudentName>() { { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }} }; ```
52,449
<p>Can I return it as an object if I am doing a </p> <pre><code>Select OneItem from Table Where OtherItem = "blah"? </code></pre> <p>Is there a better way to do this?</p> <p>I am building a constructor to return an object based on its name rather than its ID.</p>
[ { "answer_id": 52470, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "<p><code>query.UniqueResult&lt;T&gt;()</code> returns just one <strong>T</strong></p>\n" }, { "answer_id": 214317, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<p>If there's more than one potential result, then <code>query.FirstResult()</code> might be better.</p>\n" }, { "answer_id": 243283, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 0, "selected": false, "text": "<p>Or using LINQ you can have <code>query.First()</code>, <code>query.SingleOrDefault()</code>, <code>query.Min(predicate)</code> etc...</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Can I return it as an object if I am doing a ``` Select OneItem from Table Where OtherItem = "blah"? ``` Is there a better way to do this? I am building a constructor to return an object based on its name rather than its ID.
`query.UniqueResult<T>()` returns just one **T**
52,485
<p>I have a Question class:</p> <pre><code>class Question { public int QuestionNumber { get; set; } public string Question { get; set; } public string Answer { get; set; } } </code></pre> <p>Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use <strong>&lt;%#Eval("Question")%></strong> to display the Question, and I use a TextBox and <strong>&lt;%#Bind("Answer")%></strong> to accept an answer.</p> <p>If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer.</p> <p>So far it works great.</p> <p>Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist.</p> <p>Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing.</p> <p>I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects.</p> <p>Surely there's an easy way to achieve all of this with little or no codebehind?</p> <p>It seems like all the bits are there, but there's some glue missing to stick them all together.</p> <p>Help!</p> <p>Anthony</p>
[ { "answer_id": 52513, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": true, "text": "<p>You have to handle the postback event (button click or whatever) then enumerate the repeater items like this:</p>\n\n<pre><code>foreach(RepeaterItem item in rptQuestions.Items)\n{\n //pull out question\n var question = (Question)item.DataItem;\n question.Answer = ((TextBox)item.FindControl(\"txtAnswer\")).Text;\n\n question.Save() ? &lt;--- not sure what you want to do with it\n}\n</code></pre>\n" }, { "answer_id": 52639, "author": "littlecharva", "author_id": 366, "author_profile": "https://Stackoverflow.com/users/366", "pm_score": 0, "selected": false, "text": "<p>Then what's the point in the Bind method (as opposed to the Eval method) if I have to bind everything back up manually on postback?</p>\n" }, { "answer_id": 52725, "author": "Solmead", "author_id": 2496, "author_profile": "https://Stackoverflow.com/users/2496", "pm_score": 1, "selected": false, "text": "<p>The bind method really isn't for the repeater, it's more for the formview or gridview, where you are editing just one item in the list not every item in the list. </p>\n\n<p>On both you click a edit button which then gives you the bound controls (bound using bind) and then hit the save link which auto saves the item back into your datasource without any code behind.</p>\n" }, { "answer_id": 53722, "author": "littlecharva", "author_id": 366, "author_profile": "https://Stackoverflow.com/users/366", "pm_score": 0, "selected": false, "text": "<p>Ben: Having tried it, item.DataItem is always null, and according to the following post, it's not designed to be used that way:</p>\n\n<p><a href=\"http://www.netnewsgroups.net/group/microsoft.public.dotnet.framework.aspnet/topic4049.aspx\" rel=\"nofollow noreferrer\">http://www.netnewsgroups.net/group/microsoft.public.dotnet.framework.aspnet/topic4049.aspx</a></p>\n\n<p>So how on earth do I manually bind it back?</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
I have a Question class: ``` class Question { public int QuestionNumber { get; set; } public string Question { get; set; } public string Answer { get; set; } } ``` Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use **<%#Eval("Question")%>** to display the Question, and I use a TextBox and **<%#Bind("Answer")%>** to accept an answer. If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer. So far it works great. Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist. Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing. I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects. Surely there's an easy way to achieve all of this with little or no codebehind? It seems like all the bits are there, but there's some glue missing to stick them all together. Help! Anthony
You have to handle the postback event (button click or whatever) then enumerate the repeater items like this: ``` foreach(RepeaterItem item in rptQuestions.Items) { //pull out question var question = (Question)item.DataItem; question.Answer = ((TextBox)item.FindControl("txtAnswer")).Text; question.Save() ? <--- not sure what you want to do with it } ```
52,506
<p>A friend and I were discussing C++ templates. He asked me what this should do:</p> <pre><code>#include &lt;iostream&gt; template &lt;bool&gt; struct A { A(bool) { std::cout &lt;&lt; "bool\n"; } A(void*) { std::cout &lt;&lt; "void*\n"; } }; int main() { A&lt;true&gt; *d = 0; const int b = 2; const int c = 1; new A&lt; b &gt; (c) &gt; (d); } </code></pre> <p>The last line in main has two reasonable parses. Is 'b' the template argument or is <code>b &gt; (c)</code> the template argument? </p> <p>Although, it is trivial to compile this, and see what we get, we were wondering what resolves the ambiguity?</p>
[ { "answer_id": 52515, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>The greediness of the lexer is probably the determining factor in the absence of parentheses to make it explicit. I'd guess that the lexer isn't greedy.</p>\n" }, { "answer_id": 52617, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": true, "text": "<p>AFAIK it would be compiled as <code>new A&lt;b>(c) > d</code>. This is the only reasonable way to parse it IMHO. If the parser can't assume under normal circumstances a > end a template argument, that would result it much more ambiguity. If you want it the other way, you should have written:</p>\n\n<pre><code>new A&lt;(b &gt; c)&gt;(d);\n</code></pre>\n" }, { "answer_id": 52875, "author": "Lee Baldwin", "author_id": 5200, "author_profile": "https://Stackoverflow.com/users/5200", "pm_score": 2, "selected": false, "text": "<p>The C++ standard defines that if for a template name followed by a <code>&lt;</code>, the <code>&lt;</code> is always the beginning of the template argument list and the first non-nested <code>&gt;</code> is taken as the end of the template argument list.</p>\n\n<p>If you intended that the result of the <code>&gt;</code> operator be the template argument, then you'd need to enclose the expression in parentheses. You don't need parentheses if the argument was part of a <code>static_cast&lt;&gt;</code> or another template expression. </p>\n" }, { "answer_id": 71706, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": "<p>As stated by Leon &amp; Lee, 14.2/3 (C++ '03) explicitly defines this behaviour.</p>\n\n<p>C++ '0x adds to the fun with a similar rule applying to <code>&gt;&gt;</code>. The basic concept, is that when parsing a template-argument-list a non nested <code>&gt;&gt;</code> will be treated as two distinct <code>&gt;</code> <code>&gt;</code> tokens and not the right shift operator:</p>\n\n<pre><code>template &lt;bool&gt;\nstruct A {\n A(bool);\n A(void*);\n};\n\ntemplate &lt;typename T&gt;\nclass C\n{\npublic:\n C (int);\n};\n\nint main() {\n A&lt;true&gt; *d = 0;\n const int b = 2;\n const int c = 1;\n new C &lt;A&lt; b &gt;&gt; (c) &gt; (d); // #1\n new C &lt;A&lt; b &gt; &gt; (c) &gt; (d); // #2\n}\n</code></pre>\n\n<p>'#1' and '#2' are equivalent in the above.</p>\n\n<p>This of course fixes that annoyance with having to add spaces in nested specializations:</p>\n\n<pre><code>C&lt;A&lt;false&gt;&gt; c; // Parse error in C++ '98, '03 due to \"right shift operator\"\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4798/" ]
A friend and I were discussing C++ templates. He asked me what this should do: ``` #include <iostream> template <bool> struct A { A(bool) { std::cout << "bool\n"; } A(void*) { std::cout << "void*\n"; } }; int main() { A<true> *d = 0; const int b = 2; const int c = 1; new A< b > (c) > (d); } ``` The last line in main has two reasonable parses. Is 'b' the template argument or is `b > (c)` the template argument? Although, it is trivial to compile this, and see what we get, we were wondering what resolves the ambiguity?
AFAIK it would be compiled as `new A<b>(c) > d`. This is the only reasonable way to parse it IMHO. If the parser can't assume under normal circumstances a > end a template argument, that would result it much more ambiguity. If you want it the other way, you should have written: ``` new A<(b > c)>(d); ```
52,550
<p>What does the <code>,</code> operator do in C?</p>
[ { "answer_id": 52558, "author": "lillq", "author_id": 2064, "author_profile": "https://Stackoverflow.com/users/2064", "pm_score": 8, "selected": true, "text": "<p>The expression:</p>\n<pre><code>(expression1, expression2)\n</code></pre>\n<p>First <code>expression1</code> is evaluated, then <code>expression2</code> is evaluated, and the value of <code>expression2</code> is returned for the whole expression.</p>\n" }, { "answer_id": 52559, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": false, "text": "<p>It causes the evaluation of multiple statements, but uses only the last one as a resulting value (rvalue, I think).</p>\n\n<p>So...</p>\n\n<pre><code>int f() { return 7; }\nint g() { return 8; }\n\nint x = (printf(\"assigning x\"), f(), g() );\n</code></pre>\n\n<p>should result in x being set to 8.</p>\n" }, { "answer_id": 52571, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>As earlier answers have stated it evaluates all statements but uses the last one as the value of the expression. Personally I've only found it useful in loop expressions:</p>\n\n<pre><code>for (tmp=0, i = MAX; i &gt; 0; i--)\n</code></pre>\n" }, { "answer_id": 52590, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 2, "selected": false, "text": "<p>The only place I've seen it being useful is when you write a funky loop where you want to do multiple things in one of the expressions (probably the init expression or loop expression. Something like:</p>\n\n<pre><code>bool arraysAreMirrored(int a1[], int a2[], size_t size)\n{\n size_t i1, i2;\n for(i1 = 0, i2 = size - 1; i1 &lt; size; i1++, i2--)\n {\n if(a1[i1] != a2[i2])\n {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>Pardon me if there are any syntax errors or if I mixed in anything that's not strict C. I'm not arguing that the , operator is good form, but that's what you could use it for. In the case above I'd probably use a <code>while</code> loop instead so the multiple expressions on init and loop would be more obvious. (And I'd initialize i1 and i2 inline instead of declaring and then initializing.... blah blah blah.)</p>\n" }, { "answer_id": 52615, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 7, "selected": false, "text": "<p>I've seen used most in <code>while</code> loops:</p>\n\n<pre><code>string s;\nwhile(read_string(s), s.len() &gt; 5)\n{\n //do something\n}\n</code></pre>\n\n<p>It will do the operation, then do a test based on a side-effect. The other way would be to do it like this:</p>\n\n<pre><code>string s;\nread_string(s);\nwhile(s.len() &gt; 5)\n{\n //do something\n read_string(s);\n}\n</code></pre>\n" }, { "answer_id": 57573, "author": "Paul Stephenson", "author_id": 5536, "author_profile": "https://Stackoverflow.com/users/5536", "pm_score": 5, "selected": false, "text": "<p>The comma operator combines the two expressions either side of it into one, evaluating them both in left-to-right order. The value of the right-hand side is returned as the value of the whole expression.\n <code>(expr1, expr2)</code> is like <code>{ expr1; expr2; }</code> but you can use the result of <code>expr2</code> in a function call or assignment.</p>\n\n<p>It is often seen in <code>for</code> loops to initialise or maintain multiple variables like this:</p>\n\n<pre><code>for (low = 0, high = MAXSIZE; low &lt; high; low = newlow, high = newhigh)\n{\n /* do something with low and high and put new values\n in newlow and newhigh */\n}\n</code></pre>\n\n<p>Apart from this, I've only used it \"in anger\" in one other case, when wrapping up two operations that should always go together in a macro. We had code that copied various binary values into a byte buffer for sending on a network, and a pointer maintained where we had got up to:</p>\n\n<pre><code>unsigned char outbuff[BUFFSIZE];\nunsigned char *ptr = outbuff;\n\n*ptr++ = first_byte_value;\n*ptr++ = second_byte_value;\n\nsend_buff(outbuff, (int)(ptr - outbuff));\n</code></pre>\n\n<p>Where the values were <code>short</code>s or <code>int</code>s we did this:</p>\n\n<pre><code>*((short *)ptr)++ = short_value;\n*((int *)ptr)++ = int_value;\n</code></pre>\n\n<p>Later we read that this was not really valid C, because <code>(short *)ptr</code> is no longer an l-value and can't be incremented, although our compiler at the time didn't mind. To fix this, we split the expression in two:</p>\n\n<pre><code>*(short *)ptr = short_value;\nptr += sizeof(short);\n</code></pre>\n\n<p>However, this approach relied on all developers remembering to put both statements in all the time. We wanted a function where you could pass in the output pointer, the value and and the value's type. This being C, not C++ with templates, we couldn't have a function take an arbitrary type, so we settled on a macro:</p>\n\n<pre><code>#define ASSIGN_INCR(p, val, type) ((*((type) *)(p) = (val)), (p) += sizeof(type))\n</code></pre>\n\n<p>By using the comma operator we were able to use this in expressions or as statements as we wished:</p>\n\n<pre><code>if (need_to_output_short)\n ASSIGN_INCR(ptr, short_value, short);\n\nlatest_pos = ASSIGN_INCR(ptr, int_value, int);\n\nsend_buff(outbuff, (int)(ASSIGN_INCR(ptr, last_value, int) - outbuff));\n</code></pre>\n\n<p>I'm not suggesting any of these examples are good style! Indeed, I seem to remember Steve McConnell's <em>Code Complete</em> advising against even using comma operators in a <code>for</code> loop: for readability and maintainability, the loop should be controlled by only one variable, and the expressions in the <code>for</code> line itself should only contain loop-control code, not other extra bits of initialisation or loop maintenance.</p>\n" }, { "answer_id": 18444099, "author": "Shafik Yaghmour", "author_id": 1708801, "author_profile": "https://Stackoverflow.com/users/1708801", "pm_score": 6, "selected": false, "text": "<p>The <a href=\"https://en.wikipedia.org/wiki/Comma_operator\" rel=\"noreferrer\">comma operator</a> will evaluate the left operand, discard the result and then evaluate the right operand and that will be the result. The <em>idiomatic</em> use as noted in the link is when initializing the variables used in a <code>for</code> loop, and it gives the following example:</p>\n\n<pre><code>void rev(char *s, size_t len)\n{\n char *first;\n for ( first = s, s += len - 1; s &gt;= first; --s)\n /*^^^^^^^^^^^^^^^^^^^^^^^*/ \n putchar(*s);\n}\n</code></pre>\n\n<p>Otherwise there are not many <em>great</em> uses of the <em>comma operator</em>, although it is easy to abuse to generate code that is hard to read and maintain.</p>\n\n<p>From the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\" rel=\"noreferrer\">draft C99 standard</a> the grammar is as follows:</p>\n\n<pre><code>expression:\n assignment-expression\n expression , assignment-expression\n</code></pre>\n\n<p>and <em>paragraph 2</em> says:</p>\n\n<blockquote>\n <p>The <strong>left operand of a comma operator is evaluated as a void expression;</strong> there is a sequence point after its evaluation. Then the <strong>right operand is evaluated; the result has its type and value.</strong> <sup>97)</sup> If an attempt is made to modify the result of a comma operator or to access it after the next sequence point, the behavior is undefined.</p>\n</blockquote>\n\n<p><em>Footnote 97</em> says:</p>\n\n<blockquote>\n <p>A comma operator does <strong>not yield an lvalue</strong>.</p>\n</blockquote>\n\n<p>which means you can not assign to the result of the <em>comma operator</em>.</p>\n\n<p>It is important to note that the comma operator has the <a href=\"https://en.cppreference.com/w/c/language/operator_precedence\" rel=\"noreferrer\">lowest precedence</a> and therefore there are cases where using <code>()</code> can make a big difference, for example:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n int x, y ;\n\n x = 1, 2 ;\n y = (3,4) ;\n\n printf( \"%d %d\\n\", x, y ) ;\n}\n</code></pre>\n\n<p>will have the following output:</p>\n\n<pre><code>1 4\n</code></pre>\n" }, { "answer_id": 54038455, "author": "ViNi89", "author_id": 5770705, "author_profile": "https://Stackoverflow.com/users/5770705", "pm_score": -1, "selected": false, "text": "<p>I'm reviving this simply to address questions from @Rajesh and @JeffMercado which i think are very important since this is one of the top search engine hits.</p>\n\n<p>Take the following snippet of code for example </p>\n\n<pre><code>int i = (5,4,3,2,1);\nint j;\nj = 5,4,3,2,1;\nprintf(\"%d %d\\n\", i , j);\n</code></pre>\n\n<p>It will print</p>\n\n<pre><code>1 5\n</code></pre>\n\n<p>The <code>i</code> case is handled as explained by most answers. All expressions are evaluated in left-to-right order but only the last one is assigned to <code>i</code>. The result of the <code>(</code> <em>expression</em> )<code>is</code>1`. </p>\n\n<p>The <code>j</code> case follows different precedence rules since <code>,</code> has the lowest operator precedence. Because of those rules, the compiler sees <em>assignment-expression, constant, constant ...</em>. The expressions are again evaluated in left-to-right order and their side-effects stay visible, therefore, <code>j</code> is <code>5</code> as a result of <code>j = 5</code>.</p>\n\n<p>Interstingly, <code>int j = 5,4,3,2,1;</code> is not allowed by the language spec. An <em>initializer</em> expects an <em>assignment-expression</em> so a direct <code>,</code> operator is not allowed.</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064/" ]
What does the `,` operator do in C?
The expression: ``` (expression1, expression2) ``` First `expression1` is evaluated, then `expression2` is evaluated, and the value of `expression2` is returned for the whole expression.
52,561
<p>What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?</p> <p>Thanks!</p>
[ { "answer_id": 52570, "author": "Espen Herseth Halvorsen", "author_id": 1542, "author_profile": "https://Stackoverflow.com/users/1542", "pm_score": 2, "selected": true, "text": "<p>Nettuts has a great introduction to web-developement for iPhone. You find it <a href=\"http://nettuts.com/misc/learn-how-to-develop-for-the-iphone/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>This is the specific code you asked for (taken from that article):</p>\n\n<pre><code>&lt;!--#if expr=\"(${HTTP_USER_AGENT} = /iPhone/)\"--&gt; \n\n&lt;!-- \nplace iPhone code in here \n--&gt; \n\n&lt;!--#else --&gt; \n\n&lt;!-- \n place standard code to be used by non iphone browser. \n--&gt; \n&lt;!--#endif --&gt; \n</code></pre>\n" }, { "answer_id": 52579, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>Apple defines the user agent <a href=\"http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/chapter_3_section_3.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>This field is transmitted in the HTTP headers under the key \"User-Agent\"</p>\n" }, { "answer_id": 54369, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 2, "selected": false, "text": "<p>Apple has some excellent guidelines for iPhone web page development here:</p>\n\n<p><a href=\"http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40002079-SW1\" rel=\"nofollow noreferrer\">Safari Web Content Guide for iPhone</a></p>\n\n<p>From my brief reading of it, here are a key elements to look out for: </p>\n\n<ul>\n<li>The way the \"viewport\" and scrolling works is a bit different due to the small screen size. There are custom META tags that let you adjust this automatically when someone comes to your page.</li>\n<li>Beware pages that use framesets or other features that require the user to scroll different elements on the page, because the iPhone does not display scrollbars. </li>\n<li>If you expect people to bookmark your page on the iPhone, there's a custom META tag that lets you specify a 53x53 icon that will look nicer than the typical favorite.ico.</li>\n<li>Avoid javascript that depends on mouse movement or hover actions to make things happen, they won't work right on iPhone.</li>\n<li>There are some custom CSS properties that allow you to adjust text size and highlight color of hyperlinks on the iPhone.</li>\n<li>There are other key HTML/Javascript features that they tell you to either favor or avoid as well.</li>\n</ul>\n" }, { "answer_id": 3119990, "author": "Jimit", "author_id": 317834, "author_profile": "https://Stackoverflow.com/users/317834", "pm_score": 0, "selected": false, "text": "<p>Better Solution:</p>\n\n<pre><code>*\n\n (NSString *)flattenHTML:(NSString *)html {\n\n NSScanner *theScanner; NSString *text = nil;\n\n theScanner = [NSScanner scannerWithString:html];\n\n while ([theScanner isAtEnd] == NO) {\n\n // find start of tag\n [theScanner scanUpToString:@\"&lt;\" intoString:NULL] ; \n\n\n // find end of tag\n [theScanner scanUpToString:@\"&gt;\" intoString:&amp;text] ;\n\n\n // replace the found tag with a space\n //(you can filter multi-spaces out later if you wish)\n html = [html stringByReplacingOccurrencesOfString:\n [ NSString stringWithFormat:@\"%@&gt;\", text]\n withString:@\" \"];\n\n } // while //\n\n return html;\n</code></pre>\n\n<p>}</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808/" ]
What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site? Thanks!
Nettuts has a great introduction to web-developement for iPhone. You find it [here](http://nettuts.com/misc/learn-how-to-develop-for-the-iphone/) This is the specific code you asked for (taken from that article): ``` <!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"--> <!-- place iPhone code in here --> <!--#else --> <!-- place standard code to be used by non iphone browser. --> <!--#endif --> ```
52,563
<p>I'm trying to let an <code>&lt;input type="text"&gt;</code> (henceforth referred to as “textbox”) fill a parent container by settings its <code>width</code> to <code>100%</code>. This works until I give the textbox a padding. This is then added to the content width and the input field overflows. Notice that in Firefox this only happens when rendering the content as standards compliant. In quirks mode, another box model seems to apply.</p> <p>Here's a minimal code to reproduce the behaviour in all modern browsers.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#x { background: salmon; padding: 1em; } #y, input { background: red; padding: 0 20px; width: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="x"&gt; &lt;div id="y"&gt;x&lt;/div&gt; &lt;input type="text"/&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>My question: <strong>How do I get the textbox to fit the container?</strong></p> <p><em>Notice</em>: for the <code>&lt;div id="y"&gt;</code>, this is straightforward: simply set <code>width: auto</code>. However, if I try to do this for the textbox, the effect is different and the textbox takes its default row count as width (even if I set <code>display: block</code> for the textbox).</p> <p>EDIT: David's solution would of course work. However, I do not want to modify the HTML – I do especially not want to add dummy elements with no semantic functionality. This is a typical case of <a href="http://en.wiktionary.org/wiki/Citations:divitis" rel="nofollow noreferrer">divitis</a> that I want to avoid at all cost. This can only be a last-resort hack.</p>
[ { "answer_id": 52575, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>i believe you can counter the overflow with a negative margin. ie</p>\n\n<pre><code>margin: -1em;\n</code></pre>\n" }, { "answer_id": 52633, "author": "David Kolar", "author_id": 3283, "author_profile": "https://Stackoverflow.com/users/3283", "pm_score": 5, "selected": false, "text": "<p>You can surround the textbox with a <code>&lt;div&gt;</code> and give that <code>&lt;div&gt;</code> <code>padding: 0 20px</code>. Your problem is that the 100% width does not include any padding or margin values; these values are added on top of the 100% width, thus the overflow.</p>\n" }, { "answer_id": 52896, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 1, "selected": false, "text": "<p>This behavior is caused by the different interpretations of the box model. The correct box model states that the width applies only to the content and padding and margin add on to it. So therefore your are getting 100% plus a 20px right and left padding equaling 100%+40px as the total width. The original IE box model, also known as quirks mode, includes padding and margin in the width. So the width of your content would be 100% - 40px in this case. This is why you see two different behaviors. As far as I know there is no solution for this there is however a work around by setting the width to say 98% and the padding to 1% on each side.</p>\n" }, { "answer_id": 52985, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 1, "selected": false, "text": "<p>@Domenic this does not work. width auto does nothing more then the default behavior of that element because the initial value of width is auto ( see page 164, Cascading Style Sheets Level 2 Revision 1 Specification). Assigning a display of type block does not work either, this simply tell the browser to use a block box when displaying the element and does not assign a default behavior of taking as much space as possible like a div does ( see page 121, Cascading Style Sheets Level 2 Revision 1 Specification). That behavior is handled by the visual user agent not CSS or HTML definition.</p>\n" }, { "answer_id": 53074, "author": "Ben", "author_id": 5005, "author_profile": "https://Stackoverflow.com/users/5005", "pm_score": 2, "selected": false, "text": "<p>Because of the way the <a href=\"http://reference.sitepoint.com/css/boxmodel\" rel=\"nofollow noreferrer\">Box-Modell</a> is defined and implemented I don't think there is a css-only solution to this problem. (Apart from what <a href=\"https://stackoverflow.com/questions/52563/css-textbox-to-fill-parent-container#52896\">Matthew</a> described: using percentage for the padding as well, e.g. width: 94%; padding: 0 3%;)</p>\n\n<p>You could however build some Javascript-Code to calculate the width dynmically on page-load... hm, and that value would of course also have to be updated every time the browserwindow is resized. </p>\n\n<p>Interesting by-product of some testing I've done: Firefox <strong>does</strong> set the width of an input field to 100% if additionally to <code>width: 100%;</code> you also set max-width to 100%. This doesn't work in Opera 9.5 or IE 7 though (haven't tested older versions).</p>\n" }, { "answer_id": 1082765, "author": "Aseem Kishore", "author_id": 132978, "author_profile": "https://Stackoverflow.com/users/132978", "pm_score": 2, "selected": false, "text": "<p>This is unfortunately not possible with pure CSS; HTML or Javascript modifications are necessary for any non-trivial flexible-but-constrained UI behavior. CSS3 columns will help in this regard somewhat, but not in scenarios like yours.</p>\n\n<p>David's solution is the cleanest. It's not really a case of divitis -- you're not adding a bunch of divs unnecessarily, or giving them classnames like \"p\" and \"h1\". It's serving a specific purpose, and the nice thing in this case is that it's also an extensible solution -- e.g. you can then add rounded corners at any time without adding anything further. Accessibility also isn't affected, as they're empty divs.</p>\n\n<p>Fwiw, here's how I implement all of my textboxes:</p>\n\n<pre><code>&lt;div class=\"textbox\" id=\"username\"&gt;\n &lt;div class=\"before\"&gt;&lt;/div&gt;\n &lt;div class=\"during\"&gt;\n &lt;input type=\"text\" value=\"\" /&gt;\n &lt;/div&gt;\n &lt;div class=\"after\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You're then free to use CSS to add rounded corners, add padding like in your case, etc., but you also don't have to -- you're free to hide those side divs altogether and have just a regular input textbox.</p>\n\n<p>Other solutions are to use tables, e.g. Amazon uses tables in order to get flexible-but-constrained layout, or to use Javascript to tweak the sizes and update them on window resizes, e.g. Google Docs, Maps, etc. all do this.</p>\n\n<p>Anyway, my two cents: don't let idealism get in the way of practicality in cases like this. :) David's solution works and hardly clutters up HTML at all (and in fact, using semantic classnames like \"before\" and \"after\" is still very clean imo).</p>\n" }, { "answer_id": 4472431, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 0, "selected": false, "text": "<p>The default padding and border will prevent your textbox from truly being 100%, so first you have to set them to 0:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input {\n background: red;\n padding: 0;\n width: 100%;\n border: 0; //use 0 instead of \"none\" for ie7 \n}\n</code></pre>\n\n<p>Then, put your border and any padding or margin you want in a div around the textbox:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.text-box {\n padding: 0 20px;\n border: solid 1px #000000;\n}\n\n&lt;body&gt;\n &lt;div id=\"x\"&gt;\n &lt;div id=\"y\"&gt;x&lt;/div&gt;\n &lt;div class=\"text-box\"&gt;&lt;input type=\"text\"/&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>This should allow your textbox to be expandable and the exact size you want without javascript.</p>\n" }, { "answer_id": 5405832, "author": "studioromeo", "author_id": 308886, "author_profile": "https://Stackoverflow.com/users/308886", "pm_score": 6, "selected": true, "text": "<p>With CSS3 you can use the box-sizing property on your inputs to standardise their box models.\nSomething like this would enable you to add padding and have 100% width:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input[type=\"text\"] {\n -webkit-box-sizing: border-box; // Safari/Chrome, other WebKit\n -moz-box-sizing: border-box; // Firefox, other Gecko\n box-sizing: border-box; // Opera/IE 8+\n}\n</code></pre>\n\n<p>Unfortunately this won't work for IE6/7 but the rest are fine (<a href=\"http://www.quirksmode.org/css/user-interface/\" rel=\"noreferrer\">Compatibility List</a>), so if you need to support these browsers your best bet would be Davids solution.</p>\n\n<p>If you'd like to read more check out <a href=\"http://css-tricks.com/box-sizing/\" rel=\"noreferrer\">this brilliant article by Chris Coyier</a>.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 59520751, "author": "Andyba", "author_id": 1851028, "author_profile": "https://Stackoverflow.com/users/1851028", "pm_score": 2, "selected": false, "text": "<p><strong>How do I get the textbox to fit the container in 2019?</strong></p>\n\n<p>Just use display: flex;</p>\n\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-css lang-css prettyprint-override\"><code>#x {\r\n background: salmon;\r\n padding: 1em;\r\n display: flex;\r\n flex-wrap: wrap;\r\n}\r\n\r\n#y, input {\r\n background: red;\r\n padding: 0 20px;\r\n width: 100%;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"x\"&gt;\r\n &lt;div id=\"y\"&gt;x&lt;/div&gt;\r\n &lt;input type=\"text\"/&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63966907, "author": "hoang21", "author_id": 3579956, "author_profile": "https://Stackoverflow.com/users/3579956", "pm_score": 0, "selected": false, "text": "<p>To make the input fill up width of parent, there're 3 attributes to set: width: 100%, margin-left: 0, margin-right: 0.</p>\n<p>I just guess zero margin setting can help, and I had tried it, however I don't know why margin (left and right; of course top and bottom margins don't affect here) should to be zero to make it works. :-)</p>\n<pre><code>input {\n width: 100%;\n margin-left: 0;\n margin-right: 0;\n}\n</code></pre>\n<p>Note: You may need to set box-sizing to border-box to make sure the padding don't affect the result.</p>\n" }, { "answer_id": 64799327, "author": "G Hasse", "author_id": 9923799, "author_profile": "https://Stackoverflow.com/users/9923799", "pm_score": 0, "selected": false, "text": "<p>I use to solve this with CSS-only tables. A little bit long example but\nimportant for all who wants to make entry screens for large amount of fields\nfor databases...</p>\n<p>// GH</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>// NO JAVA !!! ;-)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n height: 100%;\n}\n\nbody {\n position: fixed;\n margin: 0px;\n padding: 0px;\n border: 2px solid #FF0000;\n width: calc(100% - 4px);\n /* Demonstrate how form can fill body */\n min-height: calc(100% - 120px);\n margin-top: 60px;\n margin-bottom: 60px;\n}\n\n\n/* Example how to make a data entry form */\n\n.rx-form {\n display: table;\n table-layout: fixed;\n border: 1px solid #0000FF;\n width: 100%;\n border-collapse: separate;\n border-spacing: 5px;\n}\n\n.rx-caption {\n display: table-caption;\n border: 1px solid #000000;\n text-align: center;\n padding: 10px;\n margin: 10px;\n width: calc(100% - 40px);\n font-size: 2.5em;\n}\n\n.rx-row {\n display: table-row;\n /* To make frame on rows. Rows have no border... ? */\n box-shadow: 0px 0px 0px 1px rgb(0, 0, 0);\n}\n\n.rx-cell {\n display: table-cell;\n margin: 0px;\n padding: 4px;\n border: 1px solid #FF0000;\n}\n\n.rx-cell label {\n float: left;\n border: 1px solid #00FF00;\n width: 110px;\n padding: 4px;\n font-size: 1em;\n text-align: right;\n font-family: Arial, Helvetica, sans-serif;\n overflow: hidden;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.rx-cell label:after {\n content: \" :\";\n}\n\n.rx-cell input[type='text'] {\n float: right;\n border: 1px solid #FF00FF;\n padding: 4px;\n background-color: #eee;\n border-radius: 0px;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 1em;\n /* Fill the cell - but subtract the label width - and litte more... */\n width: calc(100% - 130px);\n overflow: hidden;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\ninput[type='submit'] {\n font-size: 1.3em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\n&lt;meta charset=\"UTF-8\"&gt;\n\n&lt;body&gt;\n\n &lt;!-- \n G Hasse, gorhas at raditex dot nu \n This example have a lot of frames so we \n can experiment with padding and margins. \n --&gt;\n\n &lt;form&gt;\n\n &lt;div class='rx-form'&gt;\n\n\n &lt;div class='rx-caption'&gt;\n Caption\n &lt;/div&gt;\n\n\n &lt;!-- First row of entry --&gt;\n\n &lt;div class='rx-row'&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input11\"&gt;Label 1-1&lt;/label&gt;\n &lt;input type=\"text\" name=\"input11\" id=\"input11\" value=\"Some latin text here. And if it is very long it will get ellipsis\" /&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input12\"&gt;Label 1-2&lt;/label&gt;\n &lt;input type=\"text\" name=\"input12\" id=\"input12\" value=\"The content of input 2\" /&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input13\"&gt;Label 1-3&lt;/label&gt;\n &lt;input type=\"text\" name=\"input13\" id=\"input13\" value=\"Content 3\" /&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input14\"&gt;Label 1-4&lt;/label&gt;\n &lt;input type=\"text\" name=\"input14\" id=\"input14\" value=\"Content 4\" /&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;!-- Next row of entry --&gt;\n\n &lt;div class='rx-row'&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input21\"&gt;Label 2-1&lt;/label&gt;\n &lt;input type=\"text\" name=\"input21\" id=\"input21\" value=\"Content 2-1\"&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input22\"&gt;Label 2-2&lt;/label&gt;\n &lt;input type=\"text\" name=\"input22\" id=\"input22\" value=\"Content 2-2\"&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input23\"&gt;Label 2-3&lt;/label&gt;\n &lt;input type=\"text\" name=\"input23\" id=\"input23\" value=\"Content 2-3\"&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n\n &lt;!-- Next row of entry --&gt;\n\n &lt;div class='rx-row'&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input21\"&gt;Label 2-1&lt;/label&gt;\n &lt;input type=\"text\" name=\"input21\" id=\"input21\" value=\"Content 2-1\"&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input22\"&gt;Label 2-2&lt;/label&gt;\n &lt;input type=\"text\" name=\"input22\" id=\"input22\" value=\"Content 2-2\"&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;label for=\"input23\"&gt;Label 2-3&lt;/label&gt;\n &lt;input type=\"text\" name=\"input23\" id=\"input23\" value=\"Content 2-3\"&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;!-- And some text in cells --&gt;\n\n &lt;div class='rx-row'&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;div&gt;Cell content&lt;/div&gt;\n &lt;/div&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;span&gt;Cell content&lt;/span&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n\n\n &lt;!-- And we place the submit buttons in a cell --&gt;\n\n &lt;div class='rx-row'&gt;\n\n &lt;div class='rx-cell'&gt;\n &lt;input type=\"submit\" name=\"submit1\" value=\"submit1\" /&gt;\n &lt;input type=\"submit\" name=\"submit2\" value=\"submit2\" /&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;!-- End of form --&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n\n&lt;/body&gt;\n\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
I'm trying to let an `<input type="text">` (henceforth referred to as “textbox”) fill a parent container by settings its `width` to `100%`. This works until I give the textbox a padding. This is then added to the content width and the input field overflows. Notice that in Firefox this only happens when rendering the content as standards compliant. In quirks mode, another box model seems to apply. Here's a minimal code to reproduce the behaviour in all modern browsers. ```css #x { background: salmon; padding: 1em; } #y, input { background: red; padding: 0 20px; width: 100%; } ``` ```html <div id="x"> <div id="y">x</div> <input type="text"/> </div> ``` My question: **How do I get the textbox to fit the container?** *Notice*: for the `<div id="y">`, this is straightforward: simply set `width: auto`. However, if I try to do this for the textbox, the effect is different and the textbox takes its default row count as width (even if I set `display: block` for the textbox). EDIT: David's solution would of course work. However, I do not want to modify the HTML – I do especially not want to add dummy elements with no semantic functionality. This is a typical case of [divitis](http://en.wiktionary.org/wiki/Citations:divitis) that I want to avoid at all cost. This can only be a last-resort hack.
With CSS3 you can use the box-sizing property on your inputs to standardise their box models. Something like this would enable you to add padding and have 100% width: ```css input[type="text"] { -webkit-box-sizing: border-box; // Safari/Chrome, other WebKit -moz-box-sizing: border-box; // Firefox, other Gecko box-sizing: border-box; // Opera/IE 8+ } ``` Unfortunately this won't work for IE6/7 but the rest are fine ([Compatibility List](http://www.quirksmode.org/css/user-interface/)), so if you need to support these browsers your best bet would be Davids solution. If you'd like to read more check out [this brilliant article by Chris Coyier](http://css-tricks.com/box-sizing/). Hope this helps!
52,591
<p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p> <pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate '' 10 words args.IsValid = args.Value.Split(" ").Length &lt;= 10 End Sub </code></pre> <p>Does anyone have a more thorough/accurate method of getting a word count?</p>
[ { "answer_id": 52610, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<p>You can use one of the builtin validators with a regex that counts the words.</p>\n\n<p>I'm a little rusty with regex so go easy on me:</p>\n\n<pre><code>(\\b.*\\b){0,10}\n</code></pre>\n" }, { "answer_id": 52625, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I voted for mharen's answer, and commented on it as well, but since the comments are hidden by default let me explain it again:</p>\n\n<p>The reason you would want to use the regex validator rather than the custom validator is that the regex validator will also automatically validate the regex client-side using javascript, if it's available. If they pass validation it's no big deal, but every time someone fails the client-side validation you save your server from doing a postback.</p>\n" }, { "answer_id": 52737, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": true, "text": "<p>This regex seems to be working great:</p>\n\n<pre><code>\"^(\\b\\S+\\b\\s*){0,10}$\"\n</code></pre>\n\n<p><strong>Update</strong>: the above had a few flaws so I ended up using this RegEx:</p>\n\n<pre><code>[\\s\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\xBF]+\n</code></pre>\n\n<p>I <code>split()</code> the string on that regex and use the <code>length</code> of the resulting array to get the correct word count.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method: ``` Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate '' 10 words args.IsValid = args.Value.Split(" ").Length <= 10 End Sub ``` Does anyone have a more thorough/accurate method of getting a word count?
This regex seems to be working great: ``` "^(\b\S+\b\s*){0,10}$" ``` **Update**: the above had a few flaws so I ended up using this RegEx: ``` [\s\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\xBF]+ ``` I `split()` the string on that regex and use the `length` of the resulting array to get the correct word count.
52,600
<p>I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects.</p> <pre><code>CorpObject o = new CorpObject(); Int32 result = o.DoSomethingLousy(); </code></pre> <p>While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it?</p>
[ { "answer_id": 52609, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>The PDB is a database file that maps the instructions to their line numbers in the original code so when you get a stack trace you'll get the line numbers for the code. If it's an unmanaged DLL then the PDB file will also give you the names of the functions in the stack trace, whereas that information is usually only available for managed DLLs without PDBs.</p>\n" }, { "answer_id": 52611, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>The main I get from the pdb is line numbers and real method names for stack traces.</p>\n" }, { "answer_id": 52705, "author": "JeffJ", "author_id": 5429, "author_profile": "https://Stackoverflow.com/users/5429", "pm_score": 3, "selected": false, "text": "<p>The pdb contains information the debugger needs in order to correctly read the stack. Your stack traces will contain line numbers and symbol names of the stack frames inside of the modules for which you have the pdb.</p>\n\n<p>I'll give two usages examples. The first is the obvious answer. The second explains source-indexed pdb's.</p>\n\n<p>1st usage example...</p>\n\n<p>Depending on calling convention and which optimizations the compiler used, it might not be possible for the debugger to manually unwind the stack through a module for which you do not have a pdb. This can happen with certain third party libraries and even for some parts of the OS.</p>\n\n<p>Consider a scenario in which you encounter an access violation inside of the windows OS. The stack trace does not unwind into your own application because that OS component uses a special calling convention that confuses the debugger. If you configure your symbol path to download the public OS pdb's, then there is a good chance that the stack trace will unwind into your application. That enables you to see exactly what arguments your own code passed into the OS system call. (and similar example for AV inside of a 3rd party library or even inside of your own code)</p>\n\n<p>2nd usage example...</p>\n\n<p>Pdb's have another very useful property - they can integrate with some source control systems using a feature that microsoft calls \"source indexing\". A source-indexed pdb contains source control commands that specify how to fetch from source control the exact file versions that were used to build the component. Microsoft's debuggers understand how to execute the commands to automatically fetch the files during a debug session. This is a powerful feature that saves the debug egineer from having to manually sync a source tree to the correct label for a given build. It's especially useful for remote debugging sessions and for analyzing crash dumps post-mortem.</p>\n\n<p>The \"debugging tools for windows\" installation (windbg) contains a document named srcsrv.doc which provides an example demonstrating how to use srctool.exe to determine which source files are source-indexed in a given pdb.</p>\n\n<p>To answer your question \"how do I know\", the \"modules\" feature in the debugger can tell you which modules have a corresponding pdb. In windbg use the \"lml\" command. In visual studio select modules from somewhere in the debug menus. (sorry, I don't have a current version of visual studio handy)</p>\n" }, { "answer_id": 53095, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 4, "selected": true, "text": "<p>To confirm if you're using the provided PDB, CorporateComponent.pdb, during debugging within the Visual Studio IDE review the output window and locate the line indicating that the CorporateComponent.dll is loaded and followed by the string <code>Symbols loaded</code>.</p>\n\n<p>To illustrate from a project of mine:</p>\n\n<pre><code>The thread 0x6a0 has exited with code 0 (0x0).\nThe thread 0x1f78 has exited with code 0 (0x0).\n'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\\Development\\Src\\trunk\\ntity\\AvayaConfigurationService\\AvayaConfigurationService\\bin\\Debug \\AvayaConfigurationService.exe', Symbols loaded.\n'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\\Development\\Src\\trunk\\ntity\\AvayaConfigurationService\\AvayaConfigurationService\\bin\\Debug\\IPOConfigService.dll', No symbols loaded.\n</code></pre>\n\n<blockquote>\n <p><code>Loaded 'C:\\Development\\src...\\bin\\Debug\\AvayaConfigurationService.exe', Symbols loaded.</code></p>\n</blockquote>\n\n<p>This indicates that the PDB was found and loaded by the IDE debugger.</p>\n\n<p>As indicated by others When examining stack frames within your application you should be able to see the symbols from the CorporateComponent.pdb. If you don't then perhaps the third-party did not include symbol information in the release PDB build.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects. ``` CorpObject o = new CorpObject(); Int32 result = o.DoSomethingLousy(); ``` While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it?
To confirm if you're using the provided PDB, CorporateComponent.pdb, during debugging within the Visual Studio IDE review the output window and locate the line indicating that the CorporateComponent.dll is loaded and followed by the string `Symbols loaded`. To illustrate from a project of mine: ``` The thread 0x6a0 has exited with code 0 (0x0). The thread 0x1f78 has exited with code 0 (0x0). 'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug \AvayaConfigurationService.exe', Symbols loaded. 'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug\IPOConfigService.dll', No symbols loaded. ``` > > `Loaded 'C:\Development\src...\bin\Debug\AvayaConfigurationService.exe', Symbols loaded.` > > > This indicates that the PDB was found and loaded by the IDE debugger. As indicated by others When examining stack frames within your application you should be able to see the symbols from the CorporateComponent.pdb. If you don't then perhaps the third-party did not include symbol information in the release PDB build.
52,634
<p>So I'm been pounding on this problem all day. I've got a LinqDataSource that points to my model and a GridView that consumes it. When I attempt to do an update on the GridView, it does not update the underlying data source. I thought it might have to do with the LinqDataSource, so I added a SqlDataSource and the same thing happens. The aspx is as follows (the code-behind page is empty):</p> <pre><code> &lt;asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=devsql32;Initial Catalog=Steam;Persist Security Info=True;" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [LangID], [Code], [Name] FROM [Languages]" UpdateCommand="UPDATE [Languages] SET [Code]=@Code WHERE [LangID]=@LangId"&gt; &lt;/asp:SqlDataSource&gt; &lt;asp:GridView ID="_languageGridView" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="LangId" DataSourceID="SqlDataSource1"&gt; &lt;Columns&gt; &lt;asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /&gt; &lt;asp:BoundField DataField="LangId" HeaderText="Id" ReadOnly="True" /&gt; &lt;asp:BoundField DataField="Code" HeaderText="Code" /&gt; &lt;asp:BoundField DataField="Name" HeaderText="Name" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:LinqDataSource ID="_languageDataSource" ContextTypeName="GeneseeSurvey.SteamDatabaseDataContext" runat="server" TableName="Languages" EnableInsert="True" EnableUpdate="true" EnableDelete="true"&gt; &lt;/asp:LinqDataSource&gt; </code></pre> <p>What in the world am I missing here? This problem is driving me insane.</p>
[ { "answer_id": 52644, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>This is a total shot in the dark since I haven't used ASP at all.</p>\n\n<p>I've been just learning XAML and WPF, which appears to be very similar to what you've posted above and I know that for some UI controls you need to specify the binding mode to two-way in order to get updates in both directions.</p>\n" }, { "answer_id": 52651, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "<p>You are missing the &lt;UpdateParameters&gt; sections of your DataSources.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.updateparameters.aspx\" rel=\"nofollow noreferrer\">LinqDataSource.UpdateParameters</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.updateparameters.aspx\" rel=\"nofollow noreferrer\">SqlDataSource.UpdateParameters</a></p>\n" }, { "answer_id": 52858, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 2, "selected": true, "text": "<p>It turns out that we had a DataBind() call in the Page_Load of the master page of the aspx file that was probably causing the state of the GridView to get tossed out on every page load.</p>\n\n<p>As a note - update parameters for a LINQ query are not required unless you want to set them some non-null default.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194/" ]
So I'm been pounding on this problem all day. I've got a LinqDataSource that points to my model and a GridView that consumes it. When I attempt to do an update on the GridView, it does not update the underlying data source. I thought it might have to do with the LinqDataSource, so I added a SqlDataSource and the same thing happens. The aspx is as follows (the code-behind page is empty): ``` <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=devsql32;Initial Catalog=Steam;Persist Security Info=True;" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [LangID], [Code], [Name] FROM [Languages]" UpdateCommand="UPDATE [Languages] SET [Code]=@Code WHERE [LangID]=@LangId"> </asp:SqlDataSource> <asp:GridView ID="_languageGridView" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="LangId" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="LangId" HeaderText="Id" ReadOnly="True" /> <asp:BoundField DataField="Code" HeaderText="Code" /> <asp:BoundField DataField="Name" HeaderText="Name" /> </Columns> </asp:GridView> <asp:LinqDataSource ID="_languageDataSource" ContextTypeName="GeneseeSurvey.SteamDatabaseDataContext" runat="server" TableName="Languages" EnableInsert="True" EnableUpdate="true" EnableDelete="true"> </asp:LinqDataSource> ``` What in the world am I missing here? This problem is driving me insane.
It turns out that we had a DataBind() call in the Page\_Load of the master page of the aspx file that was probably causing the state of the GridView to get tossed out on every page load. As a note - update parameters for a LINQ query are not required unless you want to set them some non-null default.
52,674
<p>Let's say you have a variable in a makefile fragment like the following:</p> <pre><code>MY_LIST=a b c d </code></pre> <p>How do I then reverse the order of that list? I need:</p> <pre><code>$(warning MY_LIST=${MY_LIST}) </code></pre> <p>to show</p> <pre><code>MY_LIST=d c b a </code></pre> <p>Edit: the real problem is that </p> <pre><code>ld -r some_object.o ${MY_LIST} </code></pre> <p>produces an <code>a.out</code> with undefined symbols because the items in <code>MY_LIST</code> are actually archives, but in the wrong order. If the order of <code>MY_LIST</code> is reversed, it will link correctly (I think). If you know a smarter way to get the link order right, clue me in.</p>
[ { "answer_id": 52722, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": false, "text": "<p>Doh! I could have just used a shell script-let:</p>\n\n<p><code>(for d in ${MY_LIST}; do echo $$d; done) | tac</code></p>\n" }, { "answer_id": 52903, "author": "ajax", "author_id": 5250, "author_profile": "https://Stackoverflow.com/users/5250", "pm_score": 3, "selected": false, "text": "<p>You can also define search groups with ld:</p>\n\n<pre><code>ld -r foo.o -( a.a b.a c.a -)\n</code></pre>\n\n<p>Will iterate through a.a, b.a, and c.a until no new unresolved symbols can be satisfied by any object in the group.</p>\n\n<p>If you're using gnu ld, you can also do:</p>\n\n<pre><code>ld -r -o foo.o --whole-archive bar.a\n</code></pre>\n\n<p>Which is slightly stronger, in that it will include every object from bar.a regardless of whether it satisfies an unresolved symbol from foo.o.</p>\n" }, { "answer_id": 786530, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>A solution in pure GNU make:</p>\n\n<blockquote>\n <p>default: all</p>\n \n <p>foo = please reverse me</p>\n \n <p>reverse = $(if $(1),$(call\n reverse,$(wordlist 2,$(words\n $(1)),$(1)))) $(firstword $(1))</p>\n \n <p>all : @echo $(call reverse,$(foo))</p>\n</blockquote>\n\n<p>Gives:</p>\n\n<blockquote>\n <p>$ make</p>\n \n <p>me reverse please</p>\n</blockquote>\n" }, { "answer_id": 14260762, "author": "studog", "author_id": 1352761, "author_profile": "https://Stackoverflow.com/users/1352761", "pm_score": 3, "selected": false, "text": "<p>An improvement to the GNU make solution:</p>\n\n<blockquote>\n <p>reverse = $(if $(wordlist 2,2,$(1)),$(call reverse,$(wordlist 2,$(words $(1)),$(1))) $(firstword $(1)),$(1))</p>\n</blockquote>\n\n<ul>\n<li>better stopping condition, original uses the empty string wasting a function call</li>\n<li>doesn't add a leading space to the reversed list, unlike the original</li>\n</ul>\n" }, { "answer_id": 16795504, "author": "Tripp Lilley", "author_id": 309233, "author_profile": "https://Stackoverflow.com/users/309233", "pm_score": 2, "selected": false, "text": "<p>Playing off of both <a href=\"https://stackoverflow.com/a/52722/309233\">Ben Collins'</a> and <a href=\"https://stackoverflow.com/a/52697/309233\">elmarco's</a> answers, here's a punt to bash which handles whitespace \"properly\"<sup>1</sup></p>\n\n<pre><code>reverse = $(shell printf \"%s\\n\" $(strip $1) | tac)\n</code></pre>\n\n<p>which does the right thing, thanks to <code>$(shell)</code> automatically cleaning whitespace and <code>printf</code> automatically formatting each word in its arg list:</p>\n\n<pre><code>$(info [ $(call reverse, one two three four ) ] )\n</code></pre>\n\n<p>yields:</p>\n\n<pre><code>[ four three two one ]\n</code></pre>\n\n<p><sup>1</sup>...according to my limited test case (i.e., the <code>$(info ...)</code> line, above).</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
Let's say you have a variable in a makefile fragment like the following: ``` MY_LIST=a b c d ``` How do I then reverse the order of that list? I need: ``` $(warning MY_LIST=${MY_LIST}) ``` to show ``` MY_LIST=d c b a ``` Edit: the real problem is that ``` ld -r some_object.o ${MY_LIST} ``` produces an `a.out` with undefined symbols because the items in `MY_LIST` are actually archives, but in the wrong order. If the order of `MY_LIST` is reversed, it will link correctly (I think). If you know a smarter way to get the link order right, clue me in.
A solution in pure GNU make: > > default: all > > > foo = please reverse me > > > reverse = $(if $(1),$(call > reverse,$(wordlist 2,$(words > $(1)),$(1)))) $(firstword $(1)) > > > all : @echo $(call reverse,$(foo)) > > > Gives: > > $ make > > > me reverse please > > >
52,702
<p>I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. </p> <p>This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. </p> <p>Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)</p> <p>Here is a code snippet:</p> <pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open); long byteNum = fs.Length; byte[] pdfBytes = new byte[byteNum]; fs.Read(pdfBytes, 0, (int)byteNum); Response.AppendHeader("Content-disposition", "filename=Testme.doc"); Response.CacheControl = "no-cache"; Response.ContentType = "application/msword; charset=utf-8"; Response.Expires = -1; Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length); Response.Flush(); Response.Close(); fs.Close(); </code></pre> <p>Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 &amp; IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. </p> <p>IE does provide an advanced setting "Do not save encrypted pages to disk". </p> <p>I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.</p> <p>Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).</p> <p>Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?</p>
[ { "answer_id": 53078, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.</p>\n\n<pre><code>\nResponse.AddHeader(\"Content-Disposition\", \"attachment;filename=myfile.doc\");\n</code></pre>\n\n<p>failing that i've included my code below as I know that works over https://</p>\n\n<pre>\n<code>\nprivate void ReadFile(string URL)\n{\n try\n {\n string uristring = URL;\n WebRequest myReq = WebRequest.Create(uristring);\n NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings[\"Username\"].ToString(), \n ConfigurationManager.AppSettings[\"Password\"].ToString(), \n ConfigurationManager.AppSettings[\"Domain\"].ToString());\n myReq.Credentials = netCredential;\n StringBuilder strSource = new StringBuilder(\"\");\n\n //get the stream of data \n string contentType = \"\";\n MemoryStream ms;\n // Send a request to download the pdf document and then get the response\n using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())\n {\n contentType = response.ContentType;\n // Get the stream from the server\n using (Stream stream = response.GetResponseStream())\n {\n // Use the ReadFully method from the link above:\n byte[] data = ReadFully(stream, response.ContentLength);\n // Return the memory stream.\n ms = new MemoryStream(data);\n }\n }\n\n Response.Clear();\n Response.ContentType = contentType;\n Response.AddHeader(\"Content-Disposition\", \"attachment;\");\n\n // Write the memory stream containing the pdf file directly to the Response object that gets sent to the client\n ms.WriteTo(Response.OutputStream);\n }\n catch (Exception ex)\n {\n throw new Exception(\"Error in ReadFile\", ex);\n }\n}\n</code>\n</pre>\n" }, { "answer_id": 77958, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 2, "selected": false, "text": "<p>Ok, I resolved the problem, several factors at play here.</p>\n\n<p>Firstly this support Microsoft article was beneficial:\n<a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;316431\" rel=\"nofollow noreferrer\">Internet Explorer is unable to open Office documents from an SSL Web site</a>.</p>\n\n<blockquote>\n <p><em>In order for Internet Explorer to open documents in Office (or any out-of-process, ActiveX document server), Internet Explorer must save the file to the local cache directory and ask the associated application to load the file by using IPersistFile::Load. If the file is not stored to disk, this operation fails.</em></p>\n \n <p><em>When Internet Explorer communicates with a secure Web site through SSL, Internet Explorer enforces any no-cache request. If the header or headers are present, Internet Explorer does not cache the file. Consequently, Office cannot open the file.</em> </p>\n</blockquote>\n\n<p>Secondly, something earlier in the page processing was causing the \"no-cache\" header to get written. So Response.ClearHeaders needed to be added, this cleared out the no-cache header, and the output of the page needs to allow caching.</p>\n\n<p>Thirdly for good measure, also added on Response.End, so that no other processing futher on in the request lifetime attempts to clear the headers I've set and re-add the no-cache header. </p>\n\n<p>Fourthly, discovered that content expiration had been enabled in IIS. I've left it enabled at the web site level, but since this one aspx page will serve as a gateway for downloading the files, I disabled it at the download page level.</p>\n\n<p>So here is the code snippet that works (there are a couple other minor changes which I believe are inconsequential):</p>\n\n<pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(\".\") + \"\\\\\" + \"TestMe.doc\", System.IO.FileMode.Open);\nlong byteNum = fs.Length;\nbyte[] fileBytes = new byte[byteNum];\nfs.Read(fileBytes, 0, (int)byteNum);\n\nResponse.ClearContent();\nResponse.ClearHeaders();\nResponse.AppendHeader(\"Content-disposition\", \"attachment; filename=Testme.doc\");\nResponse.Cache.SetCacheability(HttpCacheability.Public);\nResponse.ContentType = \"application/octet-stream\";\nResponse.OutputStream.Write(fileBytes, 0, fileBytes.Length);\nResponse.Flush();\nResponse.Close();\nfs.Close();\nResponse.End();\n</code></pre>\n\n<p>Keep in mind too, this is just for illustration. The real production code will include exception handling and likely read the file a chunk at a time (perhaps 10K).</p>\n\n<p>Mauro, thanks for catching a detail that was missing from the code as well.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4764/" ]
I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.) Here is a code snippet: ``` System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open); long byteNum = fs.Length; byte[] pdfBytes = new byte[byteNum]; fs.Read(pdfBytes, 0, (int)byteNum); Response.AppendHeader("Content-disposition", "filename=Testme.doc"); Response.CacheControl = "no-cache"; Response.ContentType = "application/msword; charset=utf-8"; Response.Expires = -1; Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length); Response.Flush(); Response.Close(); fs.Close(); ``` Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 & IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. IE does provide an advanced setting "Do not save encrypted pages to disk". I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled. Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size). Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?
It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved. ``` Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc"); ``` failing that i've included my code below as I know that works over https:// ``` private void ReadFile(string URL) { try { string uristring = URL; WebRequest myReq = WebRequest.Create(uristring); NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString()); myReq.Credentials = netCredential; StringBuilder strSource = new StringBuilder(""); //get the stream of data string contentType = ""; MemoryStream ms; // Send a request to download the pdf document and then get the response using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse()) { contentType = response.ContentType; // Get the stream from the server using (Stream stream = response.GetResponseStream()) { // Use the ReadFully method from the link above: byte[] data = ReadFully(stream, response.ContentLength); // Return the memory stream. ms = new MemoryStream(data); } } Response.Clear(); Response.ContentType = contentType; Response.AddHeader("Content-Disposition", "attachment;"); // Write the memory stream containing the pdf file directly to the Response object that gets sent to the client ms.WriteTo(Response.OutputStream); } catch (Exception ex) { throw new Exception("Error in ReadFile", ex); } } ```
52,703
<p>Has anyone encountered this oddity?</p> <p>I'm checking for the existence of a number of directories in one of my unit tests. <code>is_dir</code> is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging):</p> <pre><code>foreach($userfolders as $uf) { $uf = sprintf($uf, $user_id); $uf = ltrim($uf,'/'); $path = trim($base . '/' . $uf); $res = is_dir($path); //returns false except last time returns 1 $this-&gt;assertFalse($res, $path); } </code></pre> <p>The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3</p> <p>Things I have checked:</p> <pre><code> - Paths are full paths - The same thing happens on two separate machines (both running Ubuntu) - I have stepped through line by line in a debugger - Paths genuinely don't exist at the point where is_dir is called - While the code is paused on this line, I can actually drop to a shell and run </code></pre> <p>the interactive PHP interpreter and get the correct result - The paths are all WELL under 256 chars - I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing.</p> <p>Comments on the PHP docs point to the odd issue with <code>is_dir</code> but not this particular one.</p> <p>I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and <em>hopefully</em> an answer from somebody else who has seen this!</p>
[ { "answer_id": 52712, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 1, "selected": false, "text": "<p>For what its worth, <code>is_readable</code> can be used as a work around.</p>\n" }, { "answer_id": 52716, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": true, "text": "<p>I don't think this would cause your problem, but $path does have the trailing slash, correct?</p>\n" }, { "answer_id": 52721, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 0, "selected": false, "text": "<pre><code>$path = trim($base . '/' . $uf);\n</code></pre>\n\n<p>That could be causing it. I'm assuming $base is some sort of root folder you are searching, so if $uf is something like '', '.', or '../' that could return true. We would have to see what values you are using in your foreach to know anything further.</p>\n\n<p>[EDIT]</p>\n\n<p>Doing some more looking the above code works fine on OpenBSD 4.3 with PHP 5.2. </p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745/" ]
Has anyone encountered this oddity? I'm checking for the existence of a number of directories in one of my unit tests. `is_dir` is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging): ``` foreach($userfolders as $uf) { $uf = sprintf($uf, $user_id); $uf = ltrim($uf,'/'); $path = trim($base . '/' . $uf); $res = is_dir($path); //returns false except last time returns 1 $this->assertFalse($res, $path); } ``` The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3 Things I have checked: ``` - Paths are full paths - The same thing happens on two separate machines (both running Ubuntu) - I have stepped through line by line in a debugger - Paths genuinely don't exist at the point where is_dir is called - While the code is paused on this line, I can actually drop to a shell and run ``` the interactive PHP interpreter and get the correct result - The paths are all WELL under 256 chars - I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing. Comments on the PHP docs point to the odd issue with `is_dir` but not this particular one. I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and *hopefully* an answer from somebody else who has seen this!
I don't think this would cause your problem, but $path does have the trailing slash, correct?
52,704
<p>How do I discard changes in my working copy that are not in the index?</p>
[ { "answer_id": 52713, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 13, "selected": false, "text": "<p>For all <em>unstaged</em> files in current working directory use:</p>\n<pre><code>git restore .\n</code></pre>\n<p>For a specific file use:</p>\n<pre><code>git restore path/to/file/to/revert\n</code></pre>\n<p>That together with <code>git switch</code> replaces the overloaded <code>git checkout</code> (<a href=\"https://stackoverflow.com/questions/58003030/what-is-the-git-restore-command-and-what-is-the-difference-between-git-restor\">see here</a>), and thus removes the argument disambiguation.</p>\n<p>If a file has both staged and unstaged changes, only the unstaged changes shown in <code>git diff</code> are reverted. Changes shown in <code>git diff --staged</code> stay intact.</p>\n<p><strong>Before Git 2.23</strong></p>\n<p>For all unstaged files in current working directory:</p>\n<pre><code>git checkout -- .\n</code></pre>\n<p>For a specific file:</p>\n<pre><code>git checkout -- path/to/file/to/revert\n</code></pre>\n<p><code>--</code> here to remove ambiguity (this is known as <a href=\"https://git-scm.com/docs/git-checkout#_argument_disambiguation\" rel=\"noreferrer\">argument disambiguation</a>).</p>\n" }, { "answer_id": 52719, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 13, "selected": true, "text": "<p>Another quicker way is:</p>\n\n<pre><code>git stash save --keep-index --include-untracked\n</code></pre>\n\n<p>You don't need to include <code>--include-untracked</code> if you don't want to be thorough about it.</p>\n\n<p>After that, you can drop that stash with a <code>git stash drop</code> command if you like.</p>\n" }, { "answer_id": 1021384, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 9, "selected": false, "text": "<p>This checks out the current index for the current directory, throwing away all changes in files from the current directory downwards.</p>\n\n<pre><code>git checkout .\n</code></pre>\n\n<p>or this which checks out all files from the index, overwriting working tree files.</p>\n\n<pre><code>git checkout-index -a -f\n</code></pre>\n" }, { "answer_id": 6854469, "author": "Joshua Kunzmann", "author_id": 121037, "author_profile": "https://Stackoverflow.com/users/121037", "pm_score": 6, "selected": false, "text": "<p>If you aren't interested in keeping the unstaged changes (especially if the staged changes are new files), I found this handy:</p>\n\n<pre><code>git diff | git apply --reverse\n</code></pre>\n" }, { "answer_id": 7773568, "author": "artur", "author_id": 201852, "author_profile": "https://Stackoverflow.com/users/201852", "pm_score": 5, "selected": false, "text": "<p>Tried all the solutions above but still couldn't get rid of new, unstaged files.</p>\n\n<p>Use <code>git clean -f</code> to remove those new files - <em>with caution though!</em> Note the force option.</p>\n" }, { "answer_id": 8415829, "author": "E Ciotti", "author_id": 415032, "author_profile": "https://Stackoverflow.com/users/415032", "pm_score": 8, "selected": false, "text": "<pre><code>git clean -df\n</code></pre>\n\n<p>Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.</p>\n\n<p><code>-d</code>: Remove untracked directories in addition to untracked files</p>\n\n<p><code>-f</code>: Force (might be not necessary depending on <code>clean.requireForce</code> setting)</p>\n\n<p>Run <code>git help clean</code> to see the manual</p>\n" }, { "answer_id": 11047504, "author": "tjb", "author_id": 530634, "author_profile": "https://Stackoverflow.com/users/530634", "pm_score": 3, "selected": false, "text": "<p>Another way to get rid of new files that is more specific than git clean -df (it will allow you to get rid of some files not necessarily all), is to add the new files to the index first, then stash, then drop the stash.</p>\n\n<p>This technique is useful when, for some reason, you can't easily delete all of the untracked files by some ordinary mechanism (like rm).</p>\n" }, { "answer_id": 11942626, "author": "blak3r", "author_id": 67268, "author_profile": "https://Stackoverflow.com/users/67268", "pm_score": 6, "selected": false, "text": "<p>I really found this article helpful for explaining when to use what command: <a href=\"http://www.szakmeister.net/blog/2011/oct/12/reverting-changes-git/\" rel=\"noreferrer\">http://www.szakmeister.net/blog/2011/oct/12/reverting-changes-git/</a></p>\n\n<p>There are a couple different cases:</p>\n\n<ol>\n<li><p>If you haven't staged the file, then you use <code>git checkout</code>. Checkout \"updates files in the working tree to match the version in the index\". If the files have not been staged (aka added to the index)... this command will essentially revert the files to what your last commit was. </p>\n\n<p><code>git checkout -- foo.txt</code></p></li>\n<li><p>If you have staged the file, then use git reset. Reset changes the index to match a commit.</p>\n\n<p><code>git reset -- foo.txt</code> </p></li>\n</ol>\n\n<p>I suspect that using <code>git stash</code> is a popular choice since it's a little less dangerous. You can always go back to it if you accidently blow too much away when using git reset. Reset is recursive by default.</p>\n\n<p>Take a look at the article above for further advice.</p>\n" }, { "answer_id": 12184274, "author": "Mariusz Nowak", "author_id": 96806, "author_profile": "https://Stackoverflow.com/users/96806", "pm_score": 11, "selected": false, "text": "<p>It seems like the complete solution is:</p>\n<pre><code>git clean -df\ngit checkout -- .\n</code></pre>\n<p><strong>WARNING</strong>: while it won't delete ignored files mentioned directly in .gitignore, <code>git clean -df</code> <strong>may delete ignored files residing in folders</strong>.</p>\n<p><a href=\"https://git-scm.com/docs/git-clean\" rel=\"noreferrer\"><code>git clean</code></a> removes all untracked files and <code>git checkout</code> clears all unstaged changes.</p>\n" }, { "answer_id": 17530055, "author": "twicejr", "author_id": 449217, "author_profile": "https://Stackoverflow.com/users/449217", "pm_score": 3, "selected": false, "text": "<p>When you want to transfer a stash to someone else:</p>\n\n<pre><code># add files\ngit add . \n# diff all the changes to a file\ngit diff --staged &gt; ~/mijn-fix.diff\n# remove local changes \ngit reset &amp;&amp; git checkout .\n# (later you can re-apply the diff:)\ngit apply ~/mijn-fix.diff\n</code></pre>\n\n<p>[edit] as commented, it ís possible to name stashes. Well, use this if you want to share your stash ;)</p>\n" }, { "answer_id": 18632808, "author": "GlassGhost", "author_id": 144020, "author_profile": "https://Stackoverflow.com/users/144020", "pm_score": 4, "selected": false, "text": "<p>This works even in directories that are; outside of normal git permissions.</p>\n\n<pre><code>sudo chmod -R 664 ./* &amp;&amp; git checkout -- . &amp;&amp; git clean -dfx\n</code></pre>\n\n<p>Happened to me recently</p>\n" }, { "answer_id": 20930217, "author": "bbarker", "author_id": 3096687, "author_profile": "https://Stackoverflow.com/users/3096687", "pm_score": 3, "selected": false, "text": "<p>What follows is really only a solution if you are working with a fork of a repository where you regularly synchronize (e.g. pull request) with another repo. Short answer: delete fork and refork, but <strong>read the warnings on github</strong>.</p>\n\n<p>I had a similar problem, perhaps not identical, and I'm sad to say my solution is not ideal, but it is ultimately effective.</p>\n\n<p>I would often have git status messages like this (involving at least 2/4 files):</p>\n\n<pre><code>$ git status\n# Not currently on any branch.\n# Changes to be committed:\n# (use \"git reset HEAD &lt;file&gt;...\" to unstage)\n#\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/constraint_s2var.dats\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/parsing/parsing_s2var.dats\n#\n# Changes not staged for commit:\n# (use \"git add &lt;file&gt;...\" to update what will be committed)\n# (use \"git checkout -- &lt;file&gt;...\" to discard changes in working directory)\n#\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/constraint_s2Var.dats\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/parsing/parsing_s2Var.dats\n</code></pre>\n\n<p>A keen eye will note that these files have dopplegangers that are a single letter in case off. Somehow, and I have no idea what led me down this path to start with (as I was not working with these files myself from the upstream repo), I had switched these files. Try the many solutions listed on this page (and other pages) did not seem to help. </p>\n\n<p><strong>I was able to fix the problem by deleting my forked repository and all local repositories, and reforking. This alone was not enough; upstream had to rename the files in question to new filenames.</strong> As long as you don't have any uncommited work, no wikis, and no issues that diverge from the upstream repository, you should be just fine. Upstream may not be very happy with you, to say the least. As for my problem, it is undoubtedly a user error as I'm not that proficient with git, but the fact that it is far from easy to fix points to an issue with git as well. </p>\n" }, { "answer_id": 23707009, "author": "Bijan", "author_id": 323720, "author_profile": "https://Stackoverflow.com/users/323720", "pm_score": 5, "selected": false, "text": "<p><code>git checkout -f</code></p>\n\n<hr>\n\n<p><code>man git-checkout</code>:</p>\n\n<p><code>-f, --force</code></p>\n\n<p>When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.</p>\n\n<p>When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.</p>\n" }, { "answer_id": 23951175, "author": "vivekporwal04", "author_id": 1856106, "author_profile": "https://Stackoverflow.com/users/1856106", "pm_score": 4, "selected": false, "text": "<pre><code>cd path_to_project_folder # take you to your project folder/working directory \ngit checkout . # removes all unstaged changes in working directory\n</code></pre>\n" }, { "answer_id": 26299506, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 7, "selected": false, "text": "<p>My favorite is</p>\n\n<pre><code>git checkout -p\n</code></pre>\n\n<p>That lets you selectively revert chunks.</p>\n\n<p>See also:</p>\n\n<pre><code>git add -p\n</code></pre>\n" }, { "answer_id": 29170402, "author": "Ivan", "author_id": 3070485, "author_profile": "https://Stackoverflow.com/users/3070485", "pm_score": 3, "selected": false, "text": "<p>If all the staged files were actually committed, then the branch can simply be reset e.g. from your GUI with about three mouse clicks: <strong>Branch</strong>, <strong>Reset</strong>, <strong>Yes</strong>!</p>\n\n<p>So what I often do in practice to revert unwanted local changes is to commit all the good stuff, and then reset the branch.</p>\n\n<p>If the good stuff is committed in a single commit, then you can use \"amend last commit\" to bring it back to being staged or unstaged if you'd ultimately like to commit it a little differently.</p>\n\n<p>This might not be the technical solution you are looking for to your problem, but I find it a very practical solution. It allows you to discard unstaged changes selectively, resetting the changes you don't like and keeping the ones you do.</p>\n\n<p>So in summary, I simply do <strong>commit</strong>, <strong>branch reset</strong>, and <strong>amend last commit</strong>.</p>\n" }, { "answer_id": 29847393, "author": "piyushmandovra", "author_id": 3568378, "author_profile": "https://Stackoverflow.com/users/3568378", "pm_score": 5, "selected": false, "text": "<p>simply say</p>\n\n<pre><code>git stash\n</code></pre>\n\n<p>It will remove all your local changes. You also can use later by saying</p>\n\n<pre><code>git stash apply \n</code></pre>\n\n<p>or \n git stash pop</p>\n" }, { "answer_id": 31886761, "author": "Nick", "author_id": 1563884, "author_profile": "https://Stackoverflow.com/users/1563884", "pm_score": 5, "selected": false, "text": "<p>Instead of discarding changes, I reset my remote to the origin. Note - this method is to completely restore your folder to that of the repo. </p>\n\n<p>So I do this to make sure they don't sit there when I git reset (later - excludes gitignores on the Origin/branchname)</p>\n\n<p>NOTE: If you want to keep files not yet tracked, but not in GITIGNORE you may wish to skip this step, as it will Wipe these untracked files not found on your remote repository (thanks @XtrmJosh).</p>\n\n<pre><code>git add --all\n</code></pre>\n\n<p>Then I </p>\n\n<pre><code>git fetch --all\n</code></pre>\n\n<p>Then I reset to origin</p>\n\n<pre><code>git reset --hard origin/branchname\n</code></pre>\n\n<p>That will put it back to square one. Just like RE-Cloning the branch, WHILE keeping all my gitignored files locally and in place.</p>\n\n<p>Updated per user comment below:\nVariation to reset the to whatever current branch the user is on. </p>\n\n<pre><code>git reset --hard @{u}\n</code></pre>\n" }, { "answer_id": 32523024, "author": "Asped", "author_id": 1132243, "author_profile": "https://Stackoverflow.com/users/1132243", "pm_score": 5, "selected": false, "text": "<p>You can use git stash - if something goes wrong, you can still revert from the stash.\nSimilar to some other answer here, but this one also removes all unstaged files and also all unstaged deletes:</p>\n\n<pre><code>git add .\ngit stash\n</code></pre>\n\n<p>if you check that everything is OK, throw the stash away:</p>\n\n<pre><code>git stash drop\n</code></pre>\n\n<p>The answer from Bilal Maqsood with <code>git clean</code> also worked for me, but with the stash I have more control - if I do sth accidentally, I can still get my changes back</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I think there is 1 more change (don't know why this worked for me before):</p>\n\n<p><code>git add . -A</code> instead of <code>git add .</code></p>\n\n<p>without the <code>-A</code> the removed files will not be staged</p>\n" }, { "answer_id": 32897226, "author": "onalbi", "author_id": 3090602, "author_profile": "https://Stackoverflow.com/users/3090602", "pm_score": 3, "selected": false, "text": "<p>If you are in case of submodule and no other solutions work try:</p>\n\n<ul>\n<li><p>To check what is the problem (maybe a \"dirty\" case) use:</p>\n\n<p><code>git diff</code></p></li>\n<li><p>To remove stash</p>\n\n<p><code>git submodule update</code></p></li>\n</ul>\n" }, { "answer_id": 33863756, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 3, "selected": false, "text": "<p>None of the solutions work if you just changed the <em>permissions</em> of a file (this is on DOS/Windoze)</p>\n\n<pre>\nMon 23/11/2015-15:16:34.80 C:\\...\\work\\checkout\\slf4j+> git status\nOn branch SLF4J_1.5.3\nChanges not staged for commit:\n (use \"git add ...\" to update what will be committed)\n (use \"git checkout -- ...\" to discard changes in working directory)\n\n modified: .gitignore\n modified: LICENSE.txt\n modified: TODO.txt\n modified: codeStyle.xml\n modified: pom.xml\n modified: version.pl\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n\nMon 23/11/2015-15:16:37.87 C:\\...\\work\\checkout\\slf4j+> git diff\ndiff --git a/.gitignore b/.gitignore\nold mode 100644\nnew mode 100755\ndiff --git a/LICENSE.txt b/LICENSE.txt\nold mode 100644\nnew mode 100755\ndiff --git a/TODO.txt b/TODO.txt\nold mode 100644\nnew mode 100755\ndiff --git a/codeStyle.xml b/codeStyle.xml\nold mode 100644\nnew mode 100755\ndiff --git a/pom.xml b/pom.xml\nold mode 100644\nnew mode 100755\ndiff --git a/version.pl b/version.pl\nold mode 100644\nnew mode 100755\n\nMon 23/11/2015-15:16:45.22 C:\\...\\work\\checkout\\slf4j+> git reset --hard HEAD\nHEAD is now at 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore\n\nMon 23/11/2015-15:16:47.42 C:\\...\\work\\checkout\\slf4j+> git clean -f\n\nMon 23/11/2015-15:16:53.49 C:\\...\\work\\checkout\\slf4j+> git stash save -u\nSaved working directory and index state WIP on SLF4J_1.5.3: 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore\nHEAD is now at 8fa8488 12133-CHIXMISSINGMESSAGES MALCOLMBOEKHOFF 20141223124940 Added .gitignore\n\nMon 23/11/2015-15:17:00.40 C:\\...\\work\\checkout\\slf4j+> git stash drop\nDropped refs/stash@{0} (cb4966e9b1e9c9d8daa79ab94edc0c1442a294dd)\n\nMon 23/11/2015-15:17:06.75 C:\\...\\work\\checkout\\slf4j+> git stash drop\nDropped refs/stash@{0} (e6c49c470f433ce344e305c5b778e810625d0529)\n\nMon 23/11/2015-15:17:08.90 C:\\...\\work\\checkout\\slf4j+> git stash drop\nNo stash found.\n\nMon 23/11/2015-15:17:15.21 C:\\...\\work\\checkout\\slf4j+> git checkout -- .\n\nMon 23/11/2015-15:22:00.68 C:\\...\\work\\checkout\\slf4j+> git checkout -f -- .\n\nMon 23/11/2015-15:22:04.53 C:\\...\\work\\checkout\\slf4j+> git status\nOn branch SLF4J_1.5.3\nChanges not staged for commit:\n (use \"git add ...\" to update what will be committed)\n (use \"git checkout -- ...\" to discard changes in working directory)\n\n modified: .gitignore\n modified: LICENSE.txt\n modified: TODO.txt\n modified: codeStyle.xml\n modified: pom.xml\n modified: version.pl\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n\nMon 23/11/2015-15:22:13.06 C:\\...\\work\\checkout\\slf4j+> git diff\ndiff --git a/.gitignore b/.gitignore\nold mode 100644\nnew mode 100755\ndiff --git a/LICENSE.txt b/LICENSE.txt\nold mode 100644\nnew mode 100755\ndiff --git a/TODO.txt b/TODO.txt\nold mode 100644\nnew mode 100755\ndiff --git a/codeStyle.xml b/codeStyle.xml\nold mode 100644\nnew mode 100755\ndiff --git a/pom.xml b/pom.xml\nold mode 100644\nnew mode 100755\ndiff --git a/version.pl b/version.pl\nold mode 100644\nnew mode 100755\n</pre>\n\n<p>The only way to fix this is to manually reset the permissions on the changed files:</p>\n\n<pre>\nMon 23/11/2015-15:25:43.79 C:\\...\\work\\checkout\\slf4j+> git status -s | egrep \"^ M\" | cut -c4- | for /f \"usebackq tokens=* delims=\" %A in (`more`) do chmod 644 %~A\n\nMon 23/11/2015-15:25:55.37 C:\\...\\work\\checkout\\slf4j+> git status\nOn branch SLF4J_1.5.3\nnothing to commit, working directory clean\n\nMon 23/11/2015-15:25:59.28 C:\\...\\work\\checkout\\slf4j+>\n\nMon 23/11/2015-15:26:31.12 C:\\...\\work\\checkout\\slf4j+> git diff\n\n</pre>\n" }, { "answer_id": 35214606, "author": "msangel", "author_id": 449553, "author_profile": "https://Stackoverflow.com/users/449553", "pm_score": 4, "selected": false, "text": "<p>No matter what state your repo is in you can always reset to any previous commit:</p>\n\n<pre><code>git reset --hard &lt;commit hash&gt;\n</code></pre>\n\n<hr>\n\n<p>This will discard all changes which were made after that commit.</p>\n" }, { "answer_id": 36924148, "author": "Martin G", "author_id": 3545094, "author_profile": "https://Stackoverflow.com/users/3545094", "pm_score": 7, "selected": false, "text": "<p>Since no answer suggests the exact option combination that I use, here it is:</p>\n<pre><code>git clean -dxn . # dry-run to inspect the list of files-to-be-removed\ngit clean -dxf . # REMOVE ignored/untracked files (in the current directory)\ngit checkout -- . # ERASE changes in tracked files (in the current directory)\n</code></pre>\n<p>This is the online help text for the used <code>git clean</code> options:</p>\n<p><code>-d</code></p>\n<p>Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use <code>-f</code> option twice if you really want to remove such a directory.</p>\n<p><code>-x</code></p>\n<p>Don’t use the standard ignore rules read from <code>.gitignore</code> (per directory) and <code>$GIT_DIR/info/exclude</code>, but do still use the ignore rules given with <code>-e</code> options. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with <code>git reset</code>) to create a pristine working directory to test a clean build.</p>\n<p><code>-n</code></p>\n<p>Don’t actually remove anything, just show what would be done.</p>\n<p><code>-f</code></p>\n<p>If the Git configuration variable <code>clean.requireForce</code> is not set to <code>false</code>, Git clean will refuse to delete files or directories unless given <code>-f</code>, <code>-n</code>, or <code>-i</code>. Git will refuse to delete directories within the <code>.git</code> subdirectory or file, unless a second <code>-f</code> is given.</p>\n" }, { "answer_id": 37274801, "author": "Erdem ÖZDEMİR", "author_id": 1836344, "author_profile": "https://Stackoverflow.com/users/1836344", "pm_score": 6, "selected": false, "text": "<p>As you type git status, \n<strong>(use \"git checkout -- ...\" to discard changes in working directory)</strong>\nis shown.</p>\n\n<p>e.g. <code>git checkout -- .</code></p>\n" }, { "answer_id": 38367577, "author": "Lahiru Jayaratne", "author_id": 1616697, "author_profile": "https://Stackoverflow.com/users/1616697", "pm_score": 4, "selected": false, "text": "<p>In my opinion,</p>\n\n<pre><code>git clean -df\n</code></pre>\n\n<p>should do the trick. As per <a href=\"https://git-scm.com/docs/git-clean/2.2.0\">Git documentation on git clean</a></p>\n\n<blockquote>\n <p>git-clean - Remove untracked files from the working tree</p>\n</blockquote>\n\n<p><strong>Description</strong> </p>\n\n<blockquote>\n <p>Cleans the working tree by recursively removing files that\n are not under version control, starting from the current directory.</p>\n \n <p>Normally, only files unknown to Git are removed, but if the -x option\n is specified, ignored files are also removed. This can, for example,\n be useful to remove all build products.</p>\n \n <p>If any optional ... arguments are given, only those paths are\n affected.</p>\n</blockquote>\n\n<p><strong>Options</strong></p>\n\n<blockquote>\n <p>-d Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is\n not removed by default. Use -f option twice if you really want to\n remove such a directory.</p>\n \n <p>-f\n --force If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given -f, -n or -i.</p>\n</blockquote>\n" }, { "answer_id": 39383786, "author": "Ben Wilde", "author_id": 2284031, "author_profile": "https://Stackoverflow.com/users/2284031", "pm_score": 5, "selected": false, "text": "<p>Just use:</p>\n\n<pre><code>git stash -u\n</code></pre>\n\n<p>Done. Easy.</p>\n\n<p>If you <em>really</em> care about your stash stack then you can follow with <code>git stash drop</code>. But at that point you're better off using (from Mariusz Nowak):</p>\n\n<pre><code>git checkout -- .\ngit clean -df\n</code></pre>\n\n<p>Nonetheless, I like <code>git stash -u</code> the best because it \"discards\" all tracked and untracked changes in just <em>one command</em>. Yet <code>git checkout -- .</code> only discards tracked changes,\nand <code>git clean -df</code> only discards untracked changes... and typing both commands is <em>far</em> too much work :)</p>\n" }, { "answer_id": 41305623, "author": "Xaree Lee", "author_id": 1282160, "author_profile": "https://Stackoverflow.com/users/1282160", "pm_score": 1, "selected": false, "text": "<p>Just use:</p>\n\n<pre><code>git stash -k -u\n</code></pre>\n\n<p>This will stash <strong>unstaged changes</strong> and <strong>untracked files (new files)</strong> and keep staged files.</p>\n\n<p>It's better than <code>reset</code>/<code>checkout</code>/<code>clean</code>, because you might want them back later (by <code>git stash pop</code>). Keeping them in the stash is better than discarding them.</p>\n" }, { "answer_id": 42112496, "author": "SDV", "author_id": 1138573, "author_profile": "https://Stackoverflow.com/users/1138573", "pm_score": 3, "selected": false, "text": "<p>I had a weird situation where a file is always unstaged, this helps me to resolve.</p>\n\n<blockquote>\n <p>git rm .gitattributes<br>\n git add -A<br>\n git reset --hard </p>\n</blockquote>\n" }, { "answer_id": 43365551, "author": "Forhadul Islam", "author_id": 1467428, "author_profile": "https://Stackoverflow.com/users/1467428", "pm_score": 6, "selected": false, "text": "<p>The easiest way to do this is by using this command:</p>\n\n<p>This command is used to discard changes in working directory -</p>\n\n<pre><code>git checkout -- .\n</code></pre>\n\n<p><a href=\"https://git-scm.com/docs/git-checkout\" rel=\"noreferrer\">https://git-scm.com/docs/git-checkout</a> </p>\n\n<p>In git command, stashing of untracked files is achieved by using:</p>\n\n<pre><code>git stash -u\n</code></pre>\n\n<p><a href=\"http://git-scm.com/docs/git-stash\" rel=\"noreferrer\">http://git-scm.com/docs/git-stash</a></p>\n" }, { "answer_id": 44361801, "author": "Pau", "author_id": 4751165, "author_profile": "https://Stackoverflow.com/users/4751165", "pm_score": 3, "selected": false, "text": "<p>You could create your own alias which describes how to do it in a descriptive way.</p>\n\n<p>I use the next alias to discard changes.</p>\n\n<hr>\n\n<h3>Discard changes in a (list of) file(s) in working tree</h3>\n\n<pre><code>discard = checkout --\n</code></pre>\n\n<p>Then you can use it as next to discard all changes:</p>\n\n<pre><code>discard .\n</code></pre>\n\n<p>Or just a file:</p>\n\n<pre><code>discard filename\n</code></pre>\n\n<hr>\n\n<p>Otherwise, if you want to discard all changes and also the untracked files, I use a mix of checkout and clean:</p>\n\n<h3>Clean and discard changes and untracked files in working tree</h3>\n\n<pre><code>cleanout = !git clean -df &amp;&amp; git checkout -- .\n</code></pre>\n\n<p>So the use is simple as next:</p>\n\n<pre><code>cleanout\n</code></pre>\n\n<hr>\n\n<p>Now is available in the next Github repo which contains a lot of aliases:</p>\n\n<ul>\n<li><a href=\"https://github.com/GitAlias/gitalias\" rel=\"noreferrer\">https://github.com/GitAlias/gitalias</a></li>\n</ul>\n" }, { "answer_id": 45420441, "author": "Jesús Castro", "author_id": 2212414, "author_profile": "https://Stackoverflow.com/users/2212414", "pm_score": 3, "selected": false, "text": "<p>If it's almost impossible to rule out modifications of the files, have you considered ignoring them? If this statement is right and you wouldn't touch those files during your development, this command may be useful: </p>\n\n<p><code>git update-index --assume-unchanged file_to_ignore</code></p>\n" }, { "answer_id": 49343276, "author": "2540625", "author_id": 2540625, "author_profile": "https://Stackoverflow.com/users/2540625", "pm_score": 6, "selected": false, "text": "<p>If you merely wish <strong>to remove changes to existing files</strong>, use <code>checkout</code> (<a href=\"https://git-scm.com/docs/git-checkout\" rel=\"noreferrer\">documented here</a>). </p>\n\n<pre><code>git checkout -- .\n</code></pre>\n\n<ul>\n<li>No branch is specified, so it checks out the current branch. </li>\n<li>The double-hyphen (<code>--</code>) tells Git that what follows should be taken as its second argument (path), that you skipped specification of a branch.</li>\n<li>The period (<code>.</code>) indicates all paths. </li>\n</ul>\n\n<p>If you want <strong>to remove files added</strong> since your last commit, use <code>clean</code> (<a href=\"https://git-scm.com/docs/git-clean\" rel=\"noreferrer\">documented here</a>): </p>\n\n<pre><code>git clean -i \n</code></pre>\n\n<ul>\n<li>The <code>-i</code> option initiates an interactive <code>clean</code>, to prevent mistaken deletions. </li>\n<li>A handful of other options are available for a quicker execution; see the documentation. </li>\n</ul>\n\n<p>If you wish <strong>to move changes to a holding space for later access</strong>, use <code>stash</code> (<a href=\"https://git-scm.com/docs/git-stash\" rel=\"noreferrer\">documented here</a>): </p>\n\n<pre><code>git stash\n</code></pre>\n\n<ul>\n<li>All changes will be moved to Git's Stash, for possible later access. </li>\n<li>A handful of options are available for more nuanced stashing; see the documentation. </li>\n</ul>\n" }, { "answer_id": 56870406, "author": "SANGEETHA P.H.", "author_id": 7510315, "author_profile": "https://Stackoverflow.com/users/7510315", "pm_score": 5, "selected": false, "text": "<p>To do a permanent discard:\n<code>git reset --hard</code></p>\n\n<p>To save changes for later:\n<code>git stash</code></p>\n" }, { "answer_id": 57670112, "author": "Khem Raj Regmi", "author_id": 5591577, "author_profile": "https://Stackoverflow.com/users/5591577", "pm_score": 4, "selected": false, "text": "<p>you have a very simple git command <code>git checkout .</code></p>\n" }, { "answer_id": 57880896, "author": "prosoitos", "author_id": 9210961, "author_profile": "https://Stackoverflow.com/users/9210961", "pm_score": 8, "selected": false, "text": "<h3>2019 update</h3>\n<p>You can now discard unstaged changes in <strong>one tracked file</strong> with:</p>\n<pre><code>git restore &lt;file&gt;\n</code></pre>\n<p>and in <strong>all tracked files</strong> in the current directory (recursively) with:</p>\n<pre><code>git restore .\n</code></pre>\n<p>If you run the latter from the root of the repository, it will discard unstaged changes in all tracked files in the project.</p>\n<h3>Notes</h3>\n<ul>\n<li><code>git restore</code> was introduced in <a href=\"https://github.com/git/git/commit/f496b064fc1135e0dded7f93d85d72eb0b302c22\" rel=\"noreferrer\">July 2019</a> and released in version 2.23 as part of a split of the <code>git checkout</code> command into <code>git restore</code> for files and <code>git switch</code> for branches.</li>\n<li><code>git checkout</code> still behaves as it used to and the older answers remain perfectly valid.</li>\n<li>When running <code>git status</code> with unstaged changes in the working tree, this is now what Git suggests to use to discard them (instead of <code>git checkout -- &lt;file&gt;</code> as it used to prior to v2.23).</li>\n<li>As with <code>git checkout -- .</code>, this only discards changes in tracked files. So <a href=\"https://stackoverflow.com/a/12184274/9210961\">Mariusz Nowak's answer</a> still applies and if you want to discard all unstaged changes, including untracked files, you could run, as he suggests, an additional <code>git clean -df</code>.</li>\n</ul>\n" }, { "answer_id": 63950139, "author": "The Schwartz", "author_id": 1369474, "author_profile": "https://Stackoverflow.com/users/1369474", "pm_score": 3, "selected": false, "text": "<p>Just as a reminder, newer versions of git has the restore command, which also is a suggestion when typing git status when you have changed files:</p>\n<p>(use &quot;git add ...&quot; to update what will be committed)</p>\n<p>(use &quot;git restore ...&quot; to discard changes in working directory)</p>\n<p>So git 'restore' is the modern solution to this. It is always a good idea to read the suggestions from git after typing 'git status' :-)</p>\n" }, { "answer_id": 68304651, "author": "Fairoz", "author_id": 5497822, "author_profile": "https://Stackoverflow.com/users/5497822", "pm_score": 2, "selected": false, "text": "<p>If you want to restore unstaged files use\ngit restore --staged .</p>\n" }, { "answer_id": 73040730, "author": "G-Man", "author_id": 4616126, "author_profile": "https://Stackoverflow.com/users/4616126", "pm_score": 3, "selected": false, "text": "<pre><code>git checkout .\n</code></pre>\n<p>This will discard any uncommitted changes to the branch. It won't reset it back if any changes were committed. This is handy when you've done some changes and decide you don't want them for some reason and you have NOT committed those changes. It actually just checks out the branch again and discards any current uncommitted changes.</p>\n<p>( must be in the app's root or home dir for this to work )</p>\n" }, { "answer_id": 73620948, "author": "Cary", "author_id": 250428, "author_profile": "https://Stackoverflow.com/users/250428", "pm_score": -1, "selected": false, "text": "<p>To delete unstaged changes I tried &quot;git restore .&quot; as I was told by Git but it just didn't work. A very good way is to use:</p>\n<pre><code>git revert --hard\n</code></pre>\n<p>It works perfectly. Its Git Help explains perfectly the point:</p>\n<blockquote>\n<p><strong>--hard</strong>\nResets the index and working tree. <strong>Any changes to tracked files in the working tree since are discarded.</strong> Any untracked files or directories in the way of writing any tracked files are simply deleted.</p>\n</blockquote>\n<p>PS: I am using git version 2.35.3.windows.1. I think quite some answers here made the issue over-complicated.</p>\n" }, { "answer_id": 74261094, "author": "Mohamed Eldefrawy", "author_id": 6627676, "author_profile": "https://Stackoverflow.com/users/6627676", "pm_score": 0, "selected": false, "text": "<p>To discard changes in working directory use\n<code>git checkout -- &lt;file&gt;</code>\n<strong>--</strong> means changes in current branch\nreferences:-</p>\n<ul>\n<li><a href=\"https://www.baeldung.com/git-discard-unstaged-changes\" rel=\"nofollow noreferrer\">https://www.baeldung.com/git-discard-unstaged-changes</a></li>\n</ul>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How do I discard changes in my working copy that are not in the index?
Another quicker way is: ``` git stash save --keep-index --include-untracked ``` You don't need to include `--include-untracked` if you don't want to be thorough about it. After that, you can drop that stash with a `git stash drop` command if you like.
52,723
<p>I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite.</p> <p>The code I'm using works something like this (page numbering starts at 0)</p> <p><a href="http://example.com/table?page=0" rel="nofollow noreferrer">http://example.com/table?page=0</a></p> <pre><code>page = request(page) per = 10 // results per page offset = page * per // take one extra record so we know if a next link is needed resultset = query(select columns from table where conditions limit offset, per + 1) if(page &gt; 0) show a previous link if(count(resultset) &gt; per) show a next link unset(resultset[per]) display results </code></pre> <p>Are there more efficient ways to do pagination than this?</p> <p>One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available.</p> <p>Is it more efficient to issue a <code>COUNT(*)</code> query to learn how many rows exist, then stream the results to the browser?</p> <p>Is this one of those "it depends on the size of your table, and whether the <code>count(*)</code> query requires a full table scan in the database backend", "do some profiling yourself" kind of questions?</p>
[ { "answer_id": 52742, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": true, "text": "<p>i'd suggest just doing the count first. a count(primary key) is a very efficient query.</p>\n" }, { "answer_id": 52747, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 1, "selected": false, "text": "<p>I doubt that it will be a problem for your users to wait for the backend to return ten rows. (You can make it up to them by being good at specifying image dimensions, make the webserver negotiate compressed data transfers when possible, etc.)</p>\n\n<p>I don't think that it will be very useful for you to do a count(*) initially.</p>\n\n<p>If you are up to some complicated coding: When the user is looking at page x, use ajax-like magic to pre-load page x+1 for improved user experience.</p>\n\n<p>A general note about pagination:\nIf the data changes while the user browses through your pages, it <em>may</em> be a problem if your solution demands a very high level of consistency. I've writte a note about that <a href=\"http://troels.arvin.dk/db/rdbms/#select-limit-offset-note\" rel=\"nofollow noreferrer\">elsewhere</a>.</p>\n" }, { "answer_id": 53415, "author": "Martin", "author_id": 2581, "author_profile": "https://Stackoverflow.com/users/2581", "pm_score": 2, "selected": false, "text": "<p>I've opted to go with the COUNT(*) two query method, because it allows me to create a link directly to the last page, which the other method does not allow. Performing the count first also allows me to stream the results, and so should work well with higher numbers of records with less memory.</p>\n\n<p>Consistency between pages is not an issue for me. Thank you for your help.</p>\n" }, { "answer_id": 62933, "author": "Mark Webster", "author_id": 7068, "author_profile": "https://Stackoverflow.com/users/7068", "pm_score": 2, "selected": false, "text": "<p>There are several cases where I have a fairly complex (9-12 table join) query, returning many thousands of rows, which I need to paginate. Obviously to paginate nicely, you need to know the total size of the result. With MySQL databases, using the SQL_CALC_FOUND_ROWS directive in the SELECT can help you achieve this easily, although the jury is out on whether that will be more efficient for you to do.</p>\n\n<p>However, since you are using SQLite, I recommend sticking with the 2 query approach. <a href=\"http://marc.info/?l=sqlite-users&amp;m=113579007126860&amp;w=2\" rel=\"nofollow noreferrer\">Here</a> is a very concise thread on the matter.</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite. The code I'm using works something like this (page numbering starts at 0) <http://example.com/table?page=0> ``` page = request(page) per = 10 // results per page offset = page * per // take one extra record so we know if a next link is needed resultset = query(select columns from table where conditions limit offset, per + 1) if(page > 0) show a previous link if(count(resultset) > per) show a next link unset(resultset[per]) display results ``` Are there more efficient ways to do pagination than this? One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available. Is it more efficient to issue a `COUNT(*)` query to learn how many rows exist, then stream the results to the browser? Is this one of those "it depends on the size of your table, and whether the `count(*)` query requires a full table scan in the database backend", "do some profiling yourself" kind of questions?
i'd suggest just doing the count first. a count(primary key) is a very efficient query.
52,732
<p>I need to dynamically create a Video object in ActionScript 2 and add it to a movie clip. In AS3 I just do this:</p> <pre><code>var videoViewComp:UIComponent; // created elsewhere videoView = new Video(); videoView.width = 400; videoView.height = 400; this.videoViewComp.addChild(videoView); </code></pre> <p>Unfortunately, I can't figure out how to accomplish this in AS2. Video isn't a child of MovieClip, so attachMovie() doesn't seem to be getting me anything. I don't see any equivalent to AS3's UIComponent.addChild() method either.</p> <p>Is there any way to dynamically create a Video object in AS2 that actually shows up on the stage?</p> <hr> <p>I potentially need multiple videos at a time though. Is it possible to duplicate that video object?</p> <p>I think I have another solution working. It's not optimal, but it fits with some of the things I have to do for other components so it's not too out of place in the project. Once I get it figured out I'll post what I did here.</p>
[ { "answer_id": 53254, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "<p>I recommend you create a single instance of the Video object, leave it invisible (i.e., <code>videoview.visible = false</code>), and load the clip when you need it, displaying it at the appropriate time. You can also use <code>swapDepth()</code> if it becomes necessary.</p>\n\n<p>Video handling in AS2 is not the best thing ever. Rest assured you'll run into a lot of little problems (looping without gaps, etc).</p>\n" }, { "answer_id": 55141, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": true, "text": "<p>Ok, I've got something working.</p>\n\n<p>First, I created a new Library symbol and called it \"VideoWrapper\". I then added a single Video object to that with an ID of \"video\".</p>\n\n<p>Now, any time I need to dynamically add a Video to my state I can use MovieClip.attachMovie() to add a new copy of the Video object.</p>\n\n<p>To make things easier I wrote a VideoWrapper class that exposes basic UI element handling (setPosition(), setSize(), etc). So when dealing with the Video in regular UI layout code I just use those methods so it looks just like all my other UI elements. When dealing with the video I just access the \"video\" member of the class.</p>\n\n<p>My actual implementation is a bit more complicated, but that's the basics of how I got things working. I have a test app that's playing 2 videos, one from the local camera and one streaming from FMS, and it's working great.</p>\n" }, { "answer_id": 99109, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": 0, "selected": false, "text": "<p>your approach is what i usually do because other option is to include the UIcomponent mediaDisplay into library and then attach that component using attachMovie but i found mediaDisplay i little buggy so i prefer to use the primitive video instance .</p>\n" }, { "answer_id": 3603369, "author": "Tonio FERENER-VARI", "author_id": 435264, "author_profile": "https://Stackoverflow.com/users/435264", "pm_score": 0, "selected": false, "text": "<p>I hope that the code below will be very useful for you:</p>\n\n<pre><code>import UTIL.MEDIA.MEDIAInstances\n\nclass Main\n\n{\n static function main() {\n\n var MEDIAInstancesInstance :MEDIAInstances = new MEDIAInstances (); \n\n _root.Video_Display.play (\"IsothermalCompression.flv\", 0);\n\n _root.VideoDisplayMC.onPress = function() { \n\n _root.Video_Display.seek (0); \n\n } // _root.displayMC.onPress = function() {\n\n } // static function main() \n\n} // class Main \n\n// \n\nimport UTIL.MEDIA.VideoDisplay \n\nclass UTIL.MEDIA.MEDIAInstances \n\n { \n\n function MEDIAInstances() \n\n {\n\n // depth \n _root.createEmptyMovieClip (\"VideoDisplayMC\", 500); \n //\n var Video_Display:VideoDisplay \n = \n new VideoDisplay(_root.VideoDisplayMC, \"Video_Display\", 1); \n\n Video_Display.setLocation(400, 0); Video_Display.setSize (320, 240); \n // \n _root.Video_Display = Video_Display; _root.VideoDisplayMC._alpha = 75; \n\n } // MEDIAInstances()\n\n} // class UTIL.MEDIA.MEDIAInstances\n\n//\n\nclass UTIL.MEDIA.VideoDisplay\n\n{\n private var display:MovieClip, nc:NetConnection, ns:NetStream;\n\n function VideoDisplay(parent:MovieClip, name:String, depth:Number)\n\n {\n display = parent.attachMovie(\"VideoDisplay\", name, depth);\n\n nc = new NetConnection(); nc.connect(null); ns = new NetStream(nc);\n\n display.video.attachVideo(ns);\n }\n function setSize(width:Number, heigth:Number):Void\n\n { display.video._width = width; display.video._height = heigth;}\n\n function setLocation(x:Number, y:Number):Void { display._x = x; display._y = y;}\n\n public function play(url:String, bufferTime:Number):Void\n {\n if (bufferTime != undefined) ns.setBufferTime(bufferTime); ns.play(url);\n }\n //\n public function pause():Void { ns.pause();}\n //\n public function seek(offset:Number):Void { ns.seek(offset); }\n\n} // UTIL.MEDIA.VideoDisplay\n</code></pre>\n" }, { "answer_id": 4334511, "author": "Tonio FERENER-VARI", "author_id": 527889, "author_profile": "https://Stackoverflow.com/users/527889", "pm_score": 1, "selected": false, "text": "<p>To send you the ends of a line which is a tag, I use HTML Symbol Entities from <a href=\"http://www.w3schools.com/tags/ref_symbols.asp\" rel=\"nofollow\">w3schools</a></p>\n\n<p>An example, taken from a project would be as follows:</p>\n\n<pre><code>&lt; asset path=\"library\\video.swf\" /&gt;\n</code></pre>\n\n<p>The line above shows that there is a directory called library which contains the file <code>video.swf</code> </p>\n\n<p>Besides, there is the file video.xml in the directory library. That file contains the lines</p>\n\n<pre><code>&lt;xml version=\"1.0\" encoding=\"utf-8\" &gt;\n&lt;movie version=\"7\"&gt; \n &lt;frame&gt;\n &lt;library&gt;\n &lt;clip id=\"VideoDisplay\"&gt;\n &lt;frame&gt;\n &lt;video id=\"VideoSurface\" width=\"160\" height=\"120\" /&gt;\n &lt;place id=\"VideoSurface\" name=\"video\" /&gt;\n &lt;/frame&gt;\n &lt;/clip&gt;\n &lt;/library&gt;\n &lt;/frame&gt;\n&lt;/movie&gt;\n</code></pre>\n\n<p>Long ago my son Alex downloaded the code of VideoDisplay class and the directory library from Internet</p>\n\n<p>I have iproved the code of the class VideoDisplay.</p>\n\n<p>by writting 2 members</p>\n\n<pre><code> public function pos():Number\n{\n return ns.time;\n}\n\n public function close():Void\n{\n return ns.close();\n}\n</code></pre>\n\n<p>The program I have created \nis \nmore than an explorer and presenter of <code>.flv</code> files</p>\n\n<p>It also\nis an explorer and presenter of the chosen fragments of each <code>.flv</code> file </p>\n\n<p>Now the code of VideoDisplay class is:</p>\n\n<pre><code>class util.VideoDisplay\n{\n //{ PUBLIC MEMBERS\n\n\n /**\n * Create a new video display surface\n */\n\n function VideoDisplay(targetURI:String, parent:MovieClip, name:String, depth:Number, initObj)\n\n {\n display = parent.attachMovie(\"VideoDisplay\", name, depth, initObj);\n\n // create video stream\n nc = new NetConnection();\n nc.connect(targetURI);\n ns = new NetStream(nc);\n\n // attach the video stream to the video object\n display.video.attachVideo(ns);\n }\n\n /**\n * Video surface dimensions\n */\n function setSize(width:Number, heigth:Number):Void\n {\n display.video._width = width;\n display.video._height = heigth;\n }\n /**\n * Video clip position\n */\n function setLocation(x:Number, y:Number):Void\n {\n display._x = x;\n display._y = y;\n }\n\n /**\n * Start streaming\n * @param url FLV file\n * @param bufferTime Buffer size (optional) \n */\n public function play(url:String, bufferTime:Number):Void\n {\n if (bufferTime != undefined) ns.setBufferTime(bufferTime);\n ns.play(url);\n }\n /**\n * Pause streaming\n */\n public function pause():Void\n {\n ns.pause();\n }\n /**\n * Seek position in video\n */\n public function seek(offset:Number):Void\n {\n ns.seek(offset);\n } \n\n /**\n * Get position in video\n */\n\n public function pos():Number\n {\n return ns.time;\n }\n\n public function close():Void\n {\n return ns.close();\n }\n\n //}\n\n //{ PRIVATE MEMBERS \n\n private var display:MovieClip;\n private var nc:NetConnection;\n private var ns:NetStream;\n\n //}\n}\n</code></pre>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
I need to dynamically create a Video object in ActionScript 2 and add it to a movie clip. In AS3 I just do this: ``` var videoViewComp:UIComponent; // created elsewhere videoView = new Video(); videoView.width = 400; videoView.height = 400; this.videoViewComp.addChild(videoView); ``` Unfortunately, I can't figure out how to accomplish this in AS2. Video isn't a child of MovieClip, so attachMovie() doesn't seem to be getting me anything. I don't see any equivalent to AS3's UIComponent.addChild() method either. Is there any way to dynamically create a Video object in AS2 that actually shows up on the stage? --- I potentially need multiple videos at a time though. Is it possible to duplicate that video object? I think I have another solution working. It's not optimal, but it fits with some of the things I have to do for other components so it's not too out of place in the project. Once I get it figured out I'll post what I did here.
Ok, I've got something working. First, I created a new Library symbol and called it "VideoWrapper". I then added a single Video object to that with an ID of "video". Now, any time I need to dynamically add a Video to my state I can use MovieClip.attachMovie() to add a new copy of the Video object. To make things easier I wrote a VideoWrapper class that exposes basic UI element handling (setPosition(), setSize(), etc). So when dealing with the Video in regular UI layout code I just use those methods so it looks just like all my other UI elements. When dealing with the video I just access the "video" member of the class. My actual implementation is a bit more complicated, but that's the basics of how I got things working. I have a test app that's playing 2 videos, one from the local camera and one streaming from FMS, and it's working great.
52,755
<p>I am using Windows, and I have two monitors.</p> <p>Some applications will <em>always</em> start on my primary monitor, no matter where they were when I closed them.</p> <p>Others will always start on the <em>secondary</em> monitor, no matter where they were when I closed them.</p> <p>Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?</p> <p>@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into.</p>
[ { "answer_id": 52775, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "<p>I'm fairly sure the primary monitor is the default. If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.</p>\n\n<p>EDIT: The way I usually do it is to have the location stored in the app's settings. On load, if there is no value for them, it defaults to the center of the screen. On closing of the form, it records its position. That way, whenever it opens, it's where it was last. I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.</p>\n\n<p>-- Kevin Fairchild</p>\n" }, { "answer_id": 52779, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 0, "selected": false, "text": "<p>Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.</p>\n\n<p>So I am not sure there is a way to tell every program where to open. Hope that helps some.</p>\n" }, { "answer_id": 52795, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "<p>Get UltraMon. Quickly. </p>\n\n<p><a href=\"http://realtimesoft.com/ultramon/\" rel=\"noreferrer\">http://realtimesoft.com/ultramon/</a> </p>\n\n<p>It doesn't let you specify what monitor an app starts on, but it lets you move an app to the another monitor, and keep its aspect ratio intact, with one mouse click. It is a very handy utility.</p>\n\n<p>Most programs will start where you last left them. So if you have two monitors at work, but only one at home, it's possible to start you laptop at home and not see the apps running on the other monitor (which now isn't there). UltrMon also lets you move those orphan apps back to the main screen quickly and easily.</p>\n" }, { "answer_id": 53187, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 7, "selected": true, "text": "<p>Correctly written Windows apps that want to save their location from run to run will save the results of <a href=\"http://msdn.microsoft.com/ru-ru/library/windows/desktop/ms633518%28v=vs.85%29.aspx\" rel=\"noreferrer\"><code>GetWindowPlacement()</code></a> before shutting down, then use <code>SetWindowPlacement()</code> on startup to restore their position.</p>\n\n<p>Frequently, apps will store the results of <code>GetWindowPlacement()</code> in the registry as a <code>REG_BINARY</code> for easy use.</p>\n\n<p>The <code>WINDOWPLACEMENT</code>route has many advantages over other methods:</p>\n\n<ul>\n<li>Handles the case where the screen resolution changed since the last run: <code>SetWindowPlacement()</code> will automatically ensure that the window is not entirely offscreen</li>\n<li>Saves the state (minimized/maximized) but also saves the restored (normal) size and position</li>\n<li>Handles desktop metrics correctly, compensating for the taskbar position, etc. (i.e. uses \"workspace coordinates\" instead of \"screen coordinates\" -- techniques that rely on saving screen coordinates may suffer from the \"walking windows\" problem where a window will always appear a little lower each time if the user has a toolbar at the top of the screen).</li>\n</ul>\n\n<p>Finally, programs that handle window restoration properly will take into account the <code>nCmdShow</code> parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize):</p>\n\n<pre><code>if(nCmdShow != SW_SHOWNORMAL)\n placement.showCmd = nCmdShow; //allow shortcut to override\n</code></pre>\n\n<p>For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's <code>setBounds()</code>/<code>getBounds()</code> problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the <code>WINDOWPLACEMENT</code> functions.</p>\n" }, { "answer_id": 53946, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 0, "selected": false, "text": "<p>I've noticed that if I put a shortcut on my desktop on one screen the launched application may appear on that screen (<strong><em>if</em></strong> that app doesn't reposition itself).</p>\n\n<p>This also applies to running things from Windows Explorer - if Explorer is on one screen the launched application will pick that monitor to use.</p>\n\n<p>Again - I think this is when the launching application specifies the default (windows managed) position. Most applications seem to override this default behavior in some way.</p>\n\n<p>A simple window created like so will do this:</p>\n\n<p>hWnd = CreateWindow(windowClass, windowTitle, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, SW_SHOW, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);</p>\n" }, { "answer_id": 73882, "author": "stevex", "author_id": 8831, "author_profile": "https://Stackoverflow.com/users/8831", "pm_score": 2, "selected": false, "text": "<p>Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.</p>\n\n<p>Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.</p>\n\n<p>To figure out how big the display really is, check out GetSystemMetrics.</p>\n" }, { "answer_id": 511735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Here's what I've found. If you want an app to open on your secondary monitor by default do the following:</p>\n\n<pre><code>1. Open the application.\n2. Re-size the window so that it is not maximized or minimized.\n3. Move the window to the monitor you want it to open on by default.\n4. Close the application. Do not re-size prior to closing.\n5. Open the application.\n It should open on the monitor you just moved it to and closed it on.\n6. Maximize the window.\n</code></pre>\n\n<p>The application will now open on this monitor by default. If you want to change it to another monitor, just follow steps 1-6 again.</p>\n" }, { "answer_id": 702893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>So I had this issue with Adobe Reader 9.0. Somehow the program forgot to open on my right monitor and was consistently opening on my left monitor. Most programs allow you to drag it over, maximize the screen, and then close it out and it will remember. Well, with Adobe, I had to drag it over and then close it before maximizing it, in order for Windows to remember which screen to open it in next time. Once you set it to the correct monitor, then you can maximize it. I think this is stupid, since almost all windows programs remember it automatically without try to rig a way for XP to remember.</p>\n" }, { "answer_id": 10937493, "author": "Mykey", "author_id": 1442941, "author_profile": "https://Stackoverflow.com/users/1442941", "pm_score": 1, "selected": false, "text": "<p>So I agree there are some apps that you can configured to open on one screen by maximizing or right clicking and moving/sizing screen, then close and reopen. However, there are others that will only open on the main screen. </p>\n\n<p>What I've done to resolve: set the monitor you prefer stubborn apps to open on, as monitor 1 and the your other monitor as 2, then change your monitor 2 to be the primary - so your desktop settings and start bar remain. Hope this helps. </p>\n" }, { "answer_id": 25909284, "author": "Croo", "author_id": 561709, "author_profile": "https://Stackoverflow.com/users/561709", "pm_score": 4, "selected": false, "text": "<p>It's not exactly the answer to this question but I dealt with this problem with the <code>Shift + Win + [left,right] arrow keys</code> shortcut. You can move the currently active window to another monitor with it.</p>\n" }, { "answer_id": 27714393, "author": "Bored", "author_id": 4406959, "author_profile": "https://Stackoverflow.com/users/4406959", "pm_score": -1, "selected": false, "text": "<p>Right click the shortcut and select properties. \nMake sure you are on the \"Shortcut\" Tab. \nSelect the RUN drop down box and change it to Maximized. </p>\n\n<p>This may assist in launching the program in full screen on the primary monitor. </p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I am using Windows, and I have two monitors. Some applications will *always* start on my primary monitor, no matter where they were when I closed them. Others will always start on the *secondary* monitor, no matter where they were when I closed them. Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default? @rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into.
Correctly written Windows apps that want to save their location from run to run will save the results of [`GetWindowPlacement()`](http://msdn.microsoft.com/ru-ru/library/windows/desktop/ms633518%28v=vs.85%29.aspx) before shutting down, then use `SetWindowPlacement()` on startup to restore their position. Frequently, apps will store the results of `GetWindowPlacement()` in the registry as a `REG_BINARY` for easy use. The `WINDOWPLACEMENT`route has many advantages over other methods: * Handles the case where the screen resolution changed since the last run: `SetWindowPlacement()` will automatically ensure that the window is not entirely offscreen * Saves the state (minimized/maximized) but also saves the restored (normal) size and position * Handles desktop metrics correctly, compensating for the taskbar position, etc. (i.e. uses "workspace coordinates" instead of "screen coordinates" -- techniques that rely on saving screen coordinates may suffer from the "walking windows" problem where a window will always appear a little lower each time if the user has a toolbar at the top of the screen). Finally, programs that handle window restoration properly will take into account the `nCmdShow` parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize): ``` if(nCmdShow != SW_SHOWNORMAL) placement.showCmd = nCmdShow; //allow shortcut to override ``` For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's `setBounds()`/`getBounds()` problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the `WINDOWPLACEMENT` functions.
52,785
<p>I think this is specific to IE 6.0 but...</p> <p>In JavaScript I add a <code>div</code> to the DOM. I assign an <code>id</code> attribute. When I later try to pick up the <code>div</code> by the <code>id</code> all I get is <code>null</code>.</p> <p>Any suggestions?</p> <p>Example:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>Alert prints <code>"::null"</code></p> <p>Seems to work fine in Firefox 2.0+</p>
[ { "answer_id": 52791, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "<p>You have to add the div to the dom.</p>\n\n<pre><code>// Create the Div\nvar oDiv = document.createElement('div');\ndocument.body.appendChild(oDiv);\n</code></pre>\n" }, { "answer_id": 52792, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>The div needs to be added to an element for it to be part of the document.</p>\n\n<pre><code>document.appendChild(newDiv);\n\nalert( document.getElementById(\"obj_1000\") );\n</code></pre>\n" }, { "answer_id": 52793, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 0, "selected": false, "text": "<p>newDiv.setAttribute( \"ID\", \"obj_1000\" );</p>\n\n<p>should be</p>\n\n<p>newDiv.id = \"obj_1000\";</p>\n" }, { "answer_id": 52805, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<p>In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via <code>getElementById()</code>), you also need to use a lower-case attribute name in order for IE6 to recognize it as the <code>id</code>:</p>\n\n<pre><code>var newDiv = document.createElement(\"DIV\"); \nnewDiv.setAttribute(\"id\", \"obj_1000\");\ndocument.body.appendChild(newDiv);\n\nalert(\"Added:\"\n + newDiv.getAttribute(\"id\") \n + \":\" + newDiv.id + \":\" \n + document.getElementById(\"obj_1000\") );\n</code></pre>\n\n<p>...responds as expected:</p>\n\n<pre><code>Added:obj_1000:obj_1000:[object]\n</code></pre>\n\n<hr>\n\n<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx\" rel=\"noreferrer\">MSDN documentation</a> for <code>setAttribute()</code>, up to IE8 there is an optional <em>third parameter</em> that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is...</p>\n" }, { "answer_id": 52811, "author": "Markus", "author_id": 2490, "author_profile": "https://Stackoverflow.com/users/2490", "pm_score": 0, "selected": false, "text": "<p>Hummm, thanks for putting me on the right track guys...this was odd but it turns out that if I change the case to lower case, everything starting working just fine...</p>\n\n<p>Finished Result:</p>\n\n<pre><code>var newDiv = document.createElement(\"DIV\");\nnewDiv.setAttribute(\"id\", \"obj_1000\");\ndocument.appendChild(newDiv);\n\nalert(\"Added:\" +\n newDiv.getAttribute(\"id\") + \":\" +\n newDiv.id + \":\" +\n document.getElementById(\"obj_1000\"));\n</code></pre>\n\n<p>ODD...VERY ODD</p>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
I think this is specific to IE 6.0 but... In JavaScript I add a `div` to the DOM. I assign an `id` attribute. When I later try to pick up the `div` by the `id` all I get is `null`. Any suggestions? Example: ``` var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); ``` Alert prints `"::null"` Seems to work fine in Firefox 2.0+
In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via `getElementById()`), you also need to use a lower-case attribute name in order for IE6 to recognize it as the `id`: ``` var newDiv = document.createElement("DIV"); newDiv.setAttribute("id", "obj_1000"); document.body.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("id") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); ``` ...responds as expected: ``` Added:obj_1000:obj_1000:[object] ``` --- According to the [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx) for `setAttribute()`, up to IE8 there is an optional *third parameter* that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is...