qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
51,019
<p>What does it mean when a <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a> process is "idle in transaction"?</p> <p>On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:</p> <pre><code>postgres: user db 127.0.0.1(55658) idle in transaction </code></pre> <p>Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated.</p>
[ { "answer_id": 51058, "author": "Anonymoose", "author_id": 2391, "author_profile": "https://Stackoverflow.com/users/2391", "pm_score": 7, "selected": true, "text": "idle in transaction" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
51,021
<p>Ruby has two different exceptions mechanisms: Throw/Catch and Raise/Rescue.</p> <p>Why do we have two?</p> <p>When should you use one and not the other? </p>
[ { "answer_id": 8692077, "author": "Jared Beck", "author_id": 567762, "author_profile": "https://Stackoverflow.com/users/567762", "pm_score": 7, "selected": false, "text": "raise" }, { "answer_id": 27277044, "author": "Mark Amery", "author_id": 1709587, "author_profile": "https://Stackoverflow.com/users/1709587", "pm_score": 5, "selected": false, "text": "raise" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2653/" ]
51,022
<p>I would like to use Haskell more for my projects, and I think if I can get started using it for web apps, it would really help that cause. I have tried happs once or twice but had trouble getting off the ground. Are there simpler/more conventional (more like lamp) frameworks out there that I can use or should I just give happs another try?</p>
[ { "answer_id": 16232663, "author": "agocorona", "author_id": 2321205, "author_profile": "https://Stackoverflow.com/users/2321205", "pm_score": 2, "selected": false, "text": "module Main where\nimport MFlow.Wai.Blaze.Html.All\n\nmain= do\n addMessageFlows [(\"sum\", transient . runFlow $ sumIt )]\n wait $ run 8081 waiMessageFlow\n\nsumIt= do\n setHeader $ html . body\n n1 <- ask $ p << \"give me the first number\" ++> getInt Nothing\n n2 <- ask $ p << \"give me the second number\" ++> getInt Nothing\n ask $ p << (\"the result is \" ++ show (n1 + n2)) ++> wlink () << p << \"click here\"\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
51,027
<p>What are the other types of database systems out there. I've recently came across couchDB that handles data in a non relational way. It got me thinking about what other models are other people is using.</p> <p>So, I want to know what other types of data model is out there. (I'm not looking for any specifics, just want to look at how other people are handling data storage, my interest are purely academic)</p> <p>The ones I already know are:</p> <ol> <li>RDBMS (mysql,postgres etc..)</li> <li>Document based approach (couchDB, lotus notes)</li> <li>Key/value pair (BerkeleyDB) </li> </ol>
[ { "answer_id": 2658647, "author": "Stefano Borini", "author_id": 78374, "author_profile": "https://Stackoverflow.com/users/78374", "pm_score": 1, "selected": false, "text": "start node ----relation----> end node \n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2976/" ]
51,028
<p>How do I create a background process with Haskell on windows without a visible command window being created?</p> <p>I wrote a Haskell program that runs backup processes periodically but every time I run it, a command window opens up to the top of all the windows. I would like to get rid of this window. What is the simplest way to do this?</p>
[ { "answer_id": 51980, "author": "Martin Del Vecchio", "author_id": 5397, "author_profile": "https://Stackoverflow.com/users/5397", "pm_score": 0, "selected": false, "text": "SHELLEXECUTEINFO Info;\nBOOL b;\n\n// Execute it\nmemset (&Info, 0, sizeof (Info));\nInfo.cbSize = sizeof (Info);\nInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;\nInfo.hwnd = NULL;\nInfo.lpVerb = \"open\";\nInfo.lpFile = \"rsync.exe\";\nInfo.lpParameters = \"whatever parameters you like\";\nInfo.lpDirectory = NULL;\nInfo.nShow = SW_HIDE;\nb = ShellExecuteEx (&Info);\nif (b)\n {\n // Looks good; if there is an instance, wait for it\n if (Info.hProcess)\n {\n // Wait\n WaitForSingleObject (Info.hProcess, INFINITE);\n }\n }\n" }, { "answer_id": 52342, "author": "Alasdair", "author_id": 2654, "author_profile": "https://Stackoverflow.com/users/2654", "pm_score": 3, "selected": false, "text": "module Main where\nimport System\nimport System.Process\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n putStrLn \"Running command...\"\n pid <- runCommand \"mplayer song.mp3\" -- or whatever you want\n replicateM_ 10 $ putStrLn \"Doing other stuff\"\n waitForProcess pid >>= exitWith\n" }, { "answer_id": 58228, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 3, "selected": false, "text": "import System.Process\nimport System.IO\nmain = do\n inH <- openFile \"in\" ReadMode\n outH <- openFile \"out\" WriteMode\n runProcess \"rsync.bat\" [] Nothing Nothing (Just inH) (Just outH) (Just outH)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
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": 51044, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": false, "text": "double atof();\n" }, { "answer_id": 51080, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 9, "selected": true, "text": "void foo()" }, { "answer_id": 36835303, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "int f();\n// means int f(void) in C ++\n// int f( unknown ) in C\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
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": "forfiles -p \"C:\\what\\ever\" -s -m *.* -d <number of days> -c \"cmd /c del @path\"\n" }, { "answer_id": 1322886, "author": "Jay", "author_id": 151152, "author_profile": "https://Stackoverflow.com/users/151152", "pm_score": 5, "selected": false, "text": "@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& set Months=%%e& 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&& 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&& 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& set Epoch=%Epoch%\n exit /b 0\n" }, { "answer_id": 1322976, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 4, "selected": false, "text": "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 >> 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" }, { "answer_id": 3161104, "author": "J.R.", "author_id": 381472, "author_profile": "https://Stackoverflow.com/users/381472", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 4383245, "author": "neuracnu", "author_id": 19277, "author_profile": "https://Stackoverflow.com/users/19277", "pm_score": 2, "selected": false, "text": "mkdir c:\\temp\\OldDirectoriesGoHere\nrobocopy c:\\logs\\SoManyDirectoriesToDelete\\ c:\\temp\\OldDirectoriesGoHere\\ /move /minage:7\nrmdir /s /q c:\\temp\\OldDirectoriesGoHere\n" }, { "answer_id": 4436614, "author": "segero", "author_id": 551504, "author_profile": "https://Stackoverflow.com/users/551504", "pm_score": 4, "selected": false, "text": "forfiles -p \"d:\\logs\" -s -m*.log -d-15 -c\"cmd /c del @PATH\\@FILE\" \n" }, { "answer_id": 4800680, "author": "Paris", "author_id": 589995, "author_profile": "https://Stackoverflow.com/users/589995", "pm_score": 3, "selected": false, "text": "DelOldFiles.vbs" }, { "answer_id": 6149776, "author": "Iman", "author_id": 772718, "author_profile": "https://Stackoverflow.com/users/772718", "pm_score": 6, "selected": false, "text": "ROBOCOPY C:\\source C:\\destination /mov /minage:7\ndel C:\\destination /q\n" }, { "answer_id": 6275689, "author": "Arno Jansen", "author_id": 788773, "author_profile": "https://Stackoverflow.com/users/788773", "pm_score": 5, "selected": false, "text": "forfiles /p \"v:\" /s /m *.* /d -3 /c \"cmd /c del @path\"\n" }, { "answer_id": 8123408, "author": "Aidan Ewen", "author_id": 795896, "author_profile": "https://Stackoverflow.com/users/795896", "pm_score": 3, "selected": false, "text": "forfiles -p\"C:\\what\\ever\" -s -m*.* -d<number of days> -c\"cmd /c del @path\"\n" }, { "answer_id": 10358807, "author": "NotJustClarkKent", "author_id": 334695, "author_profile": "https://Stackoverflow.com/users/334695", "pm_score": 3, "selected": false, "text": "forfiles /P c:\\sql_backups\\ /S /M *.sql /D -90 /C \"cmd /c del @PATH\"\n" }, { "answer_id": 16234804, "author": "Graham Laight", "author_id": 1649135, "author_profile": "https://Stackoverflow.com/users/1649135", "pm_score": 3, "selected": false, "text": "// 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 < dateTest)\n {\n var filename = file.name;\n var ext = filename.split('.').pop().toLowerCase();\n\n if (ext != 'exe' && 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" }, { "answer_id": 20671056, "author": "Goran B.", "author_id": 2175524, "author_profile": "https://Stackoverflow.com/users/2175524", "pm_score": 2, "selected": false, "text": "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 & echo: file extention not specified (default set to \"*.log\")\nIF [%2] EQU [] echo: file directory no specified (a required parameter), exiting! & 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: >> c:\\trimLogFiles\\logBat\\log.txt\necho: executed on %DATE% %TIME% >> c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- >> c:\\trimLogFiles\\logBat\\log.txt\necho: in path [ %logPath% ] >> c:\\trimLogFiles\\logBat\\log.txt\necho: finding all files like [ %logFileExt% ] >> c:\\trimLogFiles\\logBat\\log.txt\necho: older than [ %keepDD% ] days >> c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- >> c:\\trimLogFiles\\logBat\\log.txt\n::\nFORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c \"cmd /c echo @path\" >> c:\\trimLogFiles\\logBat\\log.txt 2<&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: >> c:\\trimLogFiles\\logBat\\log.txt\n echo: deleting files ... >> c:\\trimLogFiles\\logBat\\log.txt\n echo: >> 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 & LOG\n::\nIF %ERRORLEVEL% EQU 0 echo: deletion successfull! & echo: deletion successfull! >> c:\\trimLogFiles\\logBat\\log.txt\necho: ---------------------------------------------------------- >> c:\\trimLogFiles\\logBat\\log.txt\n" }, { "answer_id": 20893589, "author": "Lectrode", "author_id": 1284754, "author_profile": "https://Stackoverflow.com/users/1284754", "pm_score": 2, "selected": false, "text": "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;;\">nul || if exist \"%%~nxa\" DEL /F /Q \"%%a\">nul 2>&1)\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": "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" }, { "answer_id": 28395552, "author": "Mofi", "author_id": 3074564, "author_profile": "https://Stackoverflow.com/users/3074564", "pm_score": 3, "selected": false, "text": "GetSeconds" }, { "answer_id": 29420453, "author": "Sting", "author_id": 782991, "author_profile": "https://Stackoverflow.com/users/782991", "pm_score": 3, "selected": false, "text": "forfiles /p \"[file path...]\\IDOC_ARCHIVE\" /s /m *.txt /d -1 /c \"cmd /c del @path\" 2>&1 | findstr /V /O /C:\"ERROR: No files found with the specified search criteria.\"2>&1 | findstr ERROR&&ECHO found error||echo found success\n" }, { "answer_id": 31628166, "author": "Viktor Ka", "author_id": 4329986, "author_profile": "https://Stackoverflow.com/users/4329986", "pm_score": 4, "selected": false, "text": " forfiles /p \"c:\\FOLDERpath\" /d -30 /c \"cmd /c del @path\"\n" }, { "answer_id": 38958120, "author": "Shawn Pauliszyn", "author_id": 5095809, "author_profile": "https://Stackoverflow.com/users/5095809", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 44065466, "author": "Snickbrack", "author_id": 3992990, "author_profile": "https://Stackoverflow.com/users/3992990", "pm_score": 1, "selected": false, "text": "@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" }, { "answer_id": 45113009, "author": "efdummy", "author_id": 2513412, "author_profile": "https://Stackoverflow.com/users/2513412", "pm_score": 1, "selected": false, "text": "@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%\") & (goto :end)\n\n:main\n @dir /a-d-h-s /s /b %_targetdir%\\*>%_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 \":\" > %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" }, { "answer_id": 49322063, "author": "GBGOLC", "author_id": 2048573, "author_profile": "https://Stackoverflow.com/users/2048573", "pm_score": 3, "selected": false, "text": "ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 & ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 /PURGE\n" }, { "answer_id": 64800901, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 0, "selected": false, "text": "FileTimeFilterJS.bat" }, { "answer_id": 66343607, "author": "Miguel Carrillo", "author_id": 11762632, "author_profile": "https://Stackoverflow.com/users/11762632", "pm_score": 3, "selected": false, "text": "forfiles -p \"C:\\folder\" -m *.* -d -3 -c \"cmd /c del /q @path\"\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
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": "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" }, { "answer_id": 51369, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 57562, "author": "NateSchneider", "author_id": 5129, "author_profile": "https://Stackoverflow.com/users/5129", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 63160, "author": "Gabor Kecskemeti", "author_id": 6572, "author_profile": "https://Stackoverflow.com/users/6572", "pm_score": 1, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
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": "2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb.\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
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": "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" }, { "answer_id": 51375, "author": "paulmorriss", "author_id": 2983, "author_profile": "https://Stackoverflow.com/users/2983", "pm_score": 0, "selected": false, "text": "Workbooks.Open FileName:=\"\\\\the\\share\\file.xls\"\n" }, { "answer_id": 51413, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "ThisWorkbook" }, { "answer_id": 54640, "author": "Justin Bennett", "author_id": 271, "author_profile": "https://Stackoverflow.com/users/271", "pm_score": 0, "selected": false, "text": "Dim xl As Excel.Application\nSet xl = CreateObject(\"Excel.Application\")\nxl.Workbooks.Open \"\\\\owghome1\\bennejm$\\testing.xls\"\nxl.Sheets(\"Sheet1\").Select\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271/" ]
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": 51182, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 2, "selected": false, "text": "ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n" }, { "answer_id": 51484, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 0, "selected": false, "text": "if (things_are_ok) {\n // Do a lot of stuff.\n return true;\n} else {\n ExpressDismay(error_str);\n return false;\n}\n" }, { "answer_id": 4297073, "author": "Zecc", "author_id": 400127, "author_profile": "https://Stackoverflow.com/users/400127", "pm_score": 2, "selected": false, "text": "ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4910/" ]
51,109
<p>When using custom-draw (NM_CUSTOMDRAW) to draw the entire contents of a ListView SubItem (in Report/Details view), it would be nice to be able to apply the same left and right padding in my custom paint method that is applied by the control itself for non-custom-drawn items.</p> <p>Is there a way to programmatically retrieve this padding value? Is it related to the width of a particular character (&quot; &quot; or &quot;w&quot; or something?) or is it a fixed value (6px on left and 3px on right or something) or...?</p> <p>EDIT: To clarify, <strong>I want to add the same padding to my NM_CUSTOMDRAWn SubItems that the control adds to items that it draws</strong>, and the metric that I'm looking for, for example, is the white space between the beginning of the 2nd column and the word &quot;Siamese&quot; in the following screenshot (<em>Note: screenshot from MSDN added to help explain my question</em>):</p> <p><a href="https://i.stack.imgur.com/yTHoy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yTHoy.png" alt="List View in Report View" /></a><br /> <sub>(source: <a href="https://msdn.microsoft.com/Bb774735.lv_detailsview(en-us,VS.85).png" rel="nofollow noreferrer">microsoft.com</a>)</sub></p> <p>Note that the word &quot;Siamese&quot; is aligned with the header item (&quot;Breed&quot;). I would like to be able to guarantee the same alignment for custom-drawn items.</p>
[ { "answer_id": 8448191, "author": "Patrick", "author_id": 1090057, "author_profile": "https://Stackoverflow.com/users/1090057", "pm_score": 1, "selected": false, "text": "LVCOLUMN myLVCOLUMN;\nmyLVCOLUMN.mask=LVCF_FMT;\nListView_GetColumn(hwnd,nCol,&myLVCOLUMN);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
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": "if(dr.Read())\n{\n //do stuff\n}\nelse\n{\n //it's empty\n}\n" }, { "answer_id": 51121, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": false, "text": "IDataReader" }, { "answer_id": 16146731, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "System.Data.IDataReader" }, { "answer_id": 29829487, "author": "SimonGates", "author_id": 387809, "author_profile": "https://Stackoverflow.com/users/387809", "pm_score": 2, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
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": 51143, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 51225, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": true, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ]
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": "\"foo\"" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4550/" ]
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": "//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" }, { "answer_id": 51155, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 51173, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": false, "text": "var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains(\"<your process name>\"));\n" }, { "answer_id": 51189, "author": "csjohnst", "author_id": 1292, "author_profile": "https://Stackoverflow.com/users/1292", "pm_score": 0, "selected": false, "text": "[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n" }, { "answer_id": 23824382, "author": "Israel Ocbina", "author_id": 1990838, "author_profile": "https://Stackoverflow.com/users/1990838", "pm_score": 2, "selected": false, "text": "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 > 1)\n {\n return true;\n }\n else\n return false;\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1292/" ]
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": 1777881, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 3, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
51,156
<p>Say I have a list as follows:</p> <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> <p>Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.</p> <p>Cheers!</p>
[ { "answer_id": 13222550, "author": "OZZIE", "author_id": 846348, "author_profile": "https://Stackoverflow.com/users/846348", "pm_score": 2, "selected": false, "text": "last-of-type" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
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": "String.prototype.localeCompare" }, { "answer_id": 51170, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 4, "selected": false, "text": "list.sort(function(item1, item2) {\n var val1 = item1.attr,\n val2 = item2.attr;\n if (val1 == val2) return 0;\n if (val1 > val2) return 1;\n if (val1 < val2) return -1;\n});\n" }, { "answer_id": 14757938, "author": "Manav", "author_id": 141220, "author_profile": "https://Stackoverflow.com/users/141220", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 19573507, "author": "eggmatters", "author_id": 1010444, "author_profile": "https://Stackoverflow.com/users/1010444", "pm_score": 0, "selected": false, "text": "item1.attr - item2.attr\n" }, { "answer_id": 26295229, "author": "Adrien Be", "author_id": 759452, "author_profile": "https://Stackoverflow.com/users/759452", "pm_score": 8, "selected": false, "text": "localeCompare()" }, { "answer_id": 39281302, "author": "Petr Varyagin", "author_id": 5149578, "author_profile": "https://Stackoverflow.com/users/5149578", "pm_score": 1, "selected": false, "text": "list.sort(function(item1, item2){\n return +(item1.attr > item2.attr) || +(item1.attr === item2.attr) - 1;\n}) \n" }, { "answer_id": 40355107, "author": "mpyw", "author_id": 1846562, "author_profile": "https://Stackoverflow.com/users/1846562", "pm_score": 6, "selected": false, "text": "list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))\n" }, { "answer_id": 49989678, "author": "Julio Munoz", "author_id": 4122286, "author_profile": "https://Stackoverflow.com/users/4122286", "pm_score": -1, "selected": false, "text": "<!doctype html>\n<html>\n<body>\n<p id = \"myString\">zyxtspqnmdba</p>\n<p id = \"orderedString\"></p>\n<script>\nvar myString = document.getElementById(\"myString\").innerHTML;\norderString(myString);\nfunction orderString(str) {\n var i = 0;\n var myArray = str.split(\"\");\n while (i < str.length){\n var j = i + 1;\n while (j < str.length) {\n if (myArray[j] < 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</script>\n</body>\n</html>\n" }, { "answer_id": 55153827, "author": "geckos", "author_id": 652528, "author_profile": "https://Stackoverflow.com/users/652528", "pm_score": 4, "selected": false, "text": "(a,b) => (a < b ? -1 : a > b ? 1 : 0)\n" }, { "answer_id": 55590696, "author": "Abdul", "author_id": 9359891, "author_profile": "https://Stackoverflow.com/users/9359891", "pm_score": -1, "selected": false, "text": "var str = ['v','a','da','c','k','l']\nvar b = str.join('').split('').sort().reverse().join('')\nconsole.log(b)\n" }, { "answer_id": 58049712, "author": "Alejadro Xalabarder", "author_id": 1191101, "author_profile": "https://Stackoverflow.com/users/1191101", "pm_score": 5, "selected": false, "text": "list.sort(function (a, b) {\n return a.attr > b.attr ? 1: -1;\n})\n" }, { "answer_id": 64611883, "author": "tash", "author_id": 11932012, "author_profile": "https://Stackoverflow.com/users/11932012", "pm_score": 3, "selected": false, "text": "let products = [\n { name: \"laptop\", price: 800 },\n { name: \"phone\", price:200},\n { name: \"tv\", price: 1200}\n];\nproducts.sort( (a, b) => {\n {let value= a.name - b.name; console.log(value); return value}\n});\n\n> 2 NaN\n" }, { "answer_id": 65979128, "author": "TrickOrTreat", "author_id": 11502061, "author_profile": "https://Stackoverflow.com/users/11502061", "pm_score": 2, "selected": false, "text": "-" }, { "answer_id": 68123055, "author": "deathfry", "author_id": 13029968, "author_profile": "https://Stackoverflow.com/users/13029968", "pm_score": 2, "selected": false, "text": "if (order === 'asc') {\n return a.localeCompare(b);\n}\nreturn b.localeCompare(a);\n" }, { "answer_id": 70430101, "author": "Felix Orinda", "author_id": 13779529, "author_profile": "https://Stackoverflow.com/users/13779529", "pm_score": 3, "selected": false, "text": ".localCompare" }, { "answer_id": 70890849, "author": "xmedeko", "author_id": 254109, "author_profile": "https://Stackoverflow.com/users/254109", "pm_score": 2, "selected": false, "text": "Intl.collator" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
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": "Text Editor > C# > Advanced > Generate XML documentation comments for ///\n" }, { "answer_id": 8235889, "author": "wozza", "author_id": 295301, "author_profile": "https://Stackoverflow.com/users/295301", "pm_score": 3, "selected": false, "text": "#if false\n\n whatever you want here\n and here\n\n#endif\n" }, { "answer_id": 36319097, "author": "Nick", "author_id": 1931573, "author_profile": "https://Stackoverflow.com/users/1931573", "pm_score": 4, "selected": false, "text": "Tools > Options > Text Editor > C# > Advanced" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4458/" ]
51,185
<p>Does javascript use immutable or mutable strings? Do I need a "string builder"?</p>
[ { "answer_id": 51199, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": false, "text": "Array.Join()" }, { "answer_id": 4717855, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 9, "selected": true, "text": "var myString = \"abbdef\"; myString[2] = 'c'" }, { "answer_id": 32074982, "author": "GibboK", "author_id": 379008, "author_profile": "https://Stackoverflow.com/users/379008", "pm_score": 2, "selected": false, "text": "var str= \"Immutable value\"; // it is immutable\n\nvar other= statement.slice(2, 10); // new string\n" }, { "answer_id": 33127871, "author": "zhanziyang", "author_id": 4315171, "author_profile": "https://Stackoverflow.com/users/4315171", "pm_score": 2, "selected": false, "text": "> var str = new String(\"test\")\nundefined\n> str\n[String: 'test']\n> str.newProp = \"some value\"\n'some value'\n> str\n{ [String: 'test'] newProp: 'some value' }\n" }, { "answer_id": 52242541, "author": "Katinka Hesselink", "author_id": 8007395, "author_profile": "https://Stackoverflow.com/users/8007395", "pm_score": 5, "selected": false, "text": "var immutableString = \"Hello\";" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
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": "# Will work (the -> dereferences the reference)\n$row = $records[$index];\nprint \"This will work: \", $row->{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" }, { "answer_id": 51206, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 1, "selected": false, "text": "my %hash = %{@records[$index]};\n" }, { "answer_id": 51209, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 3, "selected": false, "text": "%row = $records[$index];\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
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": 71601, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 2, "selected": false, "text": "map.connect '*', :controller => 'error', :action => 'not_found'\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266/" ]
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": "curses" }, { "answer_id": 51218, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 4, "selected": false, "text": "sys.stdout.write(\"\\r%2d%%\" % percent)\nsys.stdout.flush()\n" }, { "answer_id": 14123416, "author": "MichaelvdNet", "author_id": 1636835, "author_profile": "https://Stackoverflow.com/users/1636835", "pm_score": 1, "selected": false, "text": "url = (<file location>)\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" }, { "answer_id": 28424236, "author": "mafrosis", "author_id": 425050, "author_profile": "https://Stackoverflow.com/users/425050", "pm_score": 0, "selected": false, "text": "urlretrieve" }, { "answer_id": 36022923, "author": "tstone2077", "author_id": 1803741, "author_profile": "https://Stackoverflow.com/users/1803741", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 43475317, "author": "Paal Pedersen", "author_id": 7048431, "author_profile": "https://Stackoverflow.com/users/7048431", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 70750636, "author": "Ashutosh Kumbhar", "author_id": 13547109, "author_profile": "https://Stackoverflow.com/users/13547109", "pm_score": 0, "selected": false, "text": "percent = min(int(count * blockSize * 100 / totalSize), 100)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
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": 51248, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 2, "selected": false, "text": "/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" }, { "answer_id": 51258, "author": "John Virgolino", "author_id": 4246, "author_profile": "https://Stackoverflow.com/users/4246", "pm_score": 4, "selected": false, "text": "\\Repository\n \\ProjectX\n \\Working\n \\Code \n \\Scripts\n \\Notes \n \\Tags\n \\Branches\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
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": 51231, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": true, "text": "[0-9]{2}/[0-9]{2}/[0-9]{4}\n" }, { "answer_id": 51236, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "( (0?1|0?3| <...> |10|11|12) / (0?1| <...> |30|31) |\n 0?2 / (0?1| <...> |28|29) ) \n/ (19|20)[0-9]{2}\n" }, { "answer_id": 60869, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "/x" }, { "answer_id": 60890, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 4, "selected": false, "text": "/\n (?:\n (?<month> (?&mon_29)) [\\/] (?<day>(?&day_29))\n | (?<month> (?&mon_30)) [\\/] (?<day>(?&day_30))\n | (?<month> (?&mon_31)) [\\/] (?<day>(?&day_31))\n )\n [\\/]\n (?<year> [0-9]{4})\n \n (?(DEFINE)\n (?<mon_29> 0?2 )\n (?<mon_30> 0?[469] | (11) )\n (?<mon_31> 0?[13578] | 1[02] )\n\n (?<day_29> 0?[1-9] | [1-2]?[0-9] )\n (?<day_30> 0?[1-9] | [1-2]?[0-9] | 30 )\n (?<day_31> 0?[1-9] | [1-2]?[0-9] | 3[01] )\n )\n/x\n" }, { "answer_id": 60899, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "rx{\n ^\n\n $<month> = (\\d ** 1..2)\n { $<month> <= 12 or fail }\n\n '/'\n\n $<day> = (\\d ** 1..2)\n {\n given( +$<month> ){\n when 1|3|5|7|8|10|12 {\n $<day> <= 31 or fail\n }\n when 4|6|9|11 {\n $<day> <= 30 or fail\n }\n when 2 {\n $<day> <= 29 or fail\n }\n default { fail }\n }\n }\n\n '/'\n\n $<year> = (\\d ** 4)\n\n $\n}\n" }, { "answer_id": 8768241, "author": "Varun Achar", "author_id": 652895, "author_profile": "https://Stackoverflow.com/users/652895", "pm_score": 6, "selected": false, "text": "^(?:(?:(?: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})$" }, { "answer_id": 8949462, "author": "chuck akers", "author_id": 1148562, "author_profile": "https://Stackoverflow.com/users/1148562", "pm_score": 2, "selected": false, "text": "^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" }, { "answer_id": 13533903, "author": "ALinnD", "author_id": 1848216, "author_profile": "https://Stackoverflow.com/users/1848216", "pm_score": 2, "selected": false, "text": " 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' && evalDate[1] != '00' && evalDate[2] != '00'){\n return true;\n }\n }\n" }, { "answer_id": 15968019, "author": "Okipa", "author_id": 2273711, "author_profile": "https://Stackoverflow.com/users/2273711", "pm_score": 3, "selected": false, "text": "(((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" }, { "answer_id": 16285136, "author": "Enrique", "author_id": 2333144, "author_profile": "https://Stackoverflow.com/users/2333144", "pm_score": 2, "selected": false, "text": "^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])\\2(19|20)\\d\\d$\n" }, { "answer_id": 40309602, "author": "Bob", "author_id": 177055, "author_profile": "https://Stackoverflow.com/users/177055", "pm_score": 5, "selected": false, "text": "[^\\w\\d\\r\\n:] \n" }, { "answer_id": 69140085, "author": "Pankkaj", "author_id": 5689392, "author_profile": "https://Stackoverflow.com/users/5689392", "pm_score": 0, "selected": false, "text": "/(([1-9]{1}|0[1-9]|1[0-2])\\/(0[1-9]|[1-9]{1}|[12]\\d|3[01])\\/[12]\\d{3})/" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
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": "import lxml.html\nt = lxml.html.parse(url)\nprint(t.find(\".//title\").text)\n" }, { "answer_id": 51242, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "#!/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(\"https://www.google.com/\")\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" }, { "answer_id": 51263, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 4, "selected": false, "text": "from mechanize import Browser\nbr = Browser()\nbr.open(\"http://www.google.com/\")\nprint br.title()\n" }, { "answer_id": 51550, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "import urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(urllib2.urlopen(\"https://www.google.com\"))\nprint soup.title.string\n" }, { "answer_id": 17123979, "author": "Sai Kiriti Badam", "author_id": 2182787, "author_profile": "https://Stackoverflow.com/users/2182787", "pm_score": 2, "selected": false, "text": "soup.title.string" }, { "answer_id": 36650753, "author": "Finn", "author_id": 4248511, "author_profile": "https://Stackoverflow.com/users/4248511", "pm_score": 4, "selected": false, "text": "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 = \"http://example.com/\"\nhtml_string = str(urlopen(url).read())\n\nparser = TitleParser()\nparser.feed(html_string)\nprint(parser.title) # prints: Example Domain\n" }, { "answer_id": 41958005, "author": "Rahul Chawla", "author_id": 6775799, "author_profile": "https://Stackoverflow.com/users/6775799", "pm_score": 5, "selected": false, "text": ">> hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}\n>>> n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)\n>>> al = n.text\n>>> al[al.find('<title>') + 7 : al.find('</title>')]\nu'Friends (TV Series 1994\\u20132004) - IMDb' \n" }, { "answer_id": 44697410, "author": "Finn", "author_id": 4248511, "author_profile": "https://Stackoverflow.com/users/4248511", "pm_score": 3, "selected": false, "text": "import re\nmatch = re.search('<title>(.*?)</title>', raw_html)\ntitle = match.group(1) if match else 'No title'\n" }, { "answer_id": 47880739, "author": "Ricky Wilson", "author_id": 2433063, "author_profile": "https://Stackoverflow.com/users/2433063", "pm_score": 2, "selected": false, "text": "HTMLParser" }, { "answer_id": 55968979, "author": "markling", "author_id": 2455413, "author_profile": "https://Stackoverflow.com/users/2455413", "pm_score": 0, "selected": false, "text": "import lxml.html.parse\nhtml_doc = lxml.html.parse(some_url)\n\nt = html_doc.xpath('//meta[@property=\"og:title\"]/@content')[0]\n" }, { "answer_id": 56416767, "author": "QHarr", "author_id": 6241235, "author_profile": "https://Stackoverflow.com/users/6241235", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 66234986, "author": "S Habeeb Ullah", "author_id": 12282050, "author_profile": "https://Stackoverflow.com/users/12282050", "pm_score": 2, "selected": false, "text": "urlopen" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
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": "command.AddWithValue(\"@param\", DbNull.Value);\n\nor\n\ncommand.Parameters.Add(\"@param\", <data type>).Value = DBNull.Value;\n" }, { "answer_id": 58277, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 3, "selected": true, "text": "command.Parameters.AddWithValue(\"@parameter\", null);\n" }, { "answer_id": 4249329, "author": "JYelton", "author_id": 161052, "author_profile": "https://Stackoverflow.com/users/161052", "pm_score": 0, "selected": false, "text": "foreach(MySqlParameter param in cmd.Parameters)\n if (param.Value == null) param.Value = DBNull.Value;\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249/" ]
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": "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 > 0\nORDER BY ELAPSED_TIME_MIN DESC\n" }, { "answer_id": 117079, "author": "DL Redden", "author_id": 20610, "author_profile": "https://Stackoverflow.com/users/20610", "pm_score": 3, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
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": "select tabname from tabs \n" }, { "answer_id": 51285, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 4, "selected": true, "text": "select table_name from all_tables where owner='<SCHEMA>';\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
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": 51282, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 5, "selected": false, "text": "ASCII[] attrs1=(ASCII[])\n typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);\n" }, { "answer_id": 276135, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 2, "selected": false, "text": "[Category]" }, { "answer_id": 1152895, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "CustomTypeDescriptorWithResources<T>" }, { "answer_id": 1839628, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 2114049, "author": "Jules", "author_id": 120399, "author_profile": "https://Stackoverflow.com/users/120399", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 10541471, "author": "David MacDermot", "author_id": 1388044, "author_profile": "https://Stackoverflow.com/users/1388044", "pm_score": 1, "selected": false, "text": "SetCategoryLabelViaReflection(MyPropertyGrid.SelectedGridItem.Parent,\n MyPropertyGrid.SelectedGridItem.Parent.Label, \"New Category Label\");\n" }, { "answer_id": 19787957, "author": "mmm", "author_id": 2922477, "author_profile": "https://Stackoverflow.com/users/2922477", "pm_score": -1, "selected": false, "text": "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" }, { "answer_id": 25254059, "author": "Darien Pardinas", "author_id": 1416294, "author_profile": "https://Stackoverflow.com/users/1416294", "pm_score": 2, "selected": false, "text": "System.Reflection.Emit" }, { "answer_id": 41679916, "author": "mbomb007", "author_id": 2415524, "author_profile": "https://Stackoverflow.com/users/2415524", "pm_score": 1, "selected": false, "text": "Property Time As Date\n\n<Display(Name:=\"Month\")>\nReadOnly Property TimeMonthly As Date\n Get\n Return Time\n End Get\nEnd Property\n\n<Display(Name:=\"Quarter\")>\nReadOnly Property TimeQuarterly As Date\n Get\n Return Time\n End Get\nEnd Property\n\n<Display(Name:=\"Year\")>\nReadOnly Property TimeYearly As Date\n Get\n Return Time\n End Get\nEnd Property\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
51,283
<p>How do you get around this Ajax cross site scripting problem on FireFox 3?</p>
[ { "answer_id": 679034, "author": "Jose M Vidal", "author_id": 8484, "author_profile": "https://Stackoverflow.com/users/8484", "pm_score": 3, "selected": false, "text": "try {\n if (netscape.security.PrivilegeManager.enablePrivilege)\n netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n} catch (e) { \n alert(\"Sorry, browser security settings won't let this program run.\"); \n return; \n}\n" }, { "answer_id": 2749743, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 1, "selected": false, "text": "var client = new XMLHttpRequest();\nclient.open(\"HEAD\", my_url, false);\nclient.send(null);\nif(client.readyState != 4 || client.status != 200) //if we failed\n alert(\"can't open web page\");\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5321/" ]
51,296
<p>So I'm running PPP under linux with a cellular modem. The program I'm writing needs to know if the link is active before sending any data.</p> <p>What are my options to check</p> <ul> <li>if the link is available</li> <li>if it routes to a server I control (it doesn't go to the internet as I said earlier)</li> </ul> <p>Also, what is the best way to restart it - I'd like to have program control over when it starts and stops, so I assume an init.d isn't appropriate. Using <code>system()</code> doesn't seem to give a PID, are there other options besides <code>fork()</code> and the gaggle of <code>exec??()</code> calls?</p> <p>C on Linux on ARM (custom distribution using buildroot).</p>
[ { "answer_id": 51313, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "/proc/net/route" }, { "answer_id": 160334, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 4, "selected": true, "text": "ip-up" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
51,311
<p>I am about to start a new project and would like to document its development in a very simple blog.</p> <p>My requirements are:</p> <ul> <li>self-hosted on my Gentoo-based LAMP stack (that seems to rule out blogger)</li> <li>Integration in a django based website (as in www.myproject.com/about, www.myproject.com/blog etc rather than www.myproject.com and a totally different site at blog.myproject.com)</li> <li>very little or no learning curve <i>that's specific to the blog engine</i> (don't want to learn an API just to blog, but having to get deeper into Django to be able to roll my own would be OK) According to the answers so far, there is a chance that this excludes Wordpress</li> </ul> <p>Should I</p> <p>a) install blog engine X (please specify X)</p> <p>b) use django to hand-roll a way to post new entries and a page on my website to display the posts in descending chronological order</p>
[ { "answer_id": 51343, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "grep" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
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": "PATH" }, { "answer_id": 51331, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 6, "selected": true, "text": "File[] roots = File.listRoots();\nfor(int i = 0; i < roots.length ; i++)\n System.out.println(\"Root[\"+i+\"]:\" + roots[i]);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018/" ]
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": "// 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 => x.fooID, x => x.barID);\n\nfrom f in Foo\nwhere fids.HasKey(f.FooId)\nselect f\n" }, { "answer_id": 51346, "author": "NakedBrunch", "author_id": 3742, "author_profile": "https://Stackoverflow.com/users/3742", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 51354, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 51400, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 7, "selected": true, "text": "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;" }, { "answer_id": 51417, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "var q = from t1 in table1\n let t2s = from t2 in table2\n where <Conditions for table2>\n select t2.KeyField\n where t2s.Contains(t1.KeyField)\n select t1;\n" }, { "answer_id": 65218, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "var foos = Foo.Where<br>\n( f => FooBar.Where(fb.BarId == 1000).Select(fb => fb.FooId).Contains(f.FooId));\n" }, { "answer_id": 1088069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var fids = (from fb in FooBar\n where fb.BarID = 1000\n select new { fooID = fb.FooID, barID = fb.BarID })\n .ToDictionary(x => x.fooID, x => x.barID);\n\nfrom f in Foo\nwhere fids.HasKey(f.FooId)\nselect f\n" }, { "answer_id": 1088178, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x => x.fooID, x => x.barID);\n\nfrom f in Foo where fids.HasKey(f.FooId) select f\n" }, { "answer_id": 8968391, "author": "Mox Shah", "author_id": 1107638, "author_profile": "https://Stackoverflow.com/users/1107638", "pm_score": 0, "selected": false, "text": "from f in foo\nwhere f.FooID equals model.FooBar.SingleOrDefault(fBar => fBar.barID = 1000).FooID\nselect new\n{\nf.Columns\n};\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1904/" ]
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": 51368, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": false, "text": "<div>&nbsp;<img src=\"spinner.gif\" id=\"spinnerImg\" style=\"display: none;\" /></div>\n" }, { "answer_id": 52597, "author": "Ed Haber", "author_id": 2926, "author_profile": "https://Stackoverflow.com/users/2926", "pm_score": 6, "selected": true, "text": "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" }, { "answer_id": 55265, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 1, "selected": false, "text": "background-image" }, { "answer_id": 2902494, "author": "4AM", "author_id": 206552, "author_profile": "https://Stackoverflow.com/users/206552", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 3083558, "author": "Christoph", "author_id": 372034, "author_profile": "https://Stackoverflow.com/users/372034", "pm_score": 1, "selected": false, "text": "if(this.width == 0) return false;\n" }, { "answer_id": 5994193, "author": "crispy", "author_id": 231529, "author_profile": "https://Stackoverflow.com/users/231529", "pm_score": 4, "selected": false, "text": "$('img.example').load(function() {\n $('#spinner').fadeOut();\n});\n" }, { "answer_id": 7624654, "author": "BC.", "author_id": 54838, "author_profile": "https://Stackoverflow.com/users/54838", "pm_score": 2, "selected": false, "text": "$('img.example').one('load', function() {\n $('#spinner').remove();\n}).each(function() {\n if(this.complete) {\n $(this).trigger('load');\n }\n});\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3847/" ]
51,363
<p>I've encountered multiple third party .Net component-vendors that use a licensing scheme. On an evaluation copy, the components show up with a nag-screen or watermark or some such indicator. On a licensed machine, a <strong>Licenses.licx</strong> is created - with what appears to be <em>just</em> the assembly full name/identifiers. This file has to be included when the client assembly is built.</p> <ul> <li>How does this model work? Both from component-vendors' and users' perspective.</li> <li>What is the .licx file used for? Should it be checked in? <em>We've had a number of issues with the wrong/right .licx file being checked in and what not</em></li> </ul>
[ { "answer_id": 8333581, "author": "Denis", "author_id": 400589, "author_profile": "https://Stackoverflow.com/users/400589", "pm_score": 3, "selected": false, "text": "TXTextControl.TextControl, TXTextControl, Version=15.0.700.500, Culture=neutral, PublicKeyToken=6b83fe9a75cfb638\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
51,380
<p>The <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInput.html#skipBytes(int)" rel="noreferrer">Sun Documentation for DataInput.skipBytes</a> states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility."</p> <ol> <li><p>Other than reaching end of file, why might <code>skipBytes()</code> not skip the right number of bytes? (The <code>DataInputStream</code> I am using will either be wrapping a <code>FileInputStream</code> or a <code>PipedInputStream</code>.)</p></li> <li><p>If I definitely want to skip n bytes and throw an <code>EOFException</code> if this causes me to go to the end of the file, should I use <code>readFully()</code> and ignore the resulting byte array? Or is there a better way?</p></li> </ol>
[ { "answer_id": 3977877, "author": "Will", "author_id": 328178, "author_profile": "https://Stackoverflow.com/users/328178", "pm_score": 2, "selected": false, "text": "int byteOffsetX = someNumber; //n bytes to skip\nint nSkipped = 0;\n\nnSkipped = in.skipBytes(byteOffsetX);\nwhile (nSkipped < byteOffsetX) {\n nSkipped = nSkipped + in.skipBytes(byteOffsetX - nSkipped);\n}\n" }, { "answer_id": 61251234, "author": "Sergei Tachenov", "author_id": 540312, "author_profile": "https://Stackoverflow.com/users/540312", "pm_score": 0, "selected": false, "text": "readFully()" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728/" ]
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": 51433, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 4, "selected": true, "text": "// 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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
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": 51415, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 6, "selected": true, "text": "methodB(\"argvalue\", **kwargs)\n" }, { "answer_id": 63943, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 2, "selected": false, "text": "import functools\n\ndef foo(arg, **kwargs):\n ...\n\nbar = functools.partial(foo, \"argvalue\")\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
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": "Math::log10(n) \n" }, { "answer_id": 51426, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 4, "selected": true, "text": "Math::log10 (n)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4187/" ]
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": 51514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 51698, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 1, "selected": false, "text": "<asp:Repeater id=\"Repeater1\" runat=\"server\" datasource=\"XMLds\">\n <ItemTemplate>\n <input type=\"text\" value=\"<%# XPath(\"<path to display field>\")%>\" />\n </ItemTemplate>\n</asp:Repeater>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
51,438
<p>How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic &amp; Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.</p> <p>How would you probe the file to determine its actual type (not merely based on the extension)?</p>
[ { "answer_id": 847849, "author": "Joshua Fox", "author_id": 39242, "author_profile": "https://Stackoverflow.com/users/39242", "pm_score": 8, "selected": false, "text": "mimeType = file.toURL().openConnection().getContentType();\n" }, { "answer_id": 1902146, "author": "Adam Hošek", "author_id": 157423, "author_profile": "https://Stackoverflow.com/users/157423", "pm_score": 6, "selected": false, "text": "javax.activation" }, { "answer_id": 6899179, "author": "AlikElzin-kilaka", "author_id": 435605, "author_profile": "https://Stackoverflow.com/users/435605", "pm_score": 4, "selected": false, "text": "FileNameMap fileNameMap = URLConnection.getFileNameMap();\nString mimeType = fileNameMap.getContentTypeFor(\"alert.gif\");\n" }, { "answer_id": 8973468, "author": "Chris Mowforth", "author_id": 468112, "author_profile": "https://Stackoverflow.com/users/468112", "pm_score": 9, "selected": true, "text": "Files.probeContentType(path)" }, { "answer_id": 12534954, "author": "ricardoc", "author_id": 1126309, "author_profile": "https://Stackoverflow.com/users/1126309", "pm_score": 2, "selected": false, "text": "MimeUtil2 mimeUtil = new MimeUtil2();\nmimeUtil.registerMimeDetector(\"eu.medsea.mimeutil.detector.MagicMimeMimeDetector\");\nString mimeType = MimeUtil2.getMostSpecificMimeType(mimeUtil.getMimeTypes(file)).toString();\n" }, { "answer_id": 13889946, "author": "Pawan", "author_id": 1365340, "author_profile": "https://Stackoverflow.com/users/1365340", "pm_score": 5, "selected": false, "text": "android.webkit.MimeTypeMap" }, { "answer_id": 16626396, "author": "koppor", "author_id": 873282, "author_profile": "https://Stackoverflow.com/users/873282", "pm_score": 5, "selected": false, "text": "tika-core" }, { "answer_id": 17302243, "author": "Gray", "author_id": 179850, "author_profile": "https://Stackoverflow.com/users/179850", "pm_score": 4, "selected": false, "text": "URLConnection" }, { "answer_id": 18640199, "author": "Ovidiu Buligan", "author_id": 284314, "author_profile": "https://Stackoverflow.com/users/284314", "pm_score": 4, "selected": false, "text": "public static String getContentType(byte[] data, String name)\n" }, { "answer_id": 27342079, "author": "Abdennour TOUMI", "author_id": 747579, "author_profile": "https://Stackoverflow.com/users/747579", "pm_score": 0, "selected": false, "text": "file --mimetype" }, { "answer_id": 36863737, "author": "Ahmad R. Nazemi", "author_id": 979765, "author_profile": "https://Stackoverflow.com/users/979765", "pm_score": 1, "selected": false, "text": "file.getContentType();" }, { "answer_id": 37461034, "author": "K. Siva Prasad Reddy", "author_id": 755932, "author_profile": "https://Stackoverflow.com/users/755932", "pm_score": 0, "selected": false, "text": "<groupId>eu.medsea.mimeutil</groupId>\n <artifactId>mime-util</artifactId>\n <version>2.1.3</version>\n</dependency>\n\nFile file = new File(\"D:/test.tif\");\nMimeUtil.registerMimeDetector(\"eu.medsea.mimeutil.detector.MagicMimeMimeDetector\");\nCollection<?> mimeTypes = MimeUtil.getMimeTypes(file);\nSystem.out.println(mimeTypes);\n" }, { "answer_id": 40765798, "author": "Vazgen Torosyan", "author_id": 3541666, "author_profile": "https://Stackoverflow.com/users/3541666", "pm_score": 0, "selected": false, "text": "public String getFileContentType(String fileName) {\n String fileType = \"Undetermined\";\n final File file = new File(fileName);\n try\n {\n fileType = Files.probeContentType(file.toPath());\n }\n catch (IOException ioException)\n {\n System.out.println(\n \"ERROR: Unable to determine file type for \" + fileName\n + \" due to exception \" + ioException);\n }\n return fileType;\n}\n" }, { "answer_id": 42229928, "author": "lifeisfoo", "author_id": 3340702, "author_profile": "https://Stackoverflow.com/users/3340702", "pm_score": 6, "selected": false, "text": "File file = new File(\"/path/to/file\");\nTika tika = new Tika();\nSystem.out.println(tika.detect(file));\n" }, { "answer_id": 42418284, "author": "madx", "author_id": 3138238, "author_profile": "https://Stackoverflow.com/users/3138238", "pm_score": 2, "selected": false, "text": "byte[] byteArray = ...\nInputStream is = new BufferedInputStream(new ByteArrayInputStream(byteArray));\nString mimeType = URLConnection.guessContentTypeFromStream(is);\n" }, { "answer_id": 46407125, "author": "nidalpres", "author_id": 2268559, "author_profile": "https://Stackoverflow.com/users/2268559", "pm_score": 3, "selected": false, "text": "new MimetypesFileTypeMap().getContentType( fileName );\n" }, { "answer_id": 48593136, "author": "Cassio Seffrin", "author_id": 2449199, "author_profile": "https://Stackoverflow.com/users/2449199", "pm_score": 2, "selected": false, "text": "import java.io.File;\nimport javax.activation.MimetypesFileTypeMap;\npublic class MimeTest {\n public static void main(String a[]){\n System.out.println(new MimetypesFileTypeMap().getContentType(\n new File(\"/path/filename.txt\")));\n }\n}\n" }, { "answer_id": 56183154, "author": "ganesh vechalapu", "author_id": 10384381, "author_profile": "https://Stackoverflow.com/users/10384381", "pm_score": 0, "selected": false, "text": "File file = new File(PropertiesReader.FILE_PATH);\nMimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();\nString mimeType = fileTypeMap.getContentType(file);\nURLConnection uconnection = file.toURL().openConnection();\nmimeType = uconnection.getContentType();\n" }, { "answer_id": 57298455, "author": "sahmad", "author_id": 3358877, "author_profile": "https://Stackoverflow.com/users/3358877", "pm_score": -1, "selected": false, "text": "import java.io.BufferedReader;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\npublic class MimeFileType {\n\n public static void main(String args[]){\n\n try{\n URL url = new URL (\"https://www.url.com.pdf\");\n\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setDoOutput(true);\n InputStream content = (InputStream)connection.getInputStream();\n connection.getHeaderField(\"Content-Type\");\n\n System.out.println(\"Content-Type \"+ connection.getHeaderField(\"Content-Type\"));\n\n BufferedReader in = new BufferedReader (new InputStreamReader(content));\n\n }catch (Exception e){\n\n }\n }\n}\n" }, { "answer_id": 58796361, "author": "Ramishka Dasanayaka", "author_id": 1166830, "author_profile": "https://Stackoverflow.com/users/1166830", "pm_score": 2, "selected": false, "text": "getServletContext().getMimeType( fileName );\n" }, { "answer_id": 61716681, "author": "Pratik Gaurav", "author_id": 5845739, "author_profile": "https://Stackoverflow.com/users/5845739", "pm_score": 2, "selected": false, "text": "<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-parsers -->\n<dependency>\n <groupId>org.apache.tika</groupId>\n <artifactId>tika-parsers</artifactId>\n <version>1.24</version>\n</dependency>\n\n" }, { "answer_id": 64671146, "author": "Samuel Prevost", "author_id": 5989906, "author_profile": "https://Stackoverflow.com/users/5989906", "pm_score": 2, "selected": false, "text": "video/mp4" }, { "answer_id": 65696342, "author": "Lorenzo", "author_id": 3225638, "author_profile": "https://Stackoverflow.com/users/3225638", "pm_score": 0, "selected": false, "text": "enum" }, { "answer_id": 66944463, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 1, "selected": false, "text": "File" }, { "answer_id": 69737453, "author": "MIsmail", "author_id": 4836726, "author_profile": "https://Stackoverflow.com/users/4836726", "pm_score": 2, "selected": false, "text": "Tika.detect(File)" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
51,462
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c">How to properly clean up Excel interop objects in C#</a> </p> </blockquote> <p>Suppose a ASP.NET web application generates automated Excel Reports on the server. How do we kill a server-side Excel.EXE once the processing is over. I am raising this purposely, because I believe that the Garbage Collecter does not clean the Excel executable even after the Excel file is closed.</p> <p>Any pointers would be helpful?</p>
[ { "answer_id": 51467, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": false, "text": "> taskkill excel.exe\n" }, { "answer_id": 51468, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "excelobject.Quit();" }, { "answer_id": 51489, "author": "Artem Tikhomirov", "author_id": 2313, "author_profile": "https://Stackoverflow.com/users/2313", "pm_score": 0, "selected": false, "text": "Stack<object> comObjectsToRelease = new Stack<object>();\n...\nLog(\"Creating VBProject object.\");\nVBProject vbProject = workbook.VBProject;\ncomObjectsToRelease.Push(vbProject);\n...\nfinally\n{\n if(excel != null)\n {\n Log(\"Quiting Excel.\");\n excel.Quit();\n excel = null;\n }\n while (comObjectsToRelease.Count > 0)\n {\n Log(\"Releasing {0} COM object.\", comObjectsToRelease.GetType().Name);\n Marshal.FinalReleaseComObject(comObjectsToRelease.Pop());\n } \n Log(\"Invoking garbage collection.\");\n GC.Collect();\n}\n" }, { "answer_id": 51600, "author": "Fabian", "author_id": 3862, "author_profile": "https://Stackoverflow.com/users/3862", "pm_score": 0, "selected": false, "text": "System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcesses();\nfor (int i = 0; i < procs.Length; i++)\n{\n if(procs[i].ProcessName == \"EXCEL\")\n {\n procs[i].Kill();\n }\n}\n" }, { "answer_id": 312513, "author": "Vincent Van Den Berghe", "author_id": 39259, "author_profile": "https://Stackoverflow.com/users/39259", "pm_score": 2, "selected": false, "text": "Dim ExcelPID As Integer\nGetWindowThreadProcessId(New IntPtr(Me.ExcelInstance.Hwnd), ExcelPID)\n\nIf ExcelPID > 0 Then\n Dim ExcelProc As Process = Process.GetProcessById(ExcelPID)\n If ExcelProc IsNot Nothing Then ExcelProc.Kill()\nEnd If\n" }, { "answer_id": 1309401, "author": "Anonymous Type", "author_id": 141720, "author_profile": "https://Stackoverflow.com/users/141720", "pm_score": 2, "selected": false, "text": " private void killExcel()\n {\n xlApp.Quit();\n Marshal.ReleaseCOMObject(xlApp);\n if(xlApp != null)\n {\n xlApp = null;\n }\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n }\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
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": "ALTER SEQUENCE serial INCREMENT BY -400;\nSELECT serial.NEXTVAL FROM dual;\nALTER SEQUENCE serial INCREMENT BY 1;\n" }, { "answer_id": 93633, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 8, "selected": true, "text": "tkyte@TKYTE901.US.ORACLE.COM> \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" }, { "answer_id": 1201816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 1885714, "author": "Vipin Vij", "author_id": 229348, "author_profile": "https://Stackoverflow.com/users/229348", "pm_score": 2, "selected": false, "text": "CREATE SEQUENCE TESTSEQ\nINCREMENT BY 1\nMINVALUE 1\nMAXVALUE 500\nNOCACHE\nNOCYCLE\nNOORDER\n" }, { "answer_id": 2866665, "author": "Gina", "author_id": 345203, "author_profile": "https://Stackoverflow.com/users/345203", "pm_score": 6, "selected": false, "text": "--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" }, { "answer_id": 4100161, "author": "Navin", "author_id": 497595, "author_profile": "https://Stackoverflow.com/users/497595", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 6062586, "author": "Allbite", "author_id": 290091, "author_profile": "https://Stackoverflow.com/users/290091", "pm_score": 5, "selected": false, "text": "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 < 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" }, { "answer_id": 14800260, "author": "Chris Saxon", "author_id": 1485955, "author_profile": "https://Stackoverflow.com/users/1485955", "pm_score": 3, "selected": false, "text": "maxvalue" }, { "answer_id": 19673327, "author": "Jon Heller", "author_id": 409172, "author_profile": "https://Stackoverflow.com/users/409172", "pm_score": 6, "selected": false, "text": "alter sequence serial restart start with 1;\n" }, { "answer_id": 22639704, "author": "justincohler", "author_id": 1133062, "author_profile": "https://Stackoverflow.com/users/1133062", "pm_score": 2, "selected": false, "text": "CREATE SEQUENCE test_seq\nMINVALUE 0\nMAXVALUE 100\nSTART WITH 0\nINCREMENT BY 1\nCYCLE;\n" }, { "answer_id": 30652117, "author": "Wendel", "author_id": 2057463, "author_profile": "https://Stackoverflow.com/users/2057463", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 32017463, "author": "Sentinel", "author_id": 4687355, "author_profile": "https://Stackoverflow.com/users/4687355", "pm_score": 2, "selected": false, "text": "next_value" }, { "answer_id": 32836249, "author": "Rakesh", "author_id": 1902897, "author_profile": "https://Stackoverflow.com/users/1902897", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 36924500, "author": "Bruno Freitas", "author_id": 1322804, "author_profile": "https://Stackoverflow.com/users/1322804", "pm_score": 1, "selected": false, "text": "--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 > 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" }, { "answer_id": 41534389, "author": "user46748", "author_id": 5439593, "author_profile": "https://Stackoverflow.com/users/5439593", "pm_score": 1, "selected": false, "text": "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 < 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" }, { "answer_id": 43614527, "author": "Lawrence", "author_id": 1435079, "author_profile": "https://Stackoverflow.com/users/1435079", "pm_score": 2, "selected": false, "text": "drop sequence blah;\ncreate sequence blah \n" }, { "answer_id": 58923589, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": -1, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917/" ]
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": 2567924, "author": "Ari", "author_id": 307804, "author_profile": "https://Stackoverflow.com/users/307804", "pm_score": 7, "selected": true, "text": "<!-- XML -->\n<Director name=\"Spielberg\">\n <Movies>\n <Movie title=\"Jaws\" year=\"1975\"/>\n <Movie title=\"E.T.\" year=\"1982\"/>\n </Movies>\n</Director>\n\n\n# YAML\nDirector: \n name: Spielberg\n Movies:\n - Movie: {title: E.T., year: 1975}\n - Movie: {title: Jaws, year: 1982}\n" }, { "answer_id": 20362887, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 2, "selected": false, "text": "// LES code has no built-in meaning. This just shows what it looks like.\n[DelayedWrite]\nOutput(\n if version > 4.0 {\n $ProjectDir/Src/Foo;\n } else {\n $ProjectDir/Foo;\n }\n);\n" }, { "answer_id": 30144859, "author": "intellimath", "author_id": 4743644, "author_profile": "https://Stackoverflow.com/users/4743644", "pm_score": 2, "selected": false, "text": "<person>\n <name>Frank Martin</name>\n <age>32</age>\n </person>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
51,499
<p>One I am aware of is <a href="http://search.cpan.org/dist/Perl-Critic/" rel="nofollow noreferrer">Perl::Critic</a></p> <p>And my googling has resulted in no results on multiple attempts so far. :-(</p> <p>Does anyone have any recommendations here?</p> <p>Any resources to configure Perl::Critic as per our coding standards and run it on code base would be appreciated.</p>
[ { "answer_id": 62714, "author": "Elliot Shank", "author_id": 6825, "author_profile": "https://Stackoverflow.com/users/6825", "pm_score": 5, "selected": true, "text": "perlcritic --profile-proto" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
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": 51551, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 4, "selected": false, "text": "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" }, { "answer_id": 52111, "author": "elarson", "author_id": 5434, "author_profile": "https://Stackoverflow.com/users/5434", "pm_score": -1, "selected": false, "text": "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" }, { "answer_id": 3054853, "author": "Lloeki", "author_id": 368409, "author_profile": "https://Stackoverflow.com/users/368409", "pm_score": 0, "selected": false, "text": "from __future__ import braces\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342/" ]
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": ">>> import os\n>>> os.path.abspath(\"mydir/myfile.txt\")\n'C:/example/cwd/mydir/myfile.txt'\n" }, { "answer_id": 58417, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 5, "selected": false, "text": "PyPI" }, { "answer_id": 15325066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "unipath" }, { "answer_id": 26539947, "author": "twasbrillig", "author_id": 2213647, "author_profile": "https://Stackoverflow.com/users/2213647", "pm_score": 7, "selected": false, "text": "pathlib" }, { "answer_id": 49639219, "author": "chikwapuro", "author_id": 4954966, "author_profile": "https://Stackoverflow.com/users/4954966", "pm_score": 2, "selected": false, "text": "import os\nupload_folder = os.path.abspath(\"static/img/users\")\n" }, { "answer_id": 51179697, "author": "BND", "author_id": 4088081, "author_profile": "https://Stackoverflow.com/users/4088081", "pm_score": 0, "selected": false, "text": ">>> path=os.popen(\"readlink -f file\").read()\n>>> print path\nabs/path/to/file\n" }, { "answer_id": 53950650, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 5, "selected": false, "text": "pathlib" }, { "answer_id": 54929069, "author": "Lucas Azevedo", "author_id": 4075155, "author_profile": "https://Stackoverflow.com/users/4075155", "pm_score": 4, "selected": false, "text": "subprocess" }, { "answer_id": 55034470, "author": "benjimin", "author_id": 5104777, "author_profile": "https://Stackoverflow.com/users/5104777", "pm_score": 5, "selected": false, "text": "import os\nos.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))\n" }, { "answer_id": 68986016, "author": "Dhiaa Shalabi", "author_id": 11795918, "author_profile": "https://Stackoverflow.com/users/11795918", "pm_score": 3, "selected": false, "text": "from pathlib import Path\n\nfpath = Path('myfile.txt').absolute()\n\nprint(fpath)\n" }, { "answer_id": 71029352, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 2, "selected": false, "text": "mydir/myfile.txt" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
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": "MyList[1] = new MyStruct(\"bob\");\n" }, { "answer_id": 51585, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": false, "text": "Struct obItem = MyList[1];\n" }, { "answer_id": 56895908, "author": "David Klempfner", "author_id": 2063755, "author_profile": "https://Stackoverflow.com/users/2063755", "pm_score": 2, "selected": false, "text": "MyList[1].Name" }, { "answer_id": 68538262, "author": "Bob Bryan", "author_id": 643828, "author_profile": "https://Stackoverflow.com/users/643828", "pm_score": 0, "selected": false, "text": "List<T>" }, { "answer_id": 72507955, "author": "DaemonFire", "author_id": 11522147, "author_profile": "https://Stackoverflow.com/users/11522147", "pm_score": 2, "selected": false, "text": "CollectionsMarshal.AsSpan()" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3989/" ]
51,548
<p>We are migrating our works repository so I want to do a cull of all the unreferenced files that exist in the source tree before moving it into the nice fresh (empty) repository.</p> <p>So far I have gone through by hand and found all the unreferenced files that I know about but I want to find out if I have caught them all. One way would be to manually move the project file by file to a new folder and see what sticks when compiling. That will take all week, so I need an automated tool.</p> <p>What do people suggest?</p> <p>Clarifications:<br> 1) It is C++.<br> 2) The files are mixed. I am looking for files that have been superseded by others but have left to rot in the repository - for instance file_iter.h is not referenced by any other file in the program but remains in the repository just in case someone wants to compile a version from 1996! Now we are moving to a fresh repository we can safely junk all the files that are no longer used.<br> 3) Lint only finds unused includes - not unused files (I have the 7.5 manual in front of me).</p>
[ { "answer_id": 52943, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 1, "selected": false, "text": "-n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
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": 52006, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 5, "selected": true, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5357/" ]
51,561
<p>Typically when writing new code you discover that you are missing a #include because the file doesn't compile. Simple enough, you add the required #include. But later you refactor the code somehow and now a couple of #include directives are no longer needed. How do I discover which ones are no longer needed? </p> <p>Of course I can manually remove some or all #include lines and add them back until the file compiles again, but this isn't really feasible in a large project with thousands of files. Are there any tools available that will help automating task?</p>
[ { "answer_id": 8667351, "author": "Gediminas", "author_id": 1121061, "author_profile": "https://Stackoverflow.com/users/1121061", "pm_score": 0, "selected": false, "text": "Sub RemoveNotUsedIncludes()\n\n'Check if already processed; Exit if so\nActiveDocument.Selection.FindText \"//INCLUDE NOT USED\", dsMatchFromStart\nIF ActiveDocument.Selection <> \"\" THEN\n ActiveDocument.Selection.SetBookmark\n MsgBox \"Already checked\"\n ActiveDocument.Selection.ClearBookmark\n EXIT SUB\nEND IF\n\n'Find first #include; Exit if not found\nActiveDocument.Selection.FindText \"#include\", dsMatchFromStart\nIF ActiveDocument.Selection = \"\" THEN\n MsgBox \"No #include found\"\n EXIT SUB\nEND IF\n\nDim FirstIncludeLine\nFirstIncludeLine = ActiveDocument.Selection.CurrentLine\n\nFOR i=1 TO 200\n\n 'Test build\n ActiveDocument.Selection.SetBookmark\n ActiveDocument.Selection = \"//CHECKING... #include\"\n Build\n ActiveDocument.Undo\n ActiveDocument.Selection.ClearBookmark\n\n IF Errors = 0 THEN\n 'If build failed add comment\n ActiveDocument.Selection.EndOfLine\n ActiveDocument.Selection = \" //INCLUDE NOT USED\"\n END IF\n\n 'Find next include\n ActiveDocument.Selection.EndOfLine\n ActiveDocument.Selection.FindText \"#include\"\n\n 'If all includes tested exit\n IF ActiveDocument.Selection.CurrentLine = FirstIncludeLine THEN EXIT FOR\n\nNEXT\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988/" ]
51,564
<p>How can i format currency related data in a manner that is culture aware in JavaScript?</p>
[ { "answer_id": 14564724, "author": "laktak", "author_id": 52817, "author_profile": "https://Stackoverflow.com/users/52817", "pm_score": 0, "selected": false, "text": "var number = 3500;\nconsole.log(number.toLocaleString()); /* Displays \"3,500\" in English locale */\n" }, { "answer_id": 66497239, "author": "Hans", "author_id": 5103859, "author_profile": "https://Stackoverflow.com/users/5103859", "pm_score": 2, "selected": false, "text": "new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
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": 56933, "author": "Patrick Ritchie", "author_id": 4748, "author_profile": "https://Stackoverflow.com/users/4748", "pm_score": 5, "selected": false, "text": "mimetype = `file -Ib #{path}`.gsub(/\\n/,\"\")\n" }, { "answer_id": 901660, "author": "Martin Carpenter", "author_id": 39443, "author_profile": "https://Stackoverflow.com/users/39443", "pm_score": 6, "selected": false, "text": "libmagic" }, { "answer_id": 4117137, "author": "jamiew", "author_id": 144807, "author_profile": "https://Stackoverflow.com/users/144807", "pm_score": 4, "selected": false, "text": "file --mime -b myvideo.mp4" }, { "answer_id": 16636012, "author": "Alain Beauvois", "author_id": 183331, "author_profile": "https://Stackoverflow.com/users/183331", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 25892795, "author": "spyle", "author_id": 326979, "author_profile": "https://Stackoverflow.com/users/326979", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 50278033, "author": "Paulo Fidalgo", "author_id": 1006863, "author_profile": "https://Stackoverflow.com/users/1006863", "pm_score": 2, "selected": false, "text": "require 'mimemagic'\n\nMimeMagic.by_magic(File.open('tux.jpg')).type # => \"image/jpeg\" \n" }, { "answer_id": 57431940, "author": "Jason Swett", "author_id": 199712, "author_profile": "https://Stackoverflow.com/users/199712", "pm_score": 3, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
51,574
<p>Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried <a href="http://www.jgraph.com/jgraph.html" rel="noreferrer">JGraph</a> and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend?</p> <p>To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API.</p>
[ { "answer_id": 52062, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 5, "selected": false, "text": "UndirectedGraph<String, DefaultEdge> g =\n new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);\n\n String v1 = \"v1\";\n String v2 = \"v2\";\n String v3 = \"v3\";\n String v4 = \"v4\";\n\n // add the vertices\n g.addVertex(v1);\n g.addVertex(v2);\n g.addVertex(v3);\n g.addVertex(v4);\n\n // add edges to create a circuit\n g.addEdge(v1, v2);\n g.addEdge(v2, v3);\n g.addEdge(v3, v4);\n g.addEdge(v4, v1);\n" }, { "answer_id": 16699707, "author": "koppor", "author_id": 873282, "author_profile": "https://Stackoverflow.com/users/873282", "pm_score": 4, "selected": false, "text": "hep.aida.*" }, { "answer_id": 21348339, "author": "Snicolas", "author_id": 693752, "author_profile": "https://Stackoverflow.com/users/693752", "pm_score": 3, "selected": false, "text": "class Node {\n int value;\n List<Node> adj;\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5346/" ]
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": "public class Test<E> { \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" }, { "answer_id": 51615, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 3, "selected": false, "text": "public class Test<E> {\n private Class<E> clazz;\n public Test(Class<E> clazz) {\n this.clazz = clazz;\n }\n public boolean sameClassAs(Object o) {\n return this.clazz.isInstance(o);\n }\n}\n" }, { "answer_id": 51623, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "Test" }, { "answer_id": 765241, "author": "Ayman", "author_id": 77222, "author_profile": "https://Stackoverflow.com/users/77222", "pm_score": -1, "selected": false, "text": "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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
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": 51621, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 4, "selected": true, "text": "interface INamedObject\n{\n string Name {get;}\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2597/" ]
51,589
<p>I'm attempting to make a DTS package to transfer data between two databases on the same server and I'm getting the following errors. Iv read that the Multiple-step OLE DB operation generated error can occur when you are transferring between different database types and there is loss of precision, but this is not that case here. How do I examine the column meta data?</p> <blockquote> <p>Error: 0xC0202009 at Data Flow Task, piTech [183]: An OLE DB error has occurred. Error code: 0x80040E21. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E21 Description: "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".</p> <p>Error: 0xC0202025 at Data Flow Task, piTech [183]: Cannot create an OLE DB accessor. Verify that the column metadata is valid.</p> <p>Error: 0xC004701A at Data Flow Task, DTS.Pipeline: component "piTech" (183) failed the pre-execute phase and returned error code 0xC0202025.</p> </blockquote>
[ { "answer_id": 51606, "author": "Michael Prewecki", "author_id": 4403, "author_profile": "https://Stackoverflow.com/users/4403", "pm_score": 0, "selected": false, "text": "SELECT * FROM INFORMATION_SCHEMA.COLUMNS" }, { "answer_id": 52032, "author": "Michael Prewecki", "author_id": 4403, "author_profile": "https://Stackoverflow.com/users/4403", "pm_score": 2, "selected": false, "text": "SELECT * \nFROM [source].INFORMATION_SCHEMA.COLUMNS src\n INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst \n ON dst.COLUMN_NAME = src.COLUMN_NAME\nWHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH \n" }, { "answer_id": 2628382, "author": "DON", "author_id": 315310, "author_profile": "https://Stackoverflow.com/users/315310", "pm_score": 0, "selected": false, "text": "SELECT * FROM [source].INFORMATION_SCHEMA.COLUMNS src INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst ON dst.COLUMN_NAME = src.COLUMN_NAME WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH" }, { "answer_id": 44671675, "author": "Herve Mutombo", "author_id": 7647224, "author_profile": "https://Stackoverflow.com/users/7647224", "pm_score": 2, "selected": false, "text": "'-2147217887' message 'IDispatch error #3105' source 'Microsoft OLE DB Service Components' description 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.'.\"" }, { "answer_id": 72013121, "author": "Ravi", "author_id": 4478353, "author_profile": "https://Stackoverflow.com/users/4478353", "pm_score": 0, "selected": false, "text": "drop table if exists Employee\nGO\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
51,592
<p>I assume that <code>char* = "string"</code> is the same to <code>char* = new char[6]</code>. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?</p>
[ { "answer_id": 51595, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 1, "selected": false, "text": "const char* c = \"string\";\n" }, { "answer_id": 51598, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 2, "selected": false, "text": "delete []" }, { "answer_id": 51599, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "char* = \"string\"" }, { "answer_id": 51602, "author": "Mike McQuaid", "author_id": 5355, "author_profile": "https://Stackoverflow.com/users/5355", "pm_score": 6, "selected": true, "text": "malloc" }, { "answer_id": 51607, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 0, "selected": false, "text": "char* const sz1 = \"string\"; // embedded string, immutable buffer\nchar* sz2 = new char[10]; // allocated string, should be deleted\n" }, { "answer_id": 51608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "const char* c = \"Hello World!\";\n" }, { "answer_id": 3693866, "author": "Fanatic23", "author_id": 350810, "author_profile": "https://Stackoverflow.com/users/350810", "pm_score": 2, "selected": false, "text": "malloc" }, { "answer_id": 30666555, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "#include <cstdio>\nint main() {\n const char *s = \"abc\";\n char *sn = new char[4];\n sn[3] = '\\0';\n std::printf(\"%s\\n\", s);\n std::printf(\"%s\\n\", sn);\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
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": "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<?xml version=\"1.0\"?>\n<methodResponse>\n <fault>\n <value>\n <struct>\n <member>\n <name>faultCode</name>\n <value><int>4</int></value>\n </member>\n <member>\n <name>faultString</name>\n <value>\n <string>Too many parameters.</string>\n </value>\n </member>\n </struct>\n </value>\n </fault>\n</methodResponse> \n" }, { "answer_id": 56631, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 3, "selected": true, "text": "} 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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/279/" ]
51,619
<p>My server already runs IIS on TCP ports 80 and 443. I want to make a centralized "push/pull" Git repository available to all my team members over the Internet.</p> <p>So I should use HTTP or HTTPS.</p> <p>But I cannot use Apache because of IIS already hooking up listening sockets on ports 80 and 443! Is there any way to publish a Git repository over <em>IIS</em>? Does Git use WebDAV?</p> <p><strong>Update.</strong> It seems that Git HTTP installation is read-only. That's sad. I intended to keep the stable branch on a build server and redeploy using a hook on push. Does anyone see a workaround besides using SVN for that branch?</p>
[ { "answer_id": 73271799, "author": "Luke S", "author_id": 19371365, "author_profile": "https://Stackoverflow.com/users/19371365", "pm_score": 0, "selected": false, "text": "git-http-backend.exe" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ]
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": "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" }, { "answer_id": 51672, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "using System.IO;\n\nDriveInfo[] allDrives = DriveInfo.GetDrives();\nforeach (DriveInfo d in allDrives)\n{\n if (d.IsReady && d.DriveType == DriveType.Removable)\n {\n // This is the drive you want...\n }\n}\n" }, { "answer_id": 51678, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 1, "selected": false, "text": "using System.IO;\n\npublic static class GetDrives\n{\n public static IEnumerable<DriveInfo> GetCDDVDAndRemovableDevices()\n {\n return DriveInfo.GetDrives().\n Where(d => d.DriveType == DriveType.Removable\n && d.DriveType == DriveType.CDRom);\n }\n\n}\n" }, { "answer_id": 12752540, "author": "Searush", "author_id": 1587402, "author_profile": "https://Stackoverflow.com/users/1587402", "pm_score": 0, "selected": false, "text": "'Drive Types <br>\n'Unknown: The type of drive is unknown. <br>\n'NoRootDirectory: The drive does not have a root directory. <br>\n'Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. <br>\n'Fixed: The drive is a fixed disk. <br>\n'Network: The drive is a network drive. <br>\n'CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. <br>\n'Ram: The drive is a RAM disk. <br>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019/" ]
51,653
<p>This is not specific to any language, it´s just about best practices. I am using JPA/Hibernate (but it could be any other ORM solution) and I would like to know how do you guys deal with this situation: Let´s suppose that you have a query returning something that is not represented by any of your domain classes. Do you create a specific class to represent that specific query? Do you return the query in some other kind of object (array, map...) Some other solutions? I would like to know about your experiences and best practices.</p> <p>P.S. Actually I am creating specific objetcs for specific queries.</p>
[ { "answer_id": 51764, "author": "Ivan Bosnic", "author_id": 3221, "author_profile": "https://Stackoverflow.com/users/3221", "pm_score": 0, "selected": false, "text": "USER\nPROJECT\nTASK\nUSER to TASK 1:n\nPROJECT to TASK 1:n\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221/" ]
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": 51934, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 2, "selected": true, "text": "string qs = getSession().getNamedQuery(queryName);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4723/" ]
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": 53170, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 1728106, "author": "Stefan Lundström", "author_id": 78757, "author_profile": "https://Stackoverflow.com/users/78757", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 2372171, "author": "Frankovskyi Bogdan", "author_id": 273689, "author_profile": "https://Stackoverflow.com/users/273689", "pm_score": 6, "selected": false, "text": "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" }, { "answer_id": 19332602, "author": "Erxin", "author_id": 1602830, "author_profile": "https://Stackoverflow.com/users/1602830", "pm_score": 5, "selected": false, "text": "import wmi\n\nc = wmi.WMI ()\nfor d in c.Win32_LogicalDisk():\n print( d.Caption, d.FreeSpace, d.Size, d.DriveType)\n" }, { "answer_id": 29944093, "author": "jhasse", "author_id": 647898, "author_profile": "https://Stackoverflow.com/users/647898", "pm_score": 5, "selected": false, "text": "pip install psutil" }, { "answer_id": 35860878, "author": "Sanjay Bhosale", "author_id": 1074838, "author_profile": "https://Stackoverflow.com/users/1074838", "pm_score": 1, "selected": false, "text": "import win32file \n\ndef get_free_space(dirname):\n secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)\n return secsPerClus * bytesPerSec * nFreeClus\n" }, { "answer_id": 48555562, "author": "Rob Truxal", "author_id": 6293857, "author_profile": "https://Stackoverflow.com/users/6293857", "pm_score": 4, "selected": false, "text": "shutil.disk_usage()" }, { "answer_id": 73115043, "author": "grepit", "author_id": 717630, "author_profile": "https://Stackoverflow.com/users/717630", "pm_score": 0, "selected": false, "text": "import shutil\n\ntotal, used, free = shutil.disk_usage(\"C:/\")\n\nprint(\"Total: %d GiB\" % (total // (2**30)))\nprint(\"Used: %d GiB\" % (used // (2**30)))\nprint(\"Free: %d GiB\" % (free // (2**30)))\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
51,673
<p>The source database is quite large. The target database doesn't grow automatically. They are on different machines.</p> <p>I'm coming from a MS SQL Server, MySQL background and IDS11 seems overly complex (I am sure, with good reason).</p>
[ { "answer_id": 488064, "author": "calvinkrishy", "author_id": 53949, "author_profile": "https://Stackoverflow.com/users/53949", "pm_score": 1, "selected": false, "text": "ontape -s -L 0 -F | rsh secondary_server \"ontape –p\"\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5374/" ]
51,680
<p>Does anyone have a decent algorithm for calculating axis minima and maxima? </p> <p>When creating a chart for a given set of data items, I'd like to be able to give the algorithm: </p> <ul> <li>the maximum (y) value in the set </li> <li>the minimum (y) value in the set </li> <li>the number of tick marks to appear on the axis </li> <li>an optional value that <strong>must</strong> appear as a tick (e.g. zero when showing +ve and -ve values)</li> </ul> <p>The algorithm should return</p> <ul> <li>the largest axis value </li> <li>the smallest axis value (although that could be inferred from the largest, the interval size and the number of ticks)</li> <li>the interval size </li> </ul> <p>The ticks should be at a regular interval should be of a "reasonable" size (e.g. 1, 3, 5, possibly even 2.5, but not any more sig figs). </p> <p>The presence of the optional value will skew this, but without that value the largest item should appear between the top two tick marks, the lowest value between the bottom two. </p> <p>This is a language-agnostic question, but if there's a C#/.NET library around, that would be smashing ;) </p>
[ { "answer_id": 152647, "author": "Bart Read", "author_id": 17786, "author_profile": "https://Stackoverflow.com/users/17786", "pm_score": 2, "selected": false, "text": " private float GetYMarkerSpacing()\n {\n YValueRange range = m_ScrollableCanvas.\n TimelineCanvas.DataModel.CurrentYRange;\n if ( range.RealMinimum == range.RealMaximum )\n {\n return 0;\n }\n\n float absolute = Math.Max(\n Math.Abs( range.RealMinimum ),\n Math.Abs( range.RealMaximum ) ),\n spacing = 0;\n for ( int power = 0; power < 39; ++power )\n {\n float temp = ( float ) Math.Pow( 10, power );\n if ( temp <= absolute )\n {\n spacing = temp;\n }\n else if ( temp / 2 <= absolute )\n {\n spacing = temp / 2;\n break;\n }\n else if ( temp / 2.5 <= absolute )\n {\n spacing = temp / 2.5F;\n break;\n }\n else if ( temp / 4 <= absolute )\n {\n spacing = temp / 4;\n break;\n }\n else if ( temp / 5 <= absolute )\n {\n spacing = temp / 5;\n break;\n }\n else\n {\n break;\n }\n }\n\n return spacing;\n }\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2902/" ]
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": 51743, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 1, "selected": false, "text": "Process.TotalProcessorTime\n" }, { "answer_id": 51789, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": -1, "selected": true, "text": "Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader\n" }, { "answer_id": 51820, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 3, "selected": false, "text": " 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" }, { "answer_id": 15454096, "author": "MD. Mohiuddin Ahmed", "author_id": 1895925, "author_profile": "https://Stackoverflow.com/users/1895925", "pm_score": 0, "selected": false, "text": "public Process getProcessWithMaxCPUUsage()\n {\n const int delay = 500;\n Process[] processes = Process.GetProcesses();\n\n var counters = new List<PerformanceCounter>();\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 < counters.Count; ik++)\n {\n tmpcpu = Math.Round(counters[ik].NextValue(), 1);\n if (tmpcpu > mxcpu)\n {\n mxcpu = tmpcpu;\n mxproc = ik;\n }\n\n }\n return processes[mxproc];\n }\n" }, { "answer_id": 19474434, "author": "Ayan Mullick", "author_id": 2748772, "author_profile": "https://Stackoverflow.com/users/2748772", "pm_score": 1, "selected": false, "text": "Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName,TotalProcessorTime -hidetableheader" }, { "answer_id": 22675167, "author": "Ambrose Leung", "author_id": 2205372, "author_profile": "https://Stackoverflow.com/users/2205372", "pm_score": 1, "selected": false, "text": "$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" }, { "answer_id": 31356645, "author": "Vidar", "author_id": 346645, "author_profile": "https://Stackoverflow.com/users/346645", "pm_score": 2, "selected": false, "text": "Get-Process" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023/" ]
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": 1149048, "author": "Sake", "author_id": 77996, "author_profile": "https://Stackoverflow.com/users/77996", "pm_score": 4, "selected": true, "text": "MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5362/" ]
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": 54341, "author": "geocoin", "author_id": 379, "author_profile": "https://Stackoverflow.com/users/379", "pm_score": 3, "selected": true, "text": "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()->GetWindowRect(&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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379/" ]
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": 51867, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<NewDataSet> \n <Foo> <!-- Foo-Id: 0 -->\n <Bar>abcd</Bar>\n <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 -->\n </Foo>\n <Foo> <!-- Foo-Id: 2 -->\n <Bar>hijk</Bar>\n <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 -->\n </Foo>\n</NewDataSet>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ]
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": 51867, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<NewDataSet> \n <Foo> <!-- Foo-Id: 0 -->\n <Bar>abcd</Bar>\n <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 -->\n </Foo>\n <Foo> <!-- Foo-Id: 2 -->\n <Bar>hijk</Bar>\n <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 -->\n </Foo>\n</NewDataSet>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5389/" ]
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": "var trace = new System.Diagnostics.StackTrace(exception);\n" }, { "answer_id": 51821, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "Logger.Error(\"Danger!!!\", myException );" }, { "answer_id": 1239123, "author": "Lindholm", "author_id": 122253, "author_profile": "https://Stackoverflow.com/users/122253", "pm_score": 5, "selected": false, "text": "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" }, { "answer_id": 6088221, "author": "Hertzel Guinness", "author_id": 293974, "author_profile": "https://Stackoverflow.com/users/293974", "pm_score": 4, "selected": false, "text": "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 < 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" }, { "answer_id": 8779644, "author": "Aftershock", "author_id": 135807, "author_profile": "https://Stackoverflow.com/users/135807", "pm_score": 3, "selected": false, "text": "Console.Write(exception.StackTrace);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
51,771
<p>I have a class with a <code>ToString</code> method that produces XML. I want to unit test it to ensure it is producing valid xml. I have a DTD to validate the XML against. </p> <p><strong>Should I include the DTD as a string within the unit test to avoid a dependency</strong> on it, or is there a smarter way to do this?</p>
[ { "answer_id": 30647084, "author": "R. Oosterholt", "author_id": 1183010, "author_profile": "https://Stackoverflow.com/users/1183010", "pm_score": 0, "selected": false, "text": "XMLUnit.setIgnoreWhitespace(true);\nXMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);\n\nDiff diff = new Diff(expectedDocument, obtainedDocument);\nXMLAssert.assertXMLIdentical(\"xml invalid\", diff, true);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
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": "Dynamic" }, { "answer_id": 67059, "author": "Michael Pliskin", "author_id": 9777, "author_profile": "https://Stackoverflow.com/users/9777", "pm_score": 2, "selected": false, "text": "var d = getDynamic();\nvar a: Array<Dynamic> = d.a;\nfor (t in a) { ... }\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
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": "0: foo\n1: bar\n2: bat\n----\n0 1\n0 2\n1 2\n" }, { "answer_id": 51814, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 51816, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 5, "selected": true, "text": " 1 2 3\n1 #t #f #f\n2 #f #f #t\n3 #f #t #f\n" }, { "answer_id": 51838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<data>\n <node id=\"1\"> \n <link ref=\"2\"/>\n </node>\n <node id=\"2\">\n <link ref=\"3\"/>\n </node>\n <node id=\"3\">\n <link ref=\"1\"/>\n </node>\n</data>\n" }, { "answer_id": 145095, "author": "jbl", "author_id": 2353001, "author_profile": "https://Stackoverflow.com/users/2353001", "pm_score": 1, "selected": false, "text": "[[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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
51,786
<p>How can I generate UML diagrams (especially sequence diagrams) from existing Java code?</p>
[ { "answer_id": 8751193, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 8, "selected": false, "text": "Name: ObjectAid UML Explorer\nLocation: http://www.objectaid.com/update/current\n" }, { "answer_id": 39018106, "author": "juanmf", "author_id": 711855, "author_profile": "https://Stackoverflow.com/users/711855", "pm_score": 3, "selected": false, "text": "@see Main#main()" }, { "answer_id": 60583105, "author": "Happy", "author_id": 2412606, "author_profile": "https://Stackoverflow.com/users/2412606", "pm_score": 1, "selected": false, "text": "UML Sequence Diagram" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772/" ]
51,793
<p>When you send an email using C# and the System.Net.Mail namespace, you can set the "From" and "Sender" properties on the MailMessage object, but neither of these allows you to make the MAIL FROM and the from address that goes into the DATA section different from each other. MAIL FROM gets set to the "From" property value, and if you set "Sender" it only adds another header field in the DATA section. This results in "From X@Y.COM on behalf of A@B.COM", which is not what you want. Am I missing something?</p> <p>The use case is controlling the NDR destination for newsletters, etc., that are sent on behalf of someone else.</p> <p>I am currently using <a href="http://www.aspnetemail.com/" rel="noreferrer">aspNetEmail</a> instead of System.Net.Mail, since it allows me to do this properly (like most other SMTP libraries). With aspNetEmail, this is accomplished using the EmailMessage.ReversePath property.</p>
[ { "answer_id": 51846, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 1, "selected": false, "text": "//create the mail message\n MailMessage mail = new MailMessage();\n\n //set the addresses\n mail.From = new MailAddress(\"me@mycompany.com\");\n mail.To.Add(\"you@yourcompany.com\");\n\n //set the content\n mail.Subject = \"This is an email\";\n mail.Body = \"this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>\";\n mail.IsBodyHtml = true;\n\n //send the message\n SmtpClient smtp = new SmtpClient(\"127.0.0.1\");\n smtp.Send(mail);\n" }, { "answer_id": 652464, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 3, "selected": false, "text": "MailMessage.Sender" }, { "answer_id": 39726489, "author": "Corben Leek", "author_id": 1396350, "author_profile": "https://Stackoverflow.com/users/1396350", "pm_score": 2, "selected": false, "text": "Dim strReplyTo As String = \"email@domain.tld\"\nmessage.ReplyToList.Add(strReplyTo)\nmessage.Headers.Add(\"Return-Path\", strReplyTo)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
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": 51938, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 51970, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 0, "selected": false, "text": "List<Expression> expressions = new List<Expression>(userConditions.Count);\nforeach(Condition c in userConditions)\n{\n expressions.Add(Expression.Eq(c.Field, c.Value));\n}\nSomeTable[] records = SomeTable.Find(expressions);\n" }, { "answer_id": 52100, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "where...\nand (@MyParam5 is null or @MyParam5 = Col5)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197/" ]
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": 51868, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 1, "selected": false, "text": "dir *.txt /b /od > systext.bak \nFOR /F %%i in (systext.bak) do set sysRunCommand=%%i \ncall %sysRunCommand%\ndel systext.bak /Y\n" }, { "answer_id": 51875, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 4, "selected": true, "text": "@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" }, { "answer_id": 51906, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "FOR /F %%I IN ('DIR *.TXT /B /O:-D') DO NOTEPAD %%I & EXIT\n" }, { "answer_id": 51922, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 3, "selected": false, "text": "@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" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
51,884
<p>I recently discussed editors with a co-worker. He uses one of the less popular editors and I use another (I won't say which ones since it's not relevant and I want to avoid an editor flame war). I was saying that I didn't like his editor as much because it doesn't let you do find/replace with regular expressions.</p> <p>He said he's never wanted to do that, which was surprising since it's something I find myself doing all the time. However, off the top of my head I wasn't able to come up with more than one or two examples. Can anyone here offer some examples of times when they've found regex find/replace useful in their editor? Here's what I've been able to come up with since then as examples of things that I've actually had to do:</p> <ol> <li><p>Strip the beginning of a line off of every line in a file that looks like:<br> <code>Line 25634 :</code><br> <code>Line 632157 :</code></p></li> <li><p>Taking a few dozen files with a standard header which is slightly different for each file and stripping the first 19 lines from all of them all at once.</p></li> <li><p>Piping the result of a MySQL select statement into a text file, then removing all of the formatting junk and reformatting it as a Python dictionary for use in a simple script.</p></li> <li><p>In a CSV file with no escaped commas, replace the first character of the 8th column of each row with a capital A.</p></li> <li><p>Given a bunch of GDB stack traces with lines like<br> <code>#3 0x080a6d61 in _mvl_set_req_done (req=0x82624a4, result=27158) at ../../mvl/src/mvl_serv.c:850</code><br> strip out everything from each line except the function names.</p></li> </ol> <p>Does anyone else have any real-life examples? The next time this comes up, I'd like to be more prepared to list good examples of why this feature is useful.</p>
[ { "answer_id": 51911, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "(\\b\\w+\\b)\n" }, { "answer_id": 51918, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 1, "selected": false, "text": "int item1\ndouble item2\n" }, { "answer_id": 288859, "author": "localshred", "author_id": 29690, "author_profile": "https://Stackoverflow.com/users/29690", "pm_score": 2, "selected": false, "text": "...\nfield_1 VARCHAR2(100) NULL,\nfield_2 VARCHAR2(10) NULL,\nfield_3 NUMBER(8) NULL,\nfield_4 VARCHAR2(100) NULL,\n....\n" }, { "answer_id": 1374860, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 1, "selected": false, "text": "/.{20,60} /\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
51,887
<p>I am doing profiling of a C code in Microsoft VS 2005 on a Intel Core-2Duo platform. I measure the time(secs:millisecs) counsumed by my function. But i have some doubts about the accuracy of this measurement as the operating system will not continuously run my application, but instead schedule others apps/services in between the execution of my code.(Although i have no major applications running while i do the profile run, still windows will have lot of code of its own which it will run by preempting my app.). Because of all this i believe the profiling number(time taken by my app to run) is not accurate. </p> <p>So my question is there any way to find out the Operating system overheads, scheduling overhead on a typical windows system(I run Windows XP)e.g. if my applications says it ran for 60 milliseconds, out of that 60 msec, how much time really was used by my app. and how much time it was sitting idle, due to being pre-empted by some other task scheduled by the OS?</p> <p>or </p> <p>Atleast is there any ball-park number to get such OS overhead, based on your experience you came across while doing something similar?</p>
[ { "answer_id": 51936, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 1, "selected": false, "text": "time" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
51,898
<p>In a C# Windows Forms application I want to detect if another instance of the application is already running. If so, activate the main form of the running instance and exit this instance.</p> <p>What is the best way to achieve this?</p>
[ { "answer_id": 51902, "author": "Dean Hill", "author_id": 3106, "author_profile": "https://Stackoverflow.com/users/3106", "pm_score": 3, "selected": false, "text": "// Sets the window to be foreground\n[DllImport(\"User32\")]\nprivate static extern int SetForegroundWindow(IntPtr hwnd);\n\n// Activate or minimize a window\n[DllImportAttribute(\"User32.DLL\")]\nprivate static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\nprivate const int SW_RESTORE = 9;\n\nstatic void Main()\n{\n try\n {\n // If another instance is already running, activate it and exit\n Process currentProc = Process.GetCurrentProcess();\n foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))\n {\n if (proc.Id != currentProc.Id)\n {\n ShowWindow(proc.MainWindowHandle, SW_RESTORE);\n SetForegroundWindow(proc.MainWindowHandle);\n return; // Exit application\n }\n }\n\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new MainForm());\n }\n catch (Exception ex)\n {\n }\n}\n" }, { "answer_id": 801707, "author": "0x49D1", "author_id": 47672, "author_profile": "https://Stackoverflow.com/users/47672", "pm_score": 2, "selected": false, "text": " // Detect existing instances\n string processName = Process.GetCurrentProcess().ProcessName;\n Process[] instances = Process.GetProcessesByName(processName);\n if (instances.Length > 1)\n {\n MessageBox.Show(\"Only one running instance of application is allowed\");\n Process.GetCurrentProcess().Kill();\n return;\n }\n // End of detection\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3106/" ]
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": "contains" }, { "answer_id": 62082, "author": "dahernan", "author_id": 6435, "author_profile": "https://Stackoverflow.com/users/6435", "pm_score": 8, "selected": false, "text": "1 in [1,2,3]\n" }, { "answer_id": 66753, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 8, "selected": true, "text": "[a:1,b:2,c:3].containsValue(3)\n[a:1,b:2,c:3].containsKey('a')\n" }, { "answer_id": 163883, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 3, "selected": false, "text": "ArrayList.metaClass.includes = { i -> i in delegate }\n" }, { "answer_id": 27724859, "author": "Twelve24", "author_id": 1513628, "author_profile": "https://Stackoverflow.com/users/1513628", "pm_score": 2, "selected": false, "text": "import groovy.transform.EqualsAndHashCode\n@EqualsAndHashCode(includes = \"settingNameId, value\")\n" }, { "answer_id": 39934815, "author": "HinataXV", "author_id": 6942112, "author_profile": "https://Stackoverflow.com/users/6942112", "pm_score": 2, "selected": false, "text": "def fruitBag = [\"orange\",\"banana\",\"coconut\"]\ndef fruit = fruitBag.collect{item -> item.contains('n')}\n" }, { "answer_id": 59853867, "author": "MagGGG", "author_id": 1726413, "author_profile": "https://Stackoverflow.com/users/1726413", "pm_score": 3, "selected": false, "text": "def list = ['Grace','Rob','Emmy']\nassert ('Emmy' in list) \n" }, { "answer_id": 62537459, "author": "ninj", "author_id": 7760893, "author_profile": "https://Stackoverflow.com/users/7760893", "pm_score": 0, "selected": false, "text": "boolean bool = List.matches(\"(?i).*SOME STRING HERE.*\")\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5419/" ]
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": "contains" }, { "answer_id": 62082, "author": "dahernan", "author_id": 6435, "author_profile": "https://Stackoverflow.com/users/6435", "pm_score": 8, "selected": false, "text": "1 in [1,2,3]\n" }, { "answer_id": 66753, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 8, "selected": true, "text": "[a:1,b:2,c:3].containsValue(3)\n[a:1,b:2,c:3].containsKey('a')\n" }, { "answer_id": 163883, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 3, "selected": false, "text": "ArrayList.metaClass.includes = { i -> i in delegate }\n" }, { "answer_id": 27724859, "author": "Twelve24", "author_id": 1513628, "author_profile": "https://Stackoverflow.com/users/1513628", "pm_score": 2, "selected": false, "text": "import groovy.transform.EqualsAndHashCode\n@EqualsAndHashCode(includes = \"settingNameId, value\")\n" }, { "answer_id": 39934815, "author": "HinataXV", "author_id": 6942112, "author_profile": "https://Stackoverflow.com/users/6942112", "pm_score": 2, "selected": false, "text": "def fruitBag = [\"orange\",\"banana\",\"coconut\"]\ndef fruit = fruitBag.collect{item -> item.contains('n')}\n" }, { "answer_id": 59853867, "author": "MagGGG", "author_id": 1726413, "author_profile": "https://Stackoverflow.com/users/1726413", "pm_score": 3, "selected": false, "text": "def list = ['Grace','Rob','Emmy']\nassert ('Emmy' in list) \n" }, { "answer_id": 62537459, "author": "ninj", "author_id": 7760893, "author_profile": "https://Stackoverflow.com/users/7760893", "pm_score": 0, "selected": false, "text": "boolean bool = List.matches(\"(?i).*SOME STRING HERE.*\")\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
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": 51953, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 3, "selected": false, "text": "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" }, { "answer_id": 91978, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 3, "selected": true, "text": "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" }, { "answer_id": 17247251, "author": "Richard Knott", "author_id": 2510909, "author_profile": "https://Stackoverflow.com/users/2510909", "pm_score": 2, "selected": false, "text": "Sheets(\"information\").Select\nRange(\"C3\").Select\nActiveCell.FormulaR1C1 = \"Updating Records\"\nApplication.ScreenUpdating = False\nApplication.Wait Now + TimeValue(\"00:00:02\")\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ]
51,948
<p>I'm building a C++/MFC program in a multilingual environment. I have one main (national) language and three international languages. Every time I add a feature to the program I have to keep the international languages up-to-date with the national one. The resource editor in Visual Studio is not very helpful because I frequently end up leaving a string, dialog box, etc., untranslated.</p> <p>I wonder if you guys know of a program that can edit resource (.rc) files and</p> <ul> <li>Build a file that includes only the strings to be translated and their respective IDs and accepts the same (or similar) file in another language (this would be helpful since usually the translation is done by someone else), or</li> <li>Handle the translations itself, allowing to view the same string in different languages at the same time.</li> </ul>
[ { "answer_id": 65313, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "for i in $trfile\ndo\n key=`echo $i | sed 's/^\\(.*\\)=\\(.*\\)$/\\1/g'`\n value=`echo $i | sed 's/^\\(.*\\)=\\(.*\\)$/\\2/g'`\n url=\"http://babelfish.altavista.com/tr?doit=done&intl=1&tt=urltext&lp=$langs&btnTrTxt=Translate&trtext=$value\"\n wget -O foo.html -A \"$agent\" \"$url\" *&> /dev/null\n tx=`grep \"<td bgcolor=white class=s><div style=padding:10px;>\" foo.html`\n tx=`echo $tx | iconv -f latin1 -t utf-8 | sed 's/<td bgcolor=white class=s><div style=padding:10px;>\\(.*\\)<\\/div><\\/td>/\\1/g'`\n echo $key=$tx\ndone\n\nrm foo.html\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4880/" ]
51,949
<p>Given a string <code>"filename.conf"</code>, how to I verify the extension part?</p> <p>I need a cross platform solution.</p>
[ { "answer_id": 51965, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 2, "selected": false, "text": "_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w\n" }, { "answer_id": 51992, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 5, "selected": false, "text": "std::string filename(\"filename.conf\");\nstd::string::size_type idx;\n\nidx = filename.rfind('.');\n\nif(idx != std::string::npos)\n{\n std::string extension = filename.substr(idx+1);\n}\nelse\n{\n // No extension found\n}\n" }, { "answer_id": 51999, "author": "brian newman", "author_id": 3210, "author_profile": "https://Stackoverflow.com/users/3210", "pm_score": 7, "selected": false, "text": "#include <iostream>\n#include <string>\n\nint main()\n{\n std::string fn = \"filename.conf\";\n if(fn.substr(fn.find_last_of(\".\") + 1) == \"conf\") {\n std::cout << \"Yes...\" << std::endl;\n } else {\n std::cout << \"No...\" << std::endl;\n }\n}\n" }, { "answer_id": 52009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "c:\\.directoryname\\file.name.with.too.many.dots.ext" }, { "answer_id": 4505931, "author": "graphitemaster", "author_id": 550752, "author_profile": "https://Stackoverflow.com/users/550752", "pm_score": 4, "selected": false, "text": "std::string GetFileExtension(const std::string& FileName)\n{\n if(FileName.find_last_of(\".\") != std::string::npos)\n return FileName.substr(FileName.find_last_of(\".\")+1);\n return \"\";\n}\n" }, { "answer_id": 4777391, "author": "delaccount992", "author_id": 554785, "author_profile": "https://Stackoverflow.com/users/554785", "pm_score": 2, "selected": false, "text": "#include <ctype.h>\n#include <string.h>\n\nint main()\n{\n char filename[] = \"apples.bmp\";\n char extension[] = \".jpeg\";\n\n if(compare_extension(filename, extension) == true)\n {\n // .....\n } else {\n // .....\n }\n\n return 0;\n}\n\nbool compare_extension(char *filename, char *extension)\n{\n /* Sanity checks */\n\n if(filename == NULL || extension == NULL)\n return false;\n\n if(strlen(filename) == 0 || strlen(extension) == 0)\n return false;\n\n if(strchr(filename, '.') == NULL || strchr(extension, '.') == NULL)\n return false;\n\n /* Iterate backwards through respective strings and compare each char one at a time */\n\n for(int i = 0; i < strlen(filename); i++)\n {\n if(tolower(filename[strlen(filename) - i - 1]) == tolower(extension[strlen(extension) - i - 1]))\n {\n if(i == strlen(extension) - 1)\n return true;\n } else\n break;\n }\n\n return false;\n}\n" }, { "answer_id": 6821673, "author": "Leopoldo Sanczyk", "author_id": 862270, "author_profile": "https://Stackoverflow.com/users/862270", "pm_score": 2, "selected": false, "text": " System::String^ GetFileExtension(System::String^ FileName)\n {\n int Ext=FileName->LastIndexOf('.');\n if( Ext != -1 )\n return FileName->Substring(Ext+1);\n return \"\";\n }\n" }, { "answer_id": 10547576, "author": "Maadiah", "author_id": 853569, "author_profile": "https://Stackoverflow.com/users/853569", "pm_score": 0, "selected": false, "text": "char* lastSlash;\nlastSlash = strstr(filename, \".\");\n" }, { "answer_id": 12792194, "author": "peter karasev", "author_id": 221802, "author_profile": "https://Stackoverflow.com/users/221802", "pm_score": 5, "selected": false, "text": "#include <boost/filesystem.hpp>\nusing std::string;\nstring texture = foo->GetTextureFilename();\nstring file_extension = boost::filesystem::extension(texture);\ncout << \"attempting load texture named \" << texture\n << \" whose extensions seems to be \" \n << file_extension << endl;\n// Use JPEG or PNG loader function, or report invalid extension\n" }, { "answer_id": 13430107, "author": "serengeor", "author_id": 1636911, "author_profile": "https://Stackoverflow.com/users/1636911", "pm_score": 3, "selected": false, "text": "bool getFileExtension(const char * dir_separator, const std::string & file, std::string & ext)\n{\n std::size_t ext_pos = file.rfind(\".\");\n std::size_t dir_pos = file.rfind(dir_separator);\n\n if(ext_pos>dir_pos+1)\n {\n ext.append(file.begin()+ext_pos,file.end());\n return true;\n }\n\n return false;\n}\n" }, { "answer_id": 17944468, "author": "Qiu", "author_id": 2572285, "author_profile": "https://Stackoverflow.com/users/2572285", "pm_score": 3, "selected": false, "text": "char* ext;\next = strrchr(filename,'.') \n" }, { "answer_id": 18100652, "author": "Quest", "author_id": 2660282, "author_profile": "https://Stackoverflow.com/users/2660282", "pm_score": 0, "selected": false, "text": " char *ExtractFileExt(char *FileName)\n {\n std::string s = FileName;\n int Len = s.length();\n while(TRUE)\n {\n if(FileName[Len] != '.')\n Len--;\n else\n {\n char *Ext = new char[s.length()-Len+1];\n for(int a=0; a<s.length()-Len; a++)\n Ext[a] = FileName[s.length()-(s.length()-Len)+a];\n Ext[s.length()-Len] = '\\0';\n return Ext;\n }\n }\n }\n" }, { "answer_id": 23346778, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 1, "selected": false, "text": "wstring get_file_extension( wstring filename )\n{\n size_t last_dot_offset = filename.rfind(L'.');\n // This assumes your directory separators are either \\ or /\n size_t last_dirsep_offset = max( filename.rfind(L'\\\\'), filename.rfind(L'/') );\n\n // no dot = no extension\n if( last_dot_offset == wstring::npos )\n return L\"\";\n\n // directory separator after last dot = extension of directory, not file.\n // for example, given C:\\temp.old\\file_that_has_no_extension we should return \"\" not \"old\"\n if( (last_dirsep_offset != wstring::npos) && (last_dirsep_offset > last_dot_offset) )\n return L\"\";\n\n return filename.substr( last_dot_offset + 1 );\n}\n" }, { "answer_id": 26822961, "author": "AMCoded", "author_id": 1146097, "author_profile": "https://Stackoverflow.com/users/1146097", "pm_score": 2, "selected": false, "text": " const char filename1 = {\"C:\\\\init.d\\\\doc\"}; // => No extention\n const char filename2 = {\"..\\\\doc\"}; //relative path name => No extention\n const char filename3 = {\"\"}; //emputy file name => No extention\n const char filename4 = {\"testing\"}; //only single name => No extention\n const char filename5 = {\"tested/k.doc\"}; // normal file name => doc\n const char filename6 = {\"..\"}; // parent folder => No extention\n const char filename7 = {\"/\"}; // linux root => No extention\n const char filename8 = {\"/bin/test.d.config/lx.wize.str\"}; // ordinary path! => str\n" }, { "answer_id": 30005179, "author": "manlio", "author_id": 3235496, "author_profile": "https://Stackoverflow.com/users/3235496", "pm_score": 2, "selected": false, "text": "boost::filesystem::extension" }, { "answer_id": 32104638, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 1, "selected": false, "text": "std::string fileExtension(std::string file){\n\n std::size_t found = file.find_last_of(\".\");\n return file.substr(found+1);\n\n}\n\nstd::string fileNameWithoutExtension(std::string file){\n\n std::size_t found = file.find_last_of(\".\");\n return file.substr(0,found); \n}\n" }, { "answer_id": 32105859, "author": "Mike Finch", "author_id": 4577467, "author_profile": "https://Stackoverflow.com/users/4577467", "pm_score": 2, "selected": false, "text": "std::string" }, { "answer_id": 33729793, "author": "Darien Pardinas", "author_id": 1416294, "author_profile": "https://Stackoverflow.com/users/1416294", "pm_score": -1, "selected": false, "text": "#include <Poco/Path.h>\n\n...\n\nstd::string fileExt = Poco::Path(\"/home/user/myFile.abc\").getExtension(); // == \"abc\"\n" }, { "answer_id": 34332887, "author": "Yuval", "author_id": 4498825, "author_profile": "https://Stackoverflow.com/users/4498825", "pm_score": -1, "selected": false, "text": "long get_extension_index(string path, char dir_separator = '/') {\n // Look from the end for the first '.',\n // but give up if finding a dir separator char first\n for(long i = path.length() - 1; i >= 0; --i) {\n if(path[i] == '.') {\n return i;\n }\n if(path[i] == dir_separator) {\n return -1;\n }\n }\n return -1;\n}\n" }, { "answer_id": 34906539, "author": "Pabitra Dash", "author_id": 2776571, "author_profile": "https://Stackoverflow.com/users/2776571", "pm_score": -1, "selected": false, "text": "#include <Shlwapi.h>\nbool A2iAWrapperUtility::isValidImageFile(string imageFile)\n{\n char * pStrExtension = ::PathFindExtension(imageFile.c_str());\n\n if (pStrExtension != NULL && strcmp(pStrExtension, \".tif\") == 0)\n {\n return true;\n }\n\n return false;\n}\n" }, { "answer_id": 50881646, "author": "Roi Danton", "author_id": 4566599, "author_profile": "https://Stackoverflow.com/users/4566599", "pm_score": 5, "selected": false, "text": "std::filesystem::path::extension" }, { "answer_id": 59923175, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 2, "selected": false, "text": "#include<stdio.h>\n\nvoid GetFileExtension(const char* file_name) {\n\n int ext = '.';\n const char* extension = NULL;\n extension = strrchr(file_name, ext);\n\n if(extension == NULL){\n printf(\"Invalid extension encountered\\n\");\n return;\n }\n\n printf(\"File extension is %s\\n\", extension);\n}\n\nint main()\n{\n const char* file_name = \"c:\\\\.directoryname\\\\file.name.with.too.many.dots.ext\";\n GetFileExtension(file_name);\n return 0;\n}\n" }, { "answer_id": 71945957, "author": "Jason C", "author_id": 616460, "author_profile": "https://Stackoverflow.com/users/616460", "pm_score": 0, "selected": false, "text": "std::filesystem" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
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": "[assembly:InternalsVisibleToAttribute(\"UnitTestAssemblyName\")]\n" }, { "answer_id": 51986, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 4, "selected": false, "text": "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"BoardEx_BusinessObjects.Tests, \n PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb3a2d8 etc etc\")]\n" }, { "answer_id": 71554850, "author": "paraJdox1", "author_id": 11565087, "author_profile": "https://Stackoverflow.com/users/11565087", "pm_score": 0, "selected": false, "text": "using System.Runtime.CompilerServices;\n\n[assembly: InternalsVisibleTo(\"App.Infrastructure.UnitTests\")]\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" }, { "answer_id": 72820728, "author": "kewur", "author_id": 4695519, "author_profile": "https://Stackoverflow.com/users/4695519", "pm_score": 0, "selected": false, "text": "<!-- Make internals available for Unit Testing -->\n<ItemGroup>\n <AssemblyAttribute Include=\"System.Runtime.CompilerServices.InternalsVisibleTo\">\n <_Parameter1>Myproject.Tests</_Parameter1>\n </AssemblyAttribute>\n</ItemGroup>\n<!-- End Unit test Internals -->\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
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": "Response.Redirect(String.Format(\"nextpage.aspx?{0}\", Request.QueryString.ToString().Replace(\"foo\", \"mangledfoo\")));\n" }, { "answer_id": 51995, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 4, "selected": true, "text": "string url = Request.RawUrl;\n\nNameValueCollection params = Request.QueryString;\nfor (int i=0; i<params.Count; i++)\n{\n if (params[i].GetKey(i).ToLower() == \"foo\")\n {\n url += string.Concat((i==0 ? \"?\" : \"&\"), params[i].GetKey(i), \"=\", params.Get(i));\n }\n}\nResponse.Redirect(url);\n" }, { "answer_id": 52128, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 0, "selected": false, "text": "Response.Redirect(String.Format(\"nextpage.aspx?{0}\", Regex.Replace(Request.QueryString.ToString(), \"&terms=.*&\", \"&\"));\n" }, { "answer_id": 1632995, "author": "Ziad", "author_id": 144227, "author_profile": "https://Stackoverflow.com/users/144227", "pm_score": 3, "selected": false, "text": " 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 < nvc.Count; i++)\n url += string.Format(\"{0}{1}={2}\", (i == 0 ? \"?\" : \"&\"), nvc.Keys[i], nvc[i]);\n\n Response.Redirect(url);\n" }, { "answer_id": 8169154, "author": "alex1kirch", "author_id": 991442, "author_profile": "https://Stackoverflow.com/users/991442", "pm_score": 2, "selected": false, "text": "HttpUtility.ParseQueryString(Request.Url.Query)" }, { "answer_id": 8919043, "author": "Answer", "author_id": 1157369, "author_profile": "https://Stackoverflow.com/users/1157369", "pm_score": 0, "selected": false, "text": "Request.Url.GetLeftPart(UriPartial.Path)" }, { "answer_id": 10412157, "author": "Chris", "author_id": 94278, "author_profile": "https://Stackoverflow.com/users/94278", "pm_score": 0, "selected": false, "text": "var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());\nqs.Remove(\"item\");\nConsole.WriteLine(qs.ToString());\n" }, { "answer_id": 16279198, "author": "biofractal", "author_id": 776476, "author_profile": "https://Stackoverflow.com/users/776476", "pm_score": 0, "selected": false, "text": "Request.QueryString" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
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": "SELECT is_read_committed_snapshot_on FROM sys.databases \nWHERE name= 'YourDatabase'\n" }, { "answer_id": 20942633, "author": "user3164106", "author_id": 3164106, "author_profile": "https://Stackoverflow.com/users/3164106", "pm_score": 0, "selected": false, "text": "DBCC USEROPTIONS" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/51969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5217/" ]
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": "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" }, { "answer_id": 52014, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 5, "selected": false, "text": "rev = StringReverse(originalString)\nreturn ( rev == originalString );\n" }, { "answer_id": 52015, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 2, "selected": false, "text": "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 <= s.Length - 1; i++)\n {\n char c = s[i];\n\n if (allowedChars.IndexOf(c) > -1)\n {\n compareString += c;\n }\n }\n\n\n for (int i = compareString.Length - 1; i >= 0; i--)\n {\n char c = compareString[i];\n rev += c;\n }\n\n return rev.Equals(compareString, \n StringComparison.CurrentCultureIgnoreCase);\n}\n" }, { "answer_id": 52021, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "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] <> s[j] then\n Exit;\n Dec(j);\n end;\n Result := true;\nend;\n" }, { "answer_id": 52023, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": ">>> def is_palindrome(s):\n... return s == s[::-1]\n" }, { "answer_id": 52028, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "def IsPalindromeString(n):\n myLen = len(n)\n i = 0\n while i <= myLen/2:\n if n[i] != n[myLen-1-i]:\n return False\n i += 1\n return True\n" }, { "answer_id": 52031, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 5, "selected": false, "text": "@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" }, { "answer_id": 52034, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "var str = \"a b a\";\nvar test = Enumerable.SequenceEqual(str.ToCharArray(), \n str.ToCharArray().Reverse());\n" }, { "answer_id": 52036, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 52038, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "boolean IsPalindrome(string s) {\n for (int i = 0; i < s.Length / 2; i++)\n {\n if (s[i] != s[s.Length - 1 - i]) return false;\n }\n return true;\n}\n" }, { "answer_id": 52040, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "private static bool Pal(string s) {\n for (int i = 0; i < s.Length; i++) {\n if (s[i] != s[s.Length - 1 - i]) {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 52041, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 2, "selected": false, "text": "private static boolean doPal(String test) {\n for(int i = 0; i < 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" }, { "answer_id": 52048, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 4, "selected": false, "text": "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 < (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" }, { "answer_id": 52051, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": false, "text": "$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" }, { "answer_id": 52053, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 3, "selected": false, "text": "bool palindrome(std::string const& s) \n{ \n return std::equal(s.begin(), s.end(), s.rbegin()); \n} \n" }, { "answer_id": 52057, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "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] <> 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" }, { "answer_id": 52063, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "static bool IsPalindrome(this string input)\n{\n char[] letters = input.ToUpper().ToCharArray();\n\n int i = 0;\n while( i < letters.Length / 2 )\n if( letters[i] != letters[letters.Length - ++i] )\n return false;\n\n return true;\n}\n" }, { "answer_id": 52064, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 52138, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "=" }, { "answer_id": 52153, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "" }, { "answer_id": 52328, "author": "kranzky", "author_id": 5442, "author_profile": "https://Stackoverflow.com/users/5442", "pm_score": 1, "selected": false, "text": "def isPalindrome( string )\n ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse\nend\n" }, { "answer_id": 52660, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "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 > leftIndex)\n {\n if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])\n {\n return false;\n }\n leftIndex++;\n rightIndex--;\n }\n return true;\n}\n" }, { "answer_id": 52749, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": false, "text": "class String\n def palindrome?\n (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse\n end\nend\n" }, { "answer_id": 53009, "author": "Hostile", "author_id": 5323, "author_profile": "https://Stackoverflow.com/users/5323", "pm_score": 3, "selected": false, "text": "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 < length && d >= 0 ; i++ , d--)\n {\n while(cf= toupper(s[i]), (cf < 'A' || cf >'Z') && i < length-1)i++;\n while(cb= toupper(s[d]), (cb < 'A' || cb >'Z') && d > 0 )d--;\n if(cf != cb && cf >= 'A' && cf <= 'Z' && cb >= 'A' && cb <='Z')\n return false;\n }\n return true;\n}\n" }, { "answer_id": 53055, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 53148, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "public boolean isPalindrome(String phrase) {\n phrase = phrase.toLowerCase().replaceAll(\"[^a-z]\", \"\");\n return StringUtils.reverse(phrase).equals(phrase);\n}\n" }, { "answer_id": 53215, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "i = 0; j = length-1;\n\nwhile( true ) {\n while( i < j && !is_alphanumeric( str[i] ) ) i++;\n while( i < j && !is_alphanumeric( str[j] ) ) j--;\n\n if( i >= j ) return true;\n\n if( tolower(string[i]) != tolower(string[j]) ) return false;\n i++; j--;\n}\n" }, { "answer_id": 53505, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 1, "selected": false, "text": "isPalindrome :: String -> Bool\nisPalindrome n = (n == reverse n)\n" }, { "answer_id": 56204, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 1, "selected": false, "text": "if s == s[::-1]: return True\n" }, { "answer_id": 58575, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "let rec palindrome s =\n s = (tailrev s)\n" }, { "answer_id": 59364, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 2, "selected": false, "text": "(defun palindrome(x) (string= x (reverse x)))\n" }, { "answer_id": 63366, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 0, "selected": false, "text": "boolean IsPalindrome(string s) {\nreturn s = s.Reverse();\n}\n" }, { "answer_id": 68900, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 77508, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "int IsPalindrome (char *s)\n{\n char*a,*b,c=0;\n for(a=b=s;a<=b;c=(c?c==1?c=(*a&~32)-65>25u?*++a,1:2:c==2?(*--b&~32)-65<26u?3:2:c==3?(*b-65&~32)-(*a-65&~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));\n return s!=0;\n}\n" }, { "answer_id": 77620, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "bool isPalindromeA(const std::string & p_strText)\n{\n if(p_strText.length() < 2) return true ;\n const char * pStart = p_strText.c_str() ; \n const char * pEnd = pStart + p_strText.length() - 1 ; \n\n for(; pStart < pEnd; ++pStart, --pEnd)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n }\n\n return true ;\n}\n" }, { "answer_id": 228706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "bool is_palindrome(const string &s)\n{\n return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());\n}\n" }, { "answer_id": 228707, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 0, "selected": false, "text": " 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) && clean.Length > 1)\n {\n isPalindrome = true;\n for (int i = 0, count = clean.Length / 2 + 1; i < 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 > 1)\n {\n isPalindrome = true;\n for (int i = 0, count = words.Length / 2 + 1; i < 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" }, { "answer_id": 263449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 277727, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::string a = \"god\";\nstd::string b = \"lol\";\n\nstd::cout << (std::string(a.rbegin(), a.rend()) == a) << \" \" \n << (std::string(b.rbegin(), b.rend()) == b);\n" }, { "answer_id": 371523, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 0, "selected": false, "text": "set l = index of left most character in word\nset r = index of right most character in word\n\nloop while(l < 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" }, { "answer_id": 430317, "author": "Vadim Ferderer", "author_id": 24142, "author_profile": "https://Stackoverflow.com/users/24142", "pm_score": 0, "selected": false, "text": "template< typename Iterator >\nbool is_palindrome( Iterator first, Iterator last, std::locale const& loc = std::locale(\"\") )\n{\n if ( first == last )\n return true;\n\n for( --last; first < last; ++first, --last )\n {\n while( ! std::isalnum( *first, loc ) && first < last )\n ++first;\n while( ! std::isalnum( *last, loc ) && first < last )\n --last;\n if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )\n return false;\n }\n return true;\n}\n" }, { "answer_id": 430363, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "reverse" }, { "answer_id": 430393, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 430444, "author": "BBetances", "author_id": 53599, "author_profile": "https://Stackoverflow.com/users/53599", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 430483, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 0, "selected": false, "text": "int IsPalindrome (const char *str)\n{\n const unsigned len = strlen(str);\n const char *end = &str[len-1];\n while (str < end)\n if (*str++ != *end--)\n return 0;\n return 1;\n}\n" }, { "answer_id": 659809, "author": "Ascalonian", "author_id": 65230, "author_profile": "https://Stackoverflow.com/users/65230", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 1039466, "author": "patjbs", "author_id": 79256, "author_profile": "https://Stackoverflow.com/users/79256", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Tests if a string is a palindrome\n /// </summary>\n public static bool IsPalindrome(this String str)\n {\n if (str.Length == 0) return false;\n int index = 0;\n while (index < str.Length / 2)\n if (str[index] != str[str.Length - ++index]) return false;\n\n return true;\n }\n" }, { "answer_id": 1039549, "author": "Matchu", "author_id": 107415, "author_profile": "https://Stackoverflow.com/users/107415", "pm_score": 2, "selected": false, "text": "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? # => false\nputs 'aba'.is_palindrome? # => true\nputs \"Madam, I'm Adam.\".is_palindrome? # => true\n" }, { "answer_id": 1078441, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 0, "selected": false, "text": "def pal(s:String) = Symbol(s) equals Symbol(s.reverse)\n" }, { "answer_id": 1115333, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 1, "selected": false, "text": "palindrome(B, R) :-\npalindrome(B, R, []).\n\npalindrome([], R, R).\npalindrome([X|B], [X|R], T) :-\npalindrome(B, R, [X|T]).\n" }, { "answer_id": 2049311, "author": "Pritam Karmakar", "author_id": 208513, "author_profile": "https://Stackoverflow.com/users/208513", "pm_score": 0, "selected": false, "text": " public bool IsPalindrome(string s)\n {\n string formattedString = s.Replace(\" \", string.Empty).ToLower();\n for (int i = 0; i < formattedString.Length / 2; i++)\n {\n if (formattedString[i] != formattedString[formattedString.Length - 1 - i])\n return false;\n }\n return true;\n }\n" }, { "answer_id": 2751730, "author": "rockvista", "author_id": 1996230, "author_profile": "https://Stackoverflow.com/users/1996230", "pm_score": 0, "selected": false, "text": "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 <= len / 2; i++, j--)\n {\n while (i<j && MyString[i] == ' ' || MyString[i] == ',')\n i++;\n\n while(j>i && MyString[j] == ' ' || MyString[j] == ',')\n j--;\n\n if ((i == len / 2) && (i == j))\n return true;\n\n first = MyString[i] >= 97 && MyString[i] <= 122 ? MyString[i] - 32 : MyString[i];\n second = MyString[j] >= 97 && MyString[j] <= 122 ? MyString[j] - 32 : MyString[j];\n\n if (first != second)\n return false;\n }\n\n return true;\n }\n" }, { "answer_id": 5130209, "author": "Micke", "author_id": 635969, "author_profile": "https://Stackoverflow.com/users/635969", "pm_score": 0, "selected": false, "text": "function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {\n $returnstrrev = \"returnstrrevverrtsnruter\";\n $verrtsnruter = $functionnoitcnuf;\n return (strrev ($verrtsnruter) == $functionnoitcnuf) ; \n}\n" }, { "answer_id": 5494118, "author": "Bubbles", "author_id": 631423, "author_profile": "https://Stackoverflow.com/users/631423", "pm_score": 0, "selected": false, "text": "public static boolean isPalindrome( String str ) {\n int count = str.length() ;\n int i, j = count - 1 ;\n for ( i = 0 ; i < 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" }, { "answer_id": 8181718, "author": "Ram", "author_id": 50418, "author_profile": "https://Stackoverflow.com/users/50418", "pm_score": 1, "selected": false, "text": "palindrome(L) -> palindrome(L,[]).\n\npalindrome([],_) -> false;\npalindrome([_|[]],[]) -> true;\npalindrome([_|L],L) -> true;\npalindrome(L,L) -> true;\npalindrome([H|T], Acc) -> palindrome(T, [H|Acc]).\n" }, { "answer_id": 8672758, "author": "Mushimo", "author_id": 456206, "author_profile": "https://Stackoverflow.com/users/456206", "pm_score": 1, "selected": false, "text": "function palindrome(s) {\n var l = 0, r = s.length - 1;\n while (l < r) if (s.charAt(left++) !== s.charAt(r--)) return false;\n return true\n}\n" }, { "answer_id": 8733562, "author": "Justin", "author_id": 950252, "author_profile": "https://Stackoverflow.com/users/950252", "pm_score": 0, "selected": false, "text": "public static final boolean isPalindromeWithAdditionalStorage(String string) {\n String reversed = new StringBuilder(string).reverse().toString();\n return string.equals(reversed);\n}\n" }, { "answer_id": 9305682, "author": "melsk", "author_id": 809694, "author_profile": "https://Stackoverflow.com/users/809694", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 14772912, "author": "user2039532", "author_id": 2039532, "author_profile": "https://Stackoverflow.com/users/2039532", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 14906430, "author": "Rhys Ulerich", "author_id": 103640, "author_profile": "https://Stackoverflow.com/users/103640", "pm_score": 0, "selected": false, "text": "const" }, { "answer_id": 19893643, "author": "Adrian Bratu", "author_id": 1161008, "author_profile": "https://Stackoverflow.com/users/1161008", "pm_score": 0, "selected": false, "text": "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 < ss.length()/2; i++) \n if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i))\n return false;\nreturn true;\n" }, { "answer_id": 23638086, "author": "sam_rox", "author_id": 3577754, "author_profile": "https://Stackoverflow.com/users/3577754", "pm_score": 0, "selected": false, "text": "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<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<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<len;r++){\n palArray[r]=pal.charAt(r);\n }\n ArrayStack palStack=new ArrayStack(len);\n for(int k=0;k<palArray.length;k++){\n palStack.push(palArray[k]);\n }\n for (int i=0;i<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" }, { "answer_id": 24759363, "author": "Pavan tej", "author_id": 2063399, "author_profile": "https://Stackoverflow.com/users/2063399", "pm_score": 0, "selected": false, "text": "//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<=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" }, { "answer_id": 29174567, "author": "arsho", "author_id": 3129414, "author_profile": "https://Stackoverflow.com/users/3129414", "pm_score": 1, "selected": false, "text": "function checkPalindrome(line){\n reverse_line=line.split(\"\").reverse().join(\"\");\n return line==reverse_line;\n }\nalert(\"checkPalindrome(radar): \"+checkPalindrome(\"radar\"));" }, { "answer_id": 29587590, "author": "Confuse", "author_id": 3886922, "author_profile": "https://Stackoverflow.com/users/3886922", "pm_score": 0, "selected": false, "text": "public static boolean isPalindrome(String str) {\n return str.equals(new StringBuilder(str).reverse().toString());\n}\n" }, { "answer_id": 32550261, "author": "mockee", "author_id": 468712, "author_profile": "https://Stackoverflow.com/users/468712", "pm_score": 0, "selected": false, "text": "// JavaScript Version.\nfunction isPalindrome(str) { \n str = str.replace(/[^a-zA-Z]/g, '')\n return str.split('').reverse().join('').toUpperCase() === str.toUpperCase() \n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
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": "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" }, { "answer_id": 52014, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 5, "selected": false, "text": "rev = StringReverse(originalString)\nreturn ( rev == originalString );\n" }, { "answer_id": 52015, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 2, "selected": false, "text": "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 <= s.Length - 1; i++)\n {\n char c = s[i];\n\n if (allowedChars.IndexOf(c) > -1)\n {\n compareString += c;\n }\n }\n\n\n for (int i = compareString.Length - 1; i >= 0; i--)\n {\n char c = compareString[i];\n rev += c;\n }\n\n return rev.Equals(compareString, \n StringComparison.CurrentCultureIgnoreCase);\n}\n" }, { "answer_id": 52021, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "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] <> s[j] then\n Exit;\n Dec(j);\n end;\n Result := true;\nend;\n" }, { "answer_id": 52023, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": ">>> def is_palindrome(s):\n... return s == s[::-1]\n" }, { "answer_id": 52028, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "def IsPalindromeString(n):\n myLen = len(n)\n i = 0\n while i <= myLen/2:\n if n[i] != n[myLen-1-i]:\n return False\n i += 1\n return True\n" }, { "answer_id": 52031, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 5, "selected": false, "text": "@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" }, { "answer_id": 52034, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "var str = \"a b a\";\nvar test = Enumerable.SequenceEqual(str.ToCharArray(), \n str.ToCharArray().Reverse());\n" }, { "answer_id": 52036, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 52038, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "boolean IsPalindrome(string s) {\n for (int i = 0; i < s.Length / 2; i++)\n {\n if (s[i] != s[s.Length - 1 - i]) return false;\n }\n return true;\n}\n" }, { "answer_id": 52040, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "private static bool Pal(string s) {\n for (int i = 0; i < s.Length; i++) {\n if (s[i] != s[s.Length - 1 - i]) {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 52041, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 2, "selected": false, "text": "private static boolean doPal(String test) {\n for(int i = 0; i < 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" }, { "answer_id": 52048, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 4, "selected": false, "text": "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 < (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" }, { "answer_id": 52051, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": false, "text": "$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" }, { "answer_id": 52053, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 3, "selected": false, "text": "bool palindrome(std::string const& s) \n{ \n return std::equal(s.begin(), s.end(), s.rbegin()); \n} \n" }, { "answer_id": 52057, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "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] <> 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" }, { "answer_id": 52063, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "static bool IsPalindrome(this string input)\n{\n char[] letters = input.ToUpper().ToCharArray();\n\n int i = 0;\n while( i < letters.Length / 2 )\n if( letters[i] != letters[letters.Length - ++i] )\n return false;\n\n return true;\n}\n" }, { "answer_id": 52064, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 52138, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "=" }, { "answer_id": 52153, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "" }, { "answer_id": 52328, "author": "kranzky", "author_id": 5442, "author_profile": "https://Stackoverflow.com/users/5442", "pm_score": 1, "selected": false, "text": "def isPalindrome( string )\n ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse\nend\n" }, { "answer_id": 52660, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "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 > leftIndex)\n {\n if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])\n {\n return false;\n }\n leftIndex++;\n rightIndex--;\n }\n return true;\n}\n" }, { "answer_id": 52749, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": false, "text": "class String\n def palindrome?\n (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse\n end\nend\n" }, { "answer_id": 53009, "author": "Hostile", "author_id": 5323, "author_profile": "https://Stackoverflow.com/users/5323", "pm_score": 3, "selected": false, "text": "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 < length && d >= 0 ; i++ , d--)\n {\n while(cf= toupper(s[i]), (cf < 'A' || cf >'Z') && i < length-1)i++;\n while(cb= toupper(s[d]), (cb < 'A' || cb >'Z') && d > 0 )d--;\n if(cf != cb && cf >= 'A' && cf <= 'Z' && cb >= 'A' && cb <='Z')\n return false;\n }\n return true;\n}\n" }, { "answer_id": 53055, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 53148, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "public boolean isPalindrome(String phrase) {\n phrase = phrase.toLowerCase().replaceAll(\"[^a-z]\", \"\");\n return StringUtils.reverse(phrase).equals(phrase);\n}\n" }, { "answer_id": 53215, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "i = 0; j = length-1;\n\nwhile( true ) {\n while( i < j && !is_alphanumeric( str[i] ) ) i++;\n while( i < j && !is_alphanumeric( str[j] ) ) j--;\n\n if( i >= j ) return true;\n\n if( tolower(string[i]) != tolower(string[j]) ) return false;\n i++; j--;\n}\n" }, { "answer_id": 53505, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 1, "selected": false, "text": "isPalindrome :: String -> Bool\nisPalindrome n = (n == reverse n)\n" }, { "answer_id": 56204, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 1, "selected": false, "text": "if s == s[::-1]: return True\n" }, { "answer_id": 58575, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "let rec palindrome s =\n s = (tailrev s)\n" }, { "answer_id": 59364, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 2, "selected": false, "text": "(defun palindrome(x) (string= x (reverse x)))\n" }, { "answer_id": 63366, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 0, "selected": false, "text": "boolean IsPalindrome(string s) {\nreturn s = s.Reverse();\n}\n" }, { "answer_id": 68900, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "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" }, { "answer_id": 77508, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "int IsPalindrome (char *s)\n{\n char*a,*b,c=0;\n for(a=b=s;a<=b;c=(c?c==1?c=(*a&~32)-65>25u?*++a,1:2:c==2?(*--b&~32)-65<26u?3:2:c==3?(*b-65&~32)-(*a-65&~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));\n return s!=0;\n}\n" }, { "answer_id": 77620, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "bool isPalindromeA(const std::string & p_strText)\n{\n if(p_strText.length() < 2) return true ;\n const char * pStart = p_strText.c_str() ; \n const char * pEnd = pStart + p_strText.length() - 1 ; \n\n for(; pStart < pEnd; ++pStart, --pEnd)\n {\n if(*pStart != *pEnd)\n {\n return false ;\n }\n }\n\n return true ;\n}\n" }, { "answer_id": 228706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "bool is_palindrome(const string &s)\n{\n return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());\n}\n" }, { "answer_id": 228707, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 0, "selected": false, "text": " 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) && clean.Length > 1)\n {\n isPalindrome = true;\n for (int i = 0, count = clean.Length / 2 + 1; i < 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 > 1)\n {\n isPalindrome = true;\n for (int i = 0, count = words.Length / 2 + 1; i < 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" }, { "answer_id": 263449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 277727, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::string a = \"god\";\nstd::string b = \"lol\";\n\nstd::cout << (std::string(a.rbegin(), a.rend()) == a) << \" \" \n << (std::string(b.rbegin(), b.rend()) == b);\n" }, { "answer_id": 371523, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 0, "selected": false, "text": "set l = index of left most character in word\nset r = index of right most character in word\n\nloop while(l < 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" }, { "answer_id": 430317, "author": "Vadim Ferderer", "author_id": 24142, "author_profile": "https://Stackoverflow.com/users/24142", "pm_score": 0, "selected": false, "text": "template< typename Iterator >\nbool is_palindrome( Iterator first, Iterator last, std::locale const& loc = std::locale(\"\") )\n{\n if ( first == last )\n return true;\n\n for( --last; first < last; ++first, --last )\n {\n while( ! std::isalnum( *first, loc ) && first < last )\n ++first;\n while( ! std::isalnum( *last, loc ) && first < last )\n --last;\n if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )\n return false;\n }\n return true;\n}\n" }, { "answer_id": 430363, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "reverse" }, { "answer_id": 430393, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 430444, "author": "BBetances", "author_id": 53599, "author_profile": "https://Stackoverflow.com/users/53599", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 430483, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 0, "selected": false, "text": "int IsPalindrome (const char *str)\n{\n const unsigned len = strlen(str);\n const char *end = &str[len-1];\n while (str < end)\n if (*str++ != *end--)\n return 0;\n return 1;\n}\n" }, { "answer_id": 659809, "author": "Ascalonian", "author_id": 65230, "author_profile": "https://Stackoverflow.com/users/65230", "pm_score": 2, "selected": false, "text": "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" }, { "answer_id": 1039466, "author": "patjbs", "author_id": 79256, "author_profile": "https://Stackoverflow.com/users/79256", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Tests if a string is a palindrome\n /// </summary>\n public static bool IsPalindrome(this String str)\n {\n if (str.Length == 0) return false;\n int index = 0;\n while (index < str.Length / 2)\n if (str[index] != str[str.Length - ++index]) return false;\n\n return true;\n }\n" }, { "answer_id": 1039549, "author": "Matchu", "author_id": 107415, "author_profile": "https://Stackoverflow.com/users/107415", "pm_score": 2, "selected": false, "text": "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? # => false\nputs 'aba'.is_palindrome? # => true\nputs \"Madam, I'm Adam.\".is_palindrome? # => true\n" }, { "answer_id": 1078441, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 0, "selected": false, "text": "def pal(s:String) = Symbol(s) equals Symbol(s.reverse)\n" }, { "answer_id": 1115333, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 1, "selected": false, "text": "palindrome(B, R) :-\npalindrome(B, R, []).\n\npalindrome([], R, R).\npalindrome([X|B], [X|R], T) :-\npalindrome(B, R, [X|T]).\n" }, { "answer_id": 2049311, "author": "Pritam Karmakar", "author_id": 208513, "author_profile": "https://Stackoverflow.com/users/208513", "pm_score": 0, "selected": false, "text": " public bool IsPalindrome(string s)\n {\n string formattedString = s.Replace(\" \", string.Empty).ToLower();\n for (int i = 0; i < formattedString.Length / 2; i++)\n {\n if (formattedString[i] != formattedString[formattedString.Length - 1 - i])\n return false;\n }\n return true;\n }\n" }, { "answer_id": 2751730, "author": "rockvista", "author_id": 1996230, "author_profile": "https://Stackoverflow.com/users/1996230", "pm_score": 0, "selected": false, "text": "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 <= len / 2; i++, j--)\n {\n while (i<j && MyString[i] == ' ' || MyString[i] == ',')\n i++;\n\n while(j>i && MyString[j] == ' ' || MyString[j] == ',')\n j--;\n\n if ((i == len / 2) && (i == j))\n return true;\n\n first = MyString[i] >= 97 && MyString[i] <= 122 ? MyString[i] - 32 : MyString[i];\n second = MyString[j] >= 97 && MyString[j] <= 122 ? MyString[j] - 32 : MyString[j];\n\n if (first != second)\n return false;\n }\n\n return true;\n }\n" }, { "answer_id": 5130209, "author": "Micke", "author_id": 635969, "author_profile": "https://Stackoverflow.com/users/635969", "pm_score": 0, "selected": false, "text": "function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {\n $returnstrrev = \"returnstrrevverrtsnruter\";\n $verrtsnruter = $functionnoitcnuf;\n return (strrev ($verrtsnruter) == $functionnoitcnuf) ; \n}\n" }, { "answer_id": 5494118, "author": "Bubbles", "author_id": 631423, "author_profile": "https://Stackoverflow.com/users/631423", "pm_score": 0, "selected": false, "text": "public static boolean isPalindrome( String str ) {\n int count = str.length() ;\n int i, j = count - 1 ;\n for ( i = 0 ; i < 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" }, { "answer_id": 8181718, "author": "Ram", "author_id": 50418, "author_profile": "https://Stackoverflow.com/users/50418", "pm_score": 1, "selected": false, "text": "palindrome(L) -> palindrome(L,[]).\n\npalindrome([],_) -> false;\npalindrome([_|[]],[]) -> true;\npalindrome([_|L],L) -> true;\npalindrome(L,L) -> true;\npalindrome([H|T], Acc) -> palindrome(T, [H|Acc]).\n" }, { "answer_id": 8672758, "author": "Mushimo", "author_id": 456206, "author_profile": "https://Stackoverflow.com/users/456206", "pm_score": 1, "selected": false, "text": "function palindrome(s) {\n var l = 0, r = s.length - 1;\n while (l < r) if (s.charAt(left++) !== s.charAt(r--)) return false;\n return true\n}\n" }, { "answer_id": 8733562, "author": "Justin", "author_id": 950252, "author_profile": "https://Stackoverflow.com/users/950252", "pm_score": 0, "selected": false, "text": "public static final boolean isPalindromeWithAdditionalStorage(String string) {\n String reversed = new StringBuilder(string).reverse().toString();\n return string.equals(reversed);\n}\n" }, { "answer_id": 9305682, "author": "melsk", "author_id": 809694, "author_profile": "https://Stackoverflow.com/users/809694", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 14772912, "author": "user2039532", "author_id": 2039532, "author_profile": "https://Stackoverflow.com/users/2039532", "pm_score": 0, "selected": false, "text": "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" }, { "answer_id": 14906430, "author": "Rhys Ulerich", "author_id": 103640, "author_profile": "https://Stackoverflow.com/users/103640", "pm_score": 0, "selected": false, "text": "const" }, { "answer_id": 19893643, "author": "Adrian Bratu", "author_id": 1161008, "author_profile": "https://Stackoverflow.com/users/1161008", "pm_score": 0, "selected": false, "text": "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 < ss.length()/2; i++) \n if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i))\n return false;\nreturn true;\n" }, { "answer_id": 23638086, "author": "sam_rox", "author_id": 3577754, "author_profile": "https://Stackoverflow.com/users/3577754", "pm_score": 0, "selected": false, "text": "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<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<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<len;r++){\n palArray[r]=pal.charAt(r);\n }\n ArrayStack palStack=new ArrayStack(len);\n for(int k=0;k<palArray.length;k++){\n palStack.push(palArray[k]);\n }\n for (int i=0;i<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" }, { "answer_id": 24759363, "author": "Pavan tej", "author_id": 2063399, "author_profile": "https://Stackoverflow.com/users/2063399", "pm_score": 0, "selected": false, "text": "//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<=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" }, { "answer_id": 29174567, "author": "arsho", "author_id": 3129414, "author_profile": "https://Stackoverflow.com/users/3129414", "pm_score": 1, "selected": false, "text": "function checkPalindrome(line){\n reverse_line=line.split(\"\").reverse().join(\"\");\n return line==reverse_line;\n }\nalert(\"checkPalindrome(radar): \"+checkPalindrome(\"radar\"));" }, { "answer_id": 29587590, "author": "Confuse", "author_id": 3886922, "author_profile": "https://Stackoverflow.com/users/3886922", "pm_score": 0, "selected": false, "text": "public static boolean isPalindrome(String str) {\n return str.equals(new StringBuilder(str).reverse().toString());\n}\n" }, { "answer_id": 32550261, "author": "mockee", "author_id": 468712, "author_profile": "https://Stackoverflow.com/users/468712", "pm_score": 0, "selected": false, "text": "// JavaScript Version.\nfunction isPalindrome(str) { \n str = str.replace(/[^a-zA-Z]/g, '')\n return str.split('').reverse().join('').toUpperCase() === str.toUpperCase() \n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
52,046
<p>Since CS3 doesn't have a web service component, as previous versions had, is there a good, feature-complete, AS3-only (no Flex dependencies) library for accessing web services with AS3?</p>
[ { "answer_id": 430835, "author": "typeoneerror", "author_id": 53653, "author_profile": "https://Stackoverflow.com/users/53653", "pm_score": 0, "selected": false, "text": "urlRequest.requestHeaders.push(new URLRequestHeader(\"Content-Type\", \"application/soap+xml\"));" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5421/" ]
52,066
<p>Is there an existing solution to create a regular expressions dynamically out of a given date-time format pattern? The supported date-time format pattern does not matter (Joda <code>DateTimeFormat</code>, <code>java.text.SimpleDateTimeFormat</code> or others).</p> <p>As a specific example, for a given date-time format like <code>dd/MM/yyyy hh:mm</code>, it should generate the corresponding regular expression to match the date-times within the specified formats.</p>
[ { "answer_id": 52149, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 0, "selected": false, "text": "SimpleDateFormat" }, { "answer_id": 179044, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 1, "selected": false, "text": "\\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}\\b\n\n10/07/2008 \n10.07.2008\n1-01/2008\n10/07/08 \n10.07.2008\n1-01/08\n" }, { "answer_id": 181870, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "\"HH\"" }, { "answer_id": 41363354, "author": "Ankit Arjaria", "author_id": 1779787, "author_profile": "https://Stackoverflow.com/users/1779787", "pm_score": 0, "selected": false, "text": "var dateFormat = \"DD-MM-YYYY\";\nvar order = [];\n var position = {\"D\":dateFormat.search('D'),\"M\":dateFormat.search('M'),\"Y\":dateFormat.search('Y')};\n var count = {\"D\":dateFormat.split(\"D\").length - 1,\"M\":dateFormat.split(\"M\").length - 1,\"Y\":dateFormat.split(\"Y\").length - 1};\n var seprator ='';\n for(var i=0; i<dateFormat.length; i++){\n if([\"Y\",\"M\",\"D\"].indexOf(dateFormat.charAt(i))<0){\n seprator = dateFormat.charAt(i);\n }else{\n if(order.indexOf(dateFormat.charAt(i)) <0 ){\n order.push(dateFormat.charAt(i));\n }\n }\n }\n var regEx = \"^\";\n $(order).each(function(ok,ov){\n regEx += '(\\d{'+count[ov]+'})'+seprator;\n });\n regEx = regEx.substr(0,(regEx.length)-1);\n regEx +=\"$\";\n var re = new RegExp(regEx);\n console.log(re);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3993/" ]
52,071
<p>Does anyone know of any good library that abstracts the problem of path manipulation in a nice way? I'd like to be able to combine and parse paths with arbitrary separators ('/' or ':' for example) without reinventing the wheel.</p> <p>It's a shame that <code>System.IO.Path</code> isn't more reusable.</p> <p>Thanks</p>
[ { "answer_id": 1637777, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 0, "selected": false, "text": "System.IO.Path" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380/" ]
52,072
<p>I am trying to code TDD style in PHP and one of my biggest stumbling blocks (other than lack of a decent IDE) is that I have to make my own hacked together IoC container just to inject all my mock objects properly.</p> <p>Has anyone used an Ioc container in PHP? All I've been able to find is <a href="http://www.phpclasses.org/browse/package/3382.html" rel="nofollow noreferrer">PHP IOC on the ever-annoying phpclasses.org</a> and it seems to have almost no documentation and not much of a following.</p>
[ { "answer_id": 13340863, "author": "Matthieu Napoli", "author_id": 245552, "author_profile": "https://Stackoverflow.com/users/245552", "pm_score": 2, "selected": false, "text": "class Foo {\n /**\n * @Inject\n * @var Bar\n */\n private $bar;\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
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": "for (var = startvalue; var <= endvalue; var = var + increment) {\n // code to be executed\n}\n" }, { "answer_id": 52088, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 1, "selected": false, "text": "for(var i = 0; i< nodes.length; i++){\n var node = nodes[i];\n alert(node);\n}\n" }, { "answer_id": 52101, "author": "georgebrock", "author_id": 5168, "author_profile": "https://Stackoverflow.com/users/5168", "pm_score": 6, "selected": true, "text": "for (i = startValue; i <= 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 <= endValue is true\n}\n" }, { "answer_id": 32355895, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "while() ..." } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]