qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
368,006 | <p>I want my background worker to add items to a list box, it appears to do so when debugging but the listbox doesn't show the values. I suspect this is something to do with adding items whilst inside the background worker thread, do I need to add these to an array and then populate the list box from the array during <code>backgroundWorker1_RunWorkerCompleted</code>?</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 368009,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 1,
"selected": false,
"text": "Form.Invoke\n Form.BeginInvoke\n .Refresh()"
},
{
"answer_id": 368017,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 3,
"selected": false,
"text": " public Form1()\n {\n InitializeComponent();\n\n BackgroundWorker bw = new BackgroundWorker();\n bw.WorkerReportsProgress = true;\n bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);\n bw.DoWork += new DoWorkEventHandler(bw_DoWork);\n bw.RunWorkerAsync();\n }\n\n void bw_DoWork(object sender, DoWorkEventArgs e)\n {\n for (int i = 0; i < 10; i++)\n {\n ((BackgroundWorker)sender).ReportProgress(0, i.ToString());\n }\n }\n\n void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)\n {\n listBox1.Items.Add((string)e.UserState);\n }\n"
},
{
"answer_id": 368026,
"author": "Gonzalo Quero",
"author_id": 40996,
"author_profile": "https://Stackoverflow.com/users/40996",
"pm_score": 4,
"selected": false,
"text": "private void AddToListBox(object oo)\n{\n Invoke(new MethodInvoker(\n delegate { listBox.Items.Add(oo); }\n ));\n}\n"
},
{
"answer_id": 429316,
"author": "Marcus Erickson",
"author_id": 38373,
"author_profile": "https://Stackoverflow.com/users/38373",
"pm_score": 1,
"selected": false,
"text": " delegate void AddListItemDelegate(string name,object otherInfoNeeded);\n\n private void\n AddListItem(\n string name,\n object otherInfoNeeded\n )\n {\n if (InvokeRequired)\n {\n BeginInvoke(new AddListItemDelegate(AddListItem), name, otherInfoNeeded\n return;\n }\n\n ... add code to create list box item and insert in list here ...\n }\n"
},
{
"answer_id": 3599212,
"author": "Abdul Hameed",
"author_id": 434806,
"author_profile": "https://Stackoverflow.com/users/434806",
"pm_score": 0,
"selected": false,
"text": "Application.Doevents()"
},
{
"answer_id": 47340681,
"author": "Michael Smith",
"author_id": 5592243,
"author_profile": "https://Stackoverflow.com/users/5592243",
"pm_score": 1,
"selected": false,
"text": "BackgroundWorker_DoWork(object sender, DoWorkArgs e)\n{\n Dataset dataset2 = dataset1;\n foreach(DataGridViewRow row in GridView)\n {\n //do some work\n dataset2.Main.AddMainRow(values to add);\n dataset2.AcceptChanges();\n }\n}\n\n\nBackgroundWorker_WorkCompleted(object sender, DoWorkArgs e)\n{\n //Forces UI thread to valitdate dataset\n dataset2.update();\n\n // Sets file Path\n string FilePath = \"Some Path to file\";\n\n dataset2.writexml(FilePath, XmlWriteOptions.WriteSchema);\n\n //if you use xml to fill your dataset filepath to write should equal path to dataset1 xml\n dataset1.Refresh();\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,014 | <p>Is there any way to detect if the iPhone wakes up from sleep while you're app is running? Eg: your app is running, the user locks the screen (or the screen auto locks) and some time later the user unlocks the screen and up pops your app. Is there some way to get an event at that point or detect it somehow? </p>
<p>I've tried searching the Google and this forum, but I can't seem to find anything about it.</p>
| [
{
"answer_id": 368066,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 4,
"selected": true,
"text": "applicationDidBecomeActive:"
},
{
"answer_id": 1490753,
"author": "noodl_es",
"author_id": 170237,
"author_profile": "https://Stackoverflow.com/users/170237",
"pm_score": 3,
"selected": false,
"text": "-(void) applicationWillResignActive:(UIApplication *)application {\n\n NSLog(@\"Asleep\");\n}\n\n-(void) applicationDidBecomeActive:(UIApplication *)application {\n\n NSLog(@\"Awake\");\n} \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
368,018 | <p>I'm trying to replace every multiline import inside a Python source file.. So, the source goes like</p>
<pre><code>from XXX import (
AAA,
BBB,
)
from YYY import (
CCC,
DDD,
EEE,
...
)
...other instructions...
</code></pre>
<p>and I'd like to get something like</p>
<pre><code>from XXX import AAA, BBB
from YYY import CCC, DDD, EEE, ...
...other instructions...
</code></pre>
<p>I tried to use sed but it looks like it doesn't support non-greedy matching of the closing parenthesis, so it "eats" the second import.. :(<br>
Any hint? Is this impossible with sed? Should I try with another tool?</p>
| [
{
"answer_id": 368037,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": true,
"text": "lineIter= iter(aFile)\nfor aLine in lineIter:\n if aLine.startswith(\"import\"):\n if aLine.endswith(\"(\"):\n for aModule in lineIter:\n if aModule.endwith(\")\"):\n break\n print \"import\", aModule.strip()\n else:\n print aLine.stri()\n else:\n print aLine.strip()\n"
},
{
"answer_id": 8607020,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 2,
"selected": false,
"text": "sed '/^from/,/^)/{H;//{x;/)/{s/[\\n()]//g;s/ */ /g;s/,$//;p;x}};d}' source\nfrom XXX import AAA, BBB\nfrom YYY import CCC, DDD, EEE, ...\n...other instructions...\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
368,021 | <p>When my app is run in the iPhone simulator, the delegate method</p>
<pre><code>- (void)applicationWillTerminate:(UIApplication *)application
</code></pre>
<p>is only called the first time I hit the iPhone simulator's home button.</p>
<p>After the home button is pressed and the app is launched again, hitting the home button does not call the delegate method.</p>
<p>What is going on here? Am I misunderstanding something fundamental?</p>
| [
{
"answer_id": 368064,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 6,
"selected": true,
"text": "NSLog applicationWillTerminate: NSLog /Applications/Console.app"
},
{
"answer_id": 4372705,
"author": "Linuxmint",
"author_id": 524358,
"author_profile": "https://Stackoverflow.com/users/524358",
"pm_score": 2,
"selected": false,
"text": "- (void)applicationWillTerminate:(UIApplication *)application\n - (void)applicationDidEnterBackground {\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26088/"
] |
368,039 | <p>I seem to have an app on my Dev server that has lots of open connections (they should be there, but some bad data layer was used to open them, that forgot to close them). I just want them closed so I can keep other apps running on the server. How can I force all the connections to close?</p>
| [
{
"answer_id": 368052,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 2,
"selected": false,
"text": "DECLARE @kill_id smallint \nDECLARE spid_cursor CURSOR FOR\nselect spid from sysprocesses \nwhere dbid = > 4 and last_batch < dateadd(hour, -24, getdate()) and spid >= 50\n\nOPEN spid_cursor\n\nFETCH NEXT FROM spid_cursor INTO @kill_id\n\nWHILE (@@FETCH_STATUS = 0)\nBEGIN\n-- Kill the current spid here\n-- KILL @kill_id <---This line will not work\n\n-- Get the next cursor row\nFETCH NEXT FROM spid_cursor INTO @kill_id\nEND \n\nCLOSE spid_cursor\n\nDEALLOCATE spid_cursor\n"
},
{
"answer_id": 368179,
"author": "Thuglife",
"author_id": 41612,
"author_profile": "https://Stackoverflow.com/users/41612",
"pm_score": 4,
"selected": true,
"text": "SET NOCOUNT ON;\n\nDECLARE @host VARCHAR(50), @login NVARCHAR(128);\n\nSET @host = 'fooHost'; --NULL to kill sessions from all hosts.\nSET @login = 'fooLogin';\n\nDECLARE @cmd NVARCHAR(255);\nDECLARE @possition INT, @total INT, @selSpid SMALLINT;\nDECLARE @spidInfo TABLE\n(\n [id] INT IDENTITY(1,1),\n spid SMALLINT,\n loginame NVARCHAR(128)\n);\n\nINSERT @spidInfo(spid, loginame)\nSELECT session_id, login_name \nFROM sys.dm_exec_sessions\nWHERE is_user_process = 1 AND [status] = 'sleeping' AND \n login_name = @login AND [host_name] = COALESCE(@host, [host_name]);\n\nSELECT @total = @@IDENTITY, @selSpid = 0, @possition = 0;\n\nWHILE @possition < @total\n BEGIN\n SELECT TOP 1 @selSpid = spid, @possition = [id]\n FROM @spidInfo\n WHERE [ID] > @possition\n\n SET @cmd = N'KILL ' + CAST(@selSpid AS NVARCHAR(10));\n EXEC sp_executesql @cmd;\n PRINT 'SessionId = ' + CAST(@selSpid AS NVARCHAR(10)) + '[' + @login + \n '] killed by ' + system_user + ' at ' + CAST(GETDATE() AS VARCHAR(50));\n END;\n\nIF (@total = 0)\n PRINT 'No sessions owned by user ' + '[' + @login + ']';\n"
},
{
"answer_id": 668072,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT DB_NAME(dbid) as 'Database Name', \nCOUNT(dbid) as 'Total Connections' \nFROM master.dbo.sysprocesses WITH (nolock)\nWHERE dbid > 0\nGROUP BY dbid\nSELECT @@MAX_CONNECTIONS AS 'Max Allowed Connections'\n USE master\ngo\n\nDECLARE @dbname sysname\n\nSET @dbname = 'Events'\n\nDECLARE @spid int\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)\nWHILE @spid IS NOT NULL\nBEGIN\nEXECUTE ('KILL ' + @spid)\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid\nEND\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
368,041 | <p>I would like to show the user with a spinner, that something is done in background but do not know how this works in a batchfile.</p>
<p>Does anyone have a clue?</p>
| [
{
"answer_id": 368793,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 1,
"selected": false,
"text": "WScript.StdOut.Write(chr(8) & WScript.Arguments(0))\n vbsEcho.vbs @echo off\n\n:LOOP\ncscript //nologo vbsEcho.vbs \"\\\"\ncscript //nologo vbsEcho.vbs \"|\"\ncscript //nologo vbsEcho.vbs \"/\"\ncscript //nologo vbsEcho.vbs \"-\"\ngoto :LOOP\n @ECHO OFF\n\nSETLOCAL ENABLEDELAYEDEXPANSION\nSET COUNT=1\n\nSTART CALC\n\ncscript //nologo vbsEcho.vbs \"Calculating: \\\"\n:LOOP\nIF !COUNT! EQU 1 cscript //nologo vbsEcho.vbs \"|\"\nIF !COUNT! EQU 2 cscript //nologo vbsEcho.vbs \"/\"\nIF !COUNT! EQU 3 cscript //nologo vbsEcho.vbs \"-\"\nIF !COUNT! EQU 4 (\n cscript //nologo vbsEcho.vbs \"\\\"\n set COUNT=1\n) else (\n set /a COUNT+=1\n)\n\npslist CALC >nul 2>&1\nif %ERRORLEVEL% EQU 1 goto :end\n\ngoto :LOOP\n\n:END\ncscript //nologo vbsEcho.vbs \". Done.\"\n"
},
{
"answer_id": 368865,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "@echo off\n\n:spinner\nset mSpinner=%mSpinner%.\nif %mSpinner%'==..............................' set mSpinner=.\ncls\necho %mSpinner%\n\nrem Check if the process has finished via WMIC and/or tasklist.\n\ngoto spinner\n\n\n:exit\n"
},
{
"answer_id": 368882,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 2,
"selected": false,
"text": "@ECHO OFF\n\nSETLOCAL ENABLEDELAYEDEXPANSION\nSET COUNT=1\n\nSTART CALC\n\n:BEGIN\n CLS\n IF !COUNT! EQU 1 ECHO \\\n IF !COUNT! EQU 2 ECHO -\n IF !COUNT! EQU 3 ECHO /\n IF !COUNT! EQU 4 ECHO -\n IF !COUNT! EQU 4 (\n SET COUNT=1\n ) ELSE (\n SET /A COUNT+=1\n )\n PSLIST CALC >nul 2>&1\n IF %ERRORLEVEL% EQU 1 GOTO END\nGOTO BEGIN\n\n:END\n"
},
{
"answer_id": 371276,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": true,
"text": "echo -n set /p <nul (set /p junk=Hello)\necho. again.\n @echo off\n\n:: Localise environment.\nsetlocal enableextensions enabledelayedexpansion\n\n:: Specify directories. Your current working directory is used\n:: to create temporary files tmp_*.*\nset wkdir=%~dp0%\nset wkdir=%wkdir:~0,-1%\n\n:: First pass, 10-second task with 20-second timeout.\ndel \"%wkdir%\\tmp_*.*\" 2>nul\necho >>\"%wkdir%\\tmp_payload.cmd\" ping 127.0.0.1 -n 11 ^>nul\necho >>\"%wkdir%\\tmp_payload.cmd\" del \"%wkdir%\\tmp_payload.flg\"\ncall :monitor \"%wkdir%\\tmp_payload.cmd\" \"%wkdir%\\tmp_payload.flg\" 20\n\n:: Second pass, 15-second task with 10-second timeout.\ndel \"%wkdir%\\tmp_*.*\" 2>nul:\necho >>\"%wkdir%\\tmp_payload.cmd\" ping 127.0.0.1 -n 16 ^>nul\necho >>\"%wkdir%\\tmp_payload.cmd\" del \"%wkdir%\\tmp_payload.flg\"\ncall :monitor \"%wkdir%\\tmp_payload.cmd\" \"%wkdir%\\tmp_payload.flg\" 10\n\ngoto :final\n\n:monitor\n :: Create flag file and start the payload minimized.\n echo >>%2 dummy\n start /min cmd.exe /c \"%1\"\n\n :: Start monitoring.\n :: i is the indicator (0=|,1=/,2=-,3=\\).\n :: m is the number of seconds left before timeout.\n set i=0\n set m=%3\n <nul (set /p z=Waiting for child to finish: ^|)\n\n :: Loop here awaiting completion.\n :loop\n :: Wait one second.\n ping 127.0.0.1 -n 2 >nul\n\n :: Update counters and output progress indicator.\n set /a \"i = i + 1\"\n set /a \"m = m - 1\"\n if %i% equ 4 set i=0\n if %i% equ 0 <nul (set /p z=^H^|)\n if %i% equ 1 <nul (set /p z=^H/)\n if %i% equ 2 <nul (set /p z=^H-)\n if %i% equ 3 <nul (set /p z=^H\\)\n\n :: End conditions, complete or timeout.\n if not exist %2 (\n echo.\n echo. Complete.\n goto :final\n )\n if %m% leq 0 (\n echo.\n echo. *** ERROR: Timed-out waiting for child.\n goto :final\n )\n goto :loop\n:final\nendlocal\n"
},
{
"answer_id": 908990,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": ":LOOP\n ECHOX -n \"~r%Processing...\"\n IF %CTR% EQU 4 SET /A CTR=0\n IF %CTR%==0 (set /p DOT=³)<NUL\n IF %CTR%==1 (set /p DOT=/)<NUL\n IF %CTR%==2 (set /p DOT=Ä)<NUL\n IF %CTR%==3 (set /p DOT=\\)<NUL\n ECHOX -n \"~r\"\n SET /A CTR+=1\n SET /A TCT+=1\n IF %TCT% GTR %MAX_COUNT% GOTO :END\nGOTO :LOOP\n"
},
{
"answer_id": 1267920,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": ":: begin spin.cmd\n@echo off\nsetlocal\n\nset COUNT=0\nset MAXCOUNT=10\nset SECONDS=1\n\n:LOOP\ntitle \"\\\"\ncall :WAIT\ntitle \"|\"\ncall :WAIT\ntitle \"/\"\ncall :WAIT\ntitle \"-\"\nif /i \"%COUNT%\" equ \"%MAXCOUNT%\" goto :EXIT\nset /a count+=1\necho %COUNT%\ngoto :LOOP\n\n:WAIT\nping -n %SECONDS% 127.0.0.1 > nul\nping -n %SECONDS% 127.0.0.1 > nul\ngoto :EOF\n\n:EXIT\ntitle FIN!\nendlocal\n:: end spin.cmd\n"
},
{
"answer_id": 2080190,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "@echo off\n\n:: Localise environment.\nsetlocal enableextensions enabledelayedexpansion\n\nset wkdir=%~dp0%\nset wkdir=%wkdir:~0,-1%\nset done_flag=\"%wkdir%\\tmp_payload.flg\"\nset timeout=7\n\n\n:controller\n\nIF (%1)==() (\n call :monitor step1 \"Getting stuff from SourceSafe: \"\n call :monitor step2 \"Compiling some PHP stuff: \"\n call :monitor step3 \"Finishing up the rest: \"\n) ELSE ( goto %1 )\n\ngoto final\n\n\n:step1\n::ping for 5 seconds\n ping 127.0.0.1 -n 6 >nul\n del \"%wkdir%\\tmp_payload.flg\"\ngoto final\n\n:step2\n::ping for 10 seconds\n ping 127.0.0.1 -n 11 >nul\n del \"%wkdir%\\tmp_payload.flg\"\ngoto final\n\n:step3\n::ping for 5 seconds\n ping 127.0.0.1 -n 6 >nul\n del \"%wkdir%\\tmp_payload.flg\"\ngoto final\n\n:monitor\n:: Create flag file and start the payload minimized.\n:: echo the word \"dummy\" to the flag file (second parameter)\n echo >>%done_flag% dummy\n:: start the command defined in the first parameter\n start /min cmd.exe /c \"test2.bat %1\"\n\n:: Start monitoring.\n:: i is the indicator (0=|,1=/,2=-,3=\\).\n:: m is the number of seconds left before timeout.\nset i=0\nset m=%timeout%\nset str=%2\nfor /f \"useback tokens=*\" %%a in ('%str%') do set str=%%~a\n\n<nul (set /p z=%str%^|)\n\n:: Loop here awaiting completion.\n:loop\n :: Wait one second.\n ping 127.0.0.1 -n 2 >nul\n\n :: Update counters and output progress indicator.\n set /a \"i = i + 1\"\n set /a \"m = m - 1\"\n if %i% equ 4 set i=0\n if %i% equ 0 <nul (set /p z=^|)\n if %i% equ 1 <nul (set /p z=/)\n if %i% equ 2 <nul (set /p z=-)\n if %i% equ 3 <nul (set /p z=\\)\n\n :: End conditions, complete or timeout.\n if not exist %done_flag% (\n ::echo.\n echo Complete\n goto :final\n )\n if %m% leq 0 (\n echo.\n echo. *** ERROR: Timed-out waiting for child.\n goto :final\n )\n goto :loop\n\n:final\nendlocal\n"
},
{
"answer_id": 12891502,
"author": "carlsomo",
"author_id": 1745223,
"author_profile": "https://Stackoverflow.com/users/1745223",
"pm_score": 2,
"selected": false,
"text": "@ECHO OFF\nSETLOCAL ENABLEDELAYEDEXPANSION\nCALL :BACKSPACE $BS\nSET /A FULL_COUNT=60\nSET /A MAX_COUNT=160\nSET /A Spin_Delay=50\nSET \"_MSG=Process running...\"\nSET /A CTR=0\nSET /A TCT=0\nIF NOT [%1]==[] SET _MSG=%~1\nIF NOT [%2]==[] SET /A FULL_COUNT=%2\nIF NOT [%3]==[] SET /A SPIN_DELAY=%3\nIF %FULL_COUNT% GTR %MAX_COUNT% SET FULL_COUNT=%MAX_COUNT%\n(SET/P=%_MSG%*)<nul\nFOR /L %%A IN (1,1,%FULL_COUNT%) DO (\n CALL :DELAY %SPIN_DELAY%\n IF !CTR! EQU 0 (set/p=%$BS%³)<nul\n IF !CTR! EQU 1 (set/p=%$BS%/)<nul\n IF !CTR! EQU 2 (set/p=%$BS%Ä)<nul\n IF !CTR! EQU 3 (set/p=%$BS%\\)<nul\n SET /A CTR=%%A %% 4\n)\n(SET/P=%$BS%*)<nul\nENDLOCAL & EXIT /B %CTR%\n\n:BackSpace\nsetlocal\nfor /f %%a in ('\"prompt $H$S &echo on &for %%b in (1) do rem\"') do set \"Bs=%%a\"\nendlocal&call set %~1=%BS%&exit /b 0\n\n:Delay msec\nsetlocal enableextensions\nset/a correct=0\nset/a msecs=%1+5\nif /i %msecs% leq 20 set /a correct-=2\nset time1=%time: =%\nset/a tsecs=%1/1000 2>nul\nset/a msecs=(%msecs% %% 1000)/10\nfor /f \"tokens=1-4 delims=:.\" %%a in (\"%time1%\") do (\n set hour1=%%a&set min1=%%b&set sec1=%%c&set \"mil1=%%d\"\n)\nif /i %hour1:~0,1% equ 0 if /i \"%hour1:~1%\" neq \"\" set hour1=%hour1:~1% \nif /i %min1:~0,1% equ 0 set min1=%min1:~1% \nif /i %sec1:~0,1% equ 0 set sec1=%sec1:~1%\nif /i %mil1:~0,1% equ 0 set mil1=%mil1:~1% \nset/a sec1+=(%hour1%*3600)+(%min1%*60)\nset/a msecs+=%mil1%\nset/a tsecs+=(%sec1%+%msecs%/100)\nset/a msecs=%msecs% %% 100\n:: check for midnight crossing\nif /i %tsecs% geq 86400 set /a tsecs-=86400\nset/a hour2=%tsecs% / 3600\nset/a min2=(%tsecs%-(%hour2%*3600)) / 60\nset/a sec2=(%tsecs%-(%hour2%*3600)) %% 60\nset/a err=%msecs%\nif /i %msecs% neq 0 set /a msecs+=%correct%\nif /i 1%msecs% lss 20 set msecs=0%msecs%\nif /i 1%min2% lss 20 set min2=0%min2%\nif /i 1%sec2% lss 20 set sec2=0%sec2%\nset time2=%hour2%:%min2%:%sec2%.%msecs%\n:wait\n set timen=%time: =%\n if /i %timen% geq %time2% goto :end\ngoto :wait\n:end\nfor /f \"tokens=2 delims=.\" %%a in (\"%timen%\") do set num=%%a\nif /i %num:~0,1% equ 0 set num=%num:~1%\nset/a err=(%num%-%err%)*10\nendlocal&exit /b %err%\n"
},
{
"answer_id": 29000218,
"author": "pollaris",
"author_id": 3120500,
"author_profile": "https://Stackoverflow.com/users/3120500",
"pm_score": 0,
"selected": false,
"text": " @echo off\n start calc\n call :spinner calc.exe\n pause\n\n :spinner \n SET COUNT=1\n :BEGIN\n set \"formattedValue=000000%count%\"\n ECHO.exe -n Elapsed: %formattedValue:~-3% seconds\n ECHO.exe -n \\r %= -n (suppress crlf) \\r output a cr =%\n\n SET /A COUNT+=1\n\n set EXE=%1 %= search output of tasklist for EXE =%\n set tl=tasklist /NH /FI \"IMAGENAME eq %EXE%\"\n FOR /F %%x IN ('%tl%') DO IF %%x == %EXE% goto FOUND\n set result=0\n goto FIN\n :FOUND\n set result=1\n :FIN\n IF %result% EQU 0 GOTO END\n\n PING -n 2 127.0.0.1 > nul %= wait for about 1 second =%\n\n GOTO BEGIN\n :END\n"
},
{
"answer_id": 45470943,
"author": "s1i2v3a",
"author_id": 3686388,
"author_profile": "https://Stackoverflow.com/users/3686388",
"pm_score": 0,
"selected": false,
"text": "@echo off & setlocal enabledelayedexpansion\nstart application.exe\n:1\nfor %%a in (^| ^/ ^- ^\\ ^| ^/ ^- ^\\) do (\nfor %%b in (^| ^/ ^- ^\\ ^| ^/ ^- ^\\) do (\nfor %%c in (^| ^/ ^- ^\\ ^| ^/ ^- ^\\) do (\ncls &echo processing..%%c%%b%%a\nsleep -m 20\nIF EXIST \"result file\" (exit)\n)))\ngoto 1\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44532/"
] |
368,049 | <p>I'd like to insert a new field with a Default value using Visual C++ Code.
I have wrote this:</p>
<pre><code>CADODatabase pDB;
String strConnessione = _T("Provider=Microsoft.Jet.OLEDB.4.0;""Data Source=");
strConnessione = strConnessione + "MioDatabase.mdb";
pDB.SetConnectionString(strConnessione);
pDB.Open();
query.Format("ALTER TABLE TBProva ADD Fattore Double Default 0;");
pDB.Execute(query);
</code></pre>
<p>but it isn't correct. How can I do for doing it?
Someone of you Can write me the just code? </p>
| [
{
"answer_id": 368572,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 2,
"selected": false,
"text": "strSql = \"ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);\"\nstrSql = \"ALTER TABLE MyTable ADD COLUMN MyText TEXT(3);\"\n Dim myConnection AS ADODB.connection\nset myConnection = New ADODB.connectionString\nmyConnection.connectionString = 'here is your connection string'\nmyConnection.open\nmyConnection.execute \"ALTER TABLE myTable ADD Column MyField DECIMAL (12,3);\"\nmyConnection.close\n CurrentProject.Connection.Execute \"ALTER TABLE myTable ADD Column MyField DOUBLE;\"\n Table.columns.append"
},
{
"answer_id": 386053,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "COLUMN ALTER TABLE TBProva ADD COLUMN Fattore Double Default 0;\n NOT NULL ALTER TABLE TBProva ADD COLUMN Fattore DOUBLE DEFAULT 0 NOT NULL;\n DEFAULT DEFAULT NOT NULL INSERT"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
</code></pre>
<p>Given that setup:</p>
<pre><code>>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>Even stranger:</p>
<pre><code>>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?</p>
| [
{
"answer_id": 368178,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 5,
"selected": true,
"text": ">>> import sys,types,xml\n>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')\n>>> import xml.config\n>>> from xml import config\n>>> from xml import config as x\n>>> x\n<module 'xml.config' (built-in)>\n"
},
{
"answer_id": 368247,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 1,
"selected": false,
"text": "class VirtualModule(object):\n def __init__(self, modname, subModules):\n try:\n import sys\n self._mod = __import__(modname)\n sys.modules[modname] = self\n __import__(modname)\n self._modname = modname\n self._subModules = subModules\n except ImportError, err:\n pass # please signal error in some useful way :-)\n def __repr__(self):\n return \"Virtual module for \" + self._modname\n def __getattr__(self, attrname):\n if attrname in self._subModules.keys():\n import sys\n __import__(self._subModules[attrname])\n return sys.modules[self._subModules[attrname]]\n else:\n return self._mod.__dict__[attrname]\n\n\nVirtualModule('mylibrary', {'config': 'actual_module_for_config'})\n\nimport mylibrary\nmylibrary.config\nmylibrary.some_function\n"
},
{
"answer_id": 368910,
"author": "fuzzyman",
"author_id": 5341,
"author_profile": "https://Stackoverflow.com/users/5341",
"pm_score": 2,
"selected": false,
"text": "import sys, types\nconfig = types.ModuleType('config')\nsys.modules['mylibrary.config'] = config\n import mylibrary\nmylibrary.config = config\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15677/"
] |
368,074 | <p>I have a problem in integrating PHP and JQuery:</p>
<p>My main file is <code>MyFile.html</code> and the AJAX call file is <code>ajax.php</code>.</p>
<p>The <code>ajax.php</code> function returns links to <code>myFile.html</code> as </p>
<p><code><a href Link.php?action=Function ></a></code> (i.e <code>echo " <a href Link.php?action=Delete";</code>)</p>
<p>When I click the returned link from <code>MyFile.html</code> it's performing as expected. I need how to modify the equivalent code to work correctly in <code>Myfile.Html</code>.</p>
<p>My motivation is that the <code>ajax.php</code> return link should work in HTML.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 368113,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "= <a href Link.php?action=Function >\n <a href=\"Link.php?action=Function\">\n echo \"<a href=\\\"Link.php?action=Function\\\">\";\n echo '<a href=\"Link.php?action=Function\">';\n"
},
{
"answer_id": 368175,
"author": "William Brendel",
"author_id": 2405,
"author_profile": "https://Stackoverflow.com/users/2405",
"pm_score": 1,
"selected": true,
"text": "<?\n // Get the parameter \"foo\" from the URL string.\n $action = $_GET['foo'];\n\n // Return a different link depending on what 'foo' is.\n switch ($action) {\n case 'a':\n print('<a href=\"Link.php?action=Delete\">Delete</a>');\n break;\n case 'b':\n print('<a href=\"Link.php?actiom=Edit\">Edit</a>');\n break;\n default:\n print('<a href=\"Link.php?action=New\">New</a>');\n break;\n }\n?>\n <html>\n<head>\n<title>Demo Page</title>\n<script type=\"text/javascript\" src=\"js/jquery.js\"></script>\n<script type=\"text/javascript\">\n $(function() {\n $.get('ajax.php?foo=a', function(data) {\n $('#result').html('Received response: ' + data);\n });\n });\n</script>\n</head>\n<body>\n<!-- This div will contain a link to the \"Delete\" -->\n<div id=\"result\"/>\n</body>\n</html>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44984/"
] |
368,094 | <p>In Java, what are the performance and resource implications of using</p>
<pre><code>System.currentTimeMillis()
</code></pre>
<p>vs. </p>
<pre><code>new Date()
</code></pre>
<p>vs. </p>
<pre><code>Calendar.getInstance().getTime()
</code></pre>
<p>As I understand it, <code>System.currentTimeMillis()</code> is the most efficient. However, in most applications, that long value would need to be converted to a Date or some similar object to do anything meaningful to humans.</p>
| [
{
"answer_id": 368100,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 4,
"selected": false,
"text": "System.currentTimeMillis() Calendar Date"
},
{
"answer_id": 368103,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 5,
"selected": false,
"text": "System.currentTimeMillis() System.currentTimeMillis() long start = System.currentTimeMillis();\n .... do something ...\n long elapsed = System.currentTimeMillis() -start;\n"
},
{
"answer_id": 368111,
"author": "Esko",
"author_id": 44523,
"author_profile": "https://Stackoverflow.com/users/44523",
"pm_score": 6,
"selected": false,
"text": "Calendar.getInstance() public GregorianCalendar(TimeZone zone, Locale aLocale) {\n super(zone, aLocale);\n gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);\n setTimeInMillis(System.currentTimeMillis());\n}\n public Date() {\n this(System.currentTimeMillis());\n}\n"
},
{
"answer_id": 368130,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 9,
"selected": true,
"text": "System.currentTimeMillis() new Date() Calendar Date Calendar"
},
{
"answer_id": 369875,
"author": "MykennaC",
"author_id": 30818,
"author_profile": "https://Stackoverflow.com/users/30818",
"pm_score": 3,
"selected": false,
"text": "System.nanoTime()"
},
{
"answer_id": 16249959,
"author": "Puzirki",
"author_id": 940157,
"author_profile": "https://Stackoverflow.com/users/940157",
"pm_score": 4,
"selected": false,
"text": "Calendar.getInstance() new Date()"
},
{
"answer_id": 21338463,
"author": "wiji",
"author_id": 3232960,
"author_profile": "https://Stackoverflow.com/users/3232960",
"pm_score": 2,
"selected": false,
"text": " long now = System.currentTimeMillis();\n for (int i = 0; i < 10000000; i++) {\n new Date().getTime();\n }\n long result = System.currentTimeMillis() - now;\n\n System.out.println(\"Date(): \" + result);\n\n now = System.currentTimeMillis();\n for (int i = 0; i < 10000000; i++) {\n System.currentTimeMillis();\n }\n result = System.currentTimeMillis() - now;\n\n System.out.println(\"currentTimeMillis(): \" + result);\n"
},
{
"answer_id": 21338583,
"author": "Ramón",
"author_id": 1916348,
"author_profile": "https://Stackoverflow.com/users/1916348",
"pm_score": 0,
"selected": false,
"text": "System.currentTimeMillis()"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
368,114 | <p>I have an HTML form with two buttons as follows:</p>
<pre><code><input type="submit" name="confirm" value="Yes, Delete" />
<button name="confirm" type="button" onclick="history.back()" value="No, Go Back">No, Go Back</button>
</code></pre>
<p>Now, when I click on either in Firefox, the behavior is as expected. If I click the submit button, then "Yes, Delete" gets posted and if I click "No, Go Back" it's as if I hit the back button on the browser. However, in Internet Explorer (6 or 8), if I click on "Yes, Delete" then "No, Go Back" gets posted. Why is that?</p>
| [
{
"answer_id": 368151,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<button> <BUTTON>"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] |
368,139 | <p>I was given a task of write the coding guidelines for my team, and it was going great until my manager asked me to write an explanation of <strong>Why Error Handling is Important</strong>.</p>
<p>I know it instinctively, but how do I express this in words?</p>
<p>I tried to google it first but came up empty, so I now ask my fellow coding wizards.</p>
| [
{
"answer_id": 368165,
"author": "Christian Payne",
"author_id": 5188,
"author_profile": "https://Stackoverflow.com/users/5188",
"pm_score": 1,
"selected": false,
"text": "System.IO.FileNotFoundException System.Data.SqlClient.SqlException System.ApplicationException"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44375/"
] |
368,143 | <p>I'm new to ASP.NET MVC and all tutorials, samples, and the like I seem to find are very basic.</p>
<p>Is it possible (and if yes, a good design) to have routes like so:
.../Organization/10/User/5/Edit
.../Organization/10/User/List</p>
<p>In other words; can the urls mirror your domain model?</p>
| [
{
"answer_id": 368243,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 1,
"selected": false,
"text": "\"~/Organization/{orgId}/{Controller}/{id}/{action}\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46343/"
] |
368,154 | <p>I'm creating a installer for a c# windows project using VS 2008. I'm trying to write a custom action that copies a settings file from the source directory of the MSI file stored on a file server (e.g. \server\fileshare\myappinstaller\mysetting.xml) to the target directory on the computer on which my application is been installed (e.g. C:\Program Files\My App). </p>
<p>The settings file can't be added in to the installer as it will contain settings with will be unique to the customer installing the app. </p>
<p>Does anyone have code (preferably C# or VB.NET) for such a custom action? Alternately does anyone know how to get the MSI source location (e.g. \server\fileshare\myappinstaller) within a custom action.</p>
<p>Many thanks</p>
| [
{
"answer_id": 2094661,
"author": "habakuk",
"author_id": 254041,
"author_profile": "https://Stackoverflow.com/users/254041",
"pm_score": 3,
"selected": false,
"text": " Public Overrides Sub Commit(ByVal savedState As System.Collections.IDictionary)\n MyBase.Commit(savedState)\n\n Dim directoryOfMSI As String = IO.Path.GetDirectoryName(Context.Parameters(\"InstallerPath\"))\n\n 'Do your work here\n '...\n\n End Sub\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/254/"
] |
368,160 | <p>I have a dataset in a worksheet that can be different every time. I am creating a pivottable from that data, but it is possible that one of the PivotItems is not there. For example:</p>
<pre><code>.PivotItems("Administratie").Visible = False
</code></pre>
<p>If that specific value is not in my dataset, the VBA script fails, saying that it can't define the item in the specified Field. (error 1004)</p>
<p>So I thought a loop might work.
I have the following: </p>
<pre><code>Dim pvtField As PivotField
Dim pvtItem As PivotItem
Dim pvtItems As PivotItems
For Each pvtItem In pvtField.pvtItems
pvtItem.Visible = False
Next
</code></pre>
<p>But that gives me an 91 error at the For Each pvtItem line:</p>
<pre><code>Object variable or With block variable not set
</code></pre>
<p>I thought I declared the variables well enough, but I am most likely missing something obvious... </p>
| [
{
"answer_id": 368211,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": "Public Function Test()\n On Error GoTo Test_EH\n\n Dim pvtField As PivotField\n Dim pvtItem As PivotItem\n Dim pvtItems As PivotItems\n\n ' Change \"Pivot\" to the name of the worksheet that has the pivot table.\n ' Change \"PivotTable1\" to the name of the pivot table; right-click on the\n ' pivot table, and select Table Options... from the context menu to get the name.\n For Each pvtField In Worksheets(\"Pivot\").PivotTables(\"PivotTable1\").PivotFields\n Debug.Print \"Pivot Field: \" & pvtField.Name\n For Each pvtItem In pvtField.VisibleItems\n pvtItem.Visible = False\n Next\n Next\n\nExit Function\n\nTest_EH:\n Debug.Print pvtItem.Name & \" error(\" & Err.Number & \"): \" & Err.Description\n Resume Next\n\nEnd Function\n Public Function PivotItemPresent(sName As String) As Boolean\n On Error GoTo PivotItemPresent_EH\n\n PivotItemPresent = False\n\n For Each pvtField In Worksheets(\"Pivot\").PivotTables(\"PivotTable1\").PivotFields\n For Each pvtItem In pvtField.VisibleItems\n If pvtItem.Name = sName Then\n PivotItemPresent = True\n Exit Function\n End If\n Next\n Next\n\n Exit Function\n\nPivotItemPresent_EH:\n Debug.Print \"Error(\" & Err.Number & \"): \" & Err.Description\n Exit Function\n\nEnd Function\n If PivotItemPresent(\"name_of_the_thing\") Then\n ' Do something\nEnd If\n"
},
{
"answer_id": 371012,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 0,
"selected": false,
"text": "For Each pvtField In Worksheets(\"my_sheet\").PivotTables(\"my_table\").PivotFields\n For Each pvtItem In pvtField.PivotItems\n Debug.Print vbTab & pvtItem.Name & \".Visible = \" & pvtItem.Visible\n /*.PivotItems(pvtItem).Visible = False*/ \n Next\nNext\n.PivotItems(\"certain_Item\").Visible = True\n If PivotItem(\"name_of_the_thing\") = present Then {\n do_something()\n}\n"
},
{
"answer_id": 371134,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": ".PivotItems(pvtItem).Visible With pvtField.PivotItems(pvtItem.Name).Visible = False"
},
{
"answer_id": 373971,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 0,
"selected": false,
"text": "With ActiveSheet.PivotTables(\"Table\").PivotFields(\"Field\")\n\n Dim pvtField As Excel.PivotField\n Dim pvtItem As Excel.PivotItem\n Dim pvtItems As Excel.PivotItems\n\n For Each pvtField In Worksheets(\"Sheet\").PivotTables(\"Table\").PivotFields\n For Each pvtItem In pvtField.PivotItems\n If pvtItem.Name = \"ItemTitle\" Then\n pvtField.PivotItems(\"ItemTitle\").Visible = True\n Else\n pvtField.PivotItems(pvtItem.Name).Visible = False\n End If\n Next\n Next\nEnd With\n"
},
{
"answer_id": 374378,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": "Public Sub ShowInPivot(Field As String, Item As String)\n On Error GoTo ShowInPivot_EH\n\n Dim pvtField As PivotField\n Dim pvtItem As PivotItem\n Dim pvtItems As PivotItems\n\n For Each pvtItem In Worksheets(\"Pivot\").PivotTables(\"PivotTable1\").PivotFields(Field).PivotItems\n If pvtItem.Name = Item Then\n pvtItem.Visible = True\n Else\n pvtItem.Visible = False\n End If\n Next\n\n Exit Sub\n\nShowInPivot_EH:\n Debug.Print \"Error(\" & Err.Number & \"): \" & Err.Description\n Exit Sub\n\nEnd Sub\n ShowInPivot \"Customer\", \"CustomerA\"\nShowInPivot \"Release\", \"1.2\"\nShowInPivot \"Phase\", \"QA\"\n"
},
{
"answer_id": 380557,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 2,
"selected": true,
"text": "Dim Table As PivotTable\nDim FoundCell As Object\nDim All As Range\nDim PvI As PivotItem\n\n Set All = Worksheets(\"Analyse\").Range(\"A7:AZ10000\")\n Set Table = Worksheets(\"Analyse\").PivotTables(\"tablename\")\n For Each PvI In Table.PivotFields(\"fieldname\").PivotItems\n Set FoundCell = All.Find(PvI.Name)\n If FoundCell <> \"itemname\" Then\n PvI.Visible = False\n End If\n Next\n"
},
{
"answer_id": 1557038,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "For Each pi In pt.PivotFields(\"Fecha\").PivotItems\n If pi.Name = ffan Then\n pi.Visible = True\n Else\n pi.Visible = False '<------------------------\n End If\nNext pi\n Dim an As Variant\nan = UserForm8.Label1.Caption 'this label contains the date i want to see its the pivot item i want to see of my pivot fiel that is \"Date\"\nDim fan\nfan = Format(an, \"d m yyyy\") \nDim ffan\nffan = Format(fan, \"general number\")\n\nSheets(\"Datos refrigerante\").Activate 'this is the sheet that has the data of the pivottable\nDim rango1 As Range\nRange(\"B1\").Select\nRange(Selection, Selection.End(xlDown)).Select\n\nSet rango1 = Selection\nActiveSheet.Cells(1, 1).Select\nrango1.Select\n\nSelection.NumberFormat = \"General\" 'I change the format of the column that has all my dates\n\n'clear the cache\nDim pt As PivotTable\nDim ws As Worksheet\nDim pc As PivotCache\n\n'change the settings\nFor Each ws In ActiveWorkbook.Worksheets\n For Each pt In ws.PivotTables\n pt.PivotCache.MissingItemsLimit = xlMissingItemsNone\n Next pt\nNext ws\n\n'refresh all the pivot caches\nFor Each pc In ActiveWorkbook.PivotCaches\n On Error Resume Next\n pc.Refresh\nNext pc\n\n'now select the pivot item i want\nDim pi As PivotItem\n\nSet pt = Sheets(\"TD Refrigerante\").PivotTables(\"PivotTable2\")\n\n'Sets Pivot Table to Manual Sort so you can manipulate PivotItems in PivotField\npt.PivotFields(\"Fecha\").AutoSort xlManual, \"Fecha\"\n\n'Speeds up code dramatically\npt.ManualUpdate = True\n\nFor Each pi In pt.PivotFields(\"Fecha\").PivotItems\n If pi.Name = ffan Then\n pi.Visible = True\n Else\n pi.Visible = False\n End If\nNext pi\n\npt.ManualUpdate = False\npt.PivotFields(\"Fecha\").AutoSort xlAscending, \"Fecha\"\n"
},
{
"answer_id": 66238778,
"author": "Danny Coleiro",
"author_id": 13075915,
"author_profile": "https://Stackoverflow.com/users/13075915",
"pm_score": 0,
"selected": false,
"text": "For Each pvtItem In ActiveSheet.PivotTables(\"PivotTable1\").PivotFields(\"Something\").PivotItems\n If Not pvtItem.Caption = \"Example\" Then\n pvtItem.Visible = False\n End If\nNext\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42389/"
] |
368,169 | <p>I have some code that prints out databse values into a repeater control on an asp.net page. However, some of the values returned are null/blank - and this makes the result look ugly when there are blank spaces. </p>
<p>How do you do conditional logic in asp.net controls i.e. print out a value if one exists, else just go to next value.</p>
<p>I should also add - that I want the markup to be conditional also, as if there is no value I dont want a <br> tag either.</p>
<p>Here is a snippet of code below just to show the type of values I am getting back from my database. (It is common for <strong>Address 2</strong> not to have a value at all).</p>
<pre><code><div id="results">
<asp:Repeater ID="repeaterResults" runat="server">
<ItemTemplate>
Company: <strong><%#Eval("CompanyName") %></strong><br />
Contact Name: <strong><%#Eval("ContactName") %></strong><br />
Address: <strong><%#Eval("Address1")%></strong><br />
<strong><%#Eval("Address2")%></strong><br />..................
</code></pre>
<p>Many thanks</p>
| [
{
"answer_id": 368225,
"author": "Matt Woodward",
"author_id": 40593,
"author_profile": "https://Stackoverflow.com/users/40593",
"pm_score": 4,
"selected": true,
"text": "<strong><% If (Eval(\"Address2\").Length > 0) Then %><%#Eval(\"Address2\")%><% Else %>No data available for Address 2<% End If %></strong><br />\n"
},
{
"answer_id": 368237,
"author": "Jeff.Crossett",
"author_id": 44746,
"author_profile": "https://Stackoverflow.com/users/44746",
"pm_score": 1,
"selected": false,
"text": "If IsDbNull(<%#Eval(\"Address2\")%>) then\n etc\nEnd If\n"
},
{
"answer_id": 368241,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 2,
"selected": false,
"text": "<asp:Repeater ID=\"repeaterResults\" runat=\"server\" OnItemDataBound=\"repeaterResult_ItemDataDataBound\">\n <ItemTemplate>\n <strong><%#Eval(\"Name\") %></strong>\n <asp:Literal runat=\"server\" ID=\"ltlOption\" />\n <br />\n </ItemTemplate></asp:Repeater>\n public class SimpleEntity\n{\n public string Name {get;set;}\n public string Option {get;set;}\n}\n protected void repeaterResult_ItemDataDataBound(object sender, RepeaterItemEventArgs e)\n{\n SimpleEntity ent = e.Item.DataItem as SimpleEntity;\n Literal ltlOption = e.Item.FindControl(\"ltlOption\") as Literal;\n if (ent != null && ltlOption != null)\n {\n if (!string.IsNullOrEmpty(ent.Option))\n {\n ltlOption.Text = ent.Option;\n }\n else\n {\n ltlOption.Text = \"Not entered!\";\n }\n\n }\n}\n"
},
{
"answer_id": 368424,
"author": "Ihar Voitka",
"author_id": 46313,
"author_profile": "https://Stackoverflow.com/users/46313",
"pm_score": 3,
"selected": false,
"text": " <%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"ShowPair.ascx.cs\" Inherits=\"MyWA.ShowPair\" %>\n\n<% if (!string.IsNullOrEmpty(Value))\n { %>\n<%=Key %> : <%=Value %>\n<% } %> \n <asp:Repeater runat='server' ID=\"repeater1\">\n <ItemTemplate>\n <cst:ShowPair Key=\"Company Name:\" Value=\"<%#((Company)Container.DataItem).CompanyName %>\" runat=\"server\"/>\n <cst:ShowPair Key=\"Contact Name:\" Value=\"<%#((Company)Container.DataItem).ContactName %>\" runat=\"server\" />\n <cst:ShowPair Key=\"Address 1:\" Value=\"<%#((Company)Container.DataItem).Address1 %>\" runat=\"server\" />\n </ItemTemplate>\n </asp:Repeater>\n"
},
{
"answer_id": 48887535,
"author": "Paul",
"author_id": 1945782,
"author_profile": "https://Stackoverflow.com/users/1945782",
"pm_score": 0,
"selected": false,
"text": "ISNULL ', ' SELECT \n ISNULL(src.address1 + ', ', '') +\n ISNULL(src.address2 + ', ', '') +\n ISNULL(src.address3 + ', ', '') +\n ISNULL(src.address4 + ', ', '') +\n ISNULL(src.postalcode, '') AS CompoundAddress\n...\n NULL NULL NULL SELECT \n (src.address1 + ', ') & \n (src.address2 + ', ') & \n (src.address3 + ', ') & \n (src.address4 + ', ') & \n (src.postalcode) As CompoundAddress\n...\n NULL NULL <div id=\"results\">\n <asp:Repeater ID=\"repeaterResults\" runat=\"server\">\n <ItemTemplate>\n Company: <strong><%#Eval(\"CompanyName\") %></strong><br />\n Contact Name: <strong><%#Eval(\"ContactName\") %></strong><br />\n Address: <strong><%#Eval(\"CompoundAddress\").ToString().Replace(\", \", \"<br />\") %></strong><br />\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
368,170 | <p>I'm trying to write some code to find a specific XmlNode object based on the URL in the XML sitemap but can't get it to find anything.</p>
<p>The sitemap is the standard ASP.net sitemap and contains:</p>
<pre><code><siteMapNode url="~/lev/index.aspx" title="Live-Eye-Views">
--- Child Items ---
</siteMapNode>
</code></pre>
<p>The code I'm using to search for the element is:</p>
<pre><code>XmlDocument siteMapXml = new XmlDocument();
siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName)
XmlNode levRoot = siteMapXml.SelectSingleNode("siteMapNode[@url=\"~/lev/index.aspx\"]");
</code></pre>
<p>The levRoot object is always null. When I break after the Load method, I can see all the elements in the XML file so it's loading as expected.</p>
<p>I've tried using single quotes in the XPath query but that didn't make any difference.</p>
<p>_siteMapFileName is set in the Initialize method and is pointing at the correct file. </p>
<p>Does anyone have any ideas what could be up with this or suggest another way to find a specific element by attribute?</p>
| [
{
"answer_id": 368239,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "<siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" >\n <siteMapNode url=\"~/lev/index.aspx\" title=\"Live-Eye-Views\">\n <!-- Child Items -->\n </siteMapNode>\n</siteMap>\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(siteMapXml.NameTable);\nnsmgr.AddNamespace(\"smap\", \"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\");\nstring xpath = \"//smap:siteMapNode[@url=\\\"{1}\\\"]\";\nstring url = \"~/lev/index.aspx\";\nXmlNode levRoot = siteMapXml.SelectSingleNode(String.Format(xpath, url), nsmgr);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33721/"
] |
368,176 | <p>I need to find 2 elements in an unsorted array such that the difference between them is less than or equal to (Maximum - Minimum)/(number of elements in the array).</p>
<p>In O(n).</p>
<p>I know the max and min values.</p>
<p>Can anyone think of something?</p>
<p>Thank you!</p>
| [
{
"answer_id": 369817,
"author": "Sid Datta",
"author_id": 18390,
"author_profile": "https://Stackoverflow.com/users/18390",
"pm_score": 1,
"selected": false,
"text": "2n (min + k((max-min)/2n)) <= value < (min + (k+1)((max-min)/2n)). ((max-min)/2n) ((max-min)/2n) ((max-min)/2n)*2 = ((max-min)/n)"
},
{
"answer_id": 53613333,
"author": "Jonathan Weiss",
"author_id": 6706019,
"author_profile": "https://Stackoverflow.com/users/6706019",
"pm_score": 1,
"selected": false,
"text": "|max - medianValue | > |min - medianValue | run(arr):\n M = max(arr)\n m = min(arr)\n return findPairBelowAverageDiff(arr,0,arr.length,m,M)\n\nfindPairBelowAverageDiff(arr, start, end, min, max) :\n if start + 1 < end:\n medianPos = start + (end - start) / 2\n // median that is between start and end in the arr.\n quickSelect(arr, start, medianPos, end)\n if max - arr[medianPos] > arr[medianPos] - min:\n return findPairBelowAverageDiff(arr, start, medianPos, \n min, arr[medianPos])\n else :\n return findPairBelowAverageDiff(arr, medianPos, \n end, arr[medianPos], max);\n else :\n return (arr[start], arr[start + 1])\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,184 | <p>I found some code in a project which looks like that : </p>
<pre><code>int main(int argc, char *argv[])
{
// some stuff
try {
theApp.Run();
} catch (std::exception& exc) {
cerr << exc.what() << std::endl;
exit(EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
</code></pre>
<p>I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed. </p>
<p>Do you see any good reason to catch exceptions here ? </p>
<hr>
<p>EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here...</p>
| [
{
"answer_id": 368217,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "int main(void)\n{\n try\n {\n // your code \n }\n catch ( /* YourPossibleExceptions i.e. barfs you expect may occur */ )\n {\n }\n catch ( ... ) // unexpected errors, so you can exit gracefully\n {\n }\n}\n"
},
{
"answer_id": 368749,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "int main()\n{\n try\n {\n }\n catch(std::exception const& e)\n { /* LOG */\n // optimally rethrow\n }\n catch(...) // Catch anything else.\n { /* LOG */\n // optimally rethrow\n }\n}\n"
},
{
"answer_id": 11825728,
"author": "Qube",
"author_id": 1578848,
"author_profile": "https://Stackoverflow.com/users/1578848",
"pm_score": 0,
"selected": false,
"text": "main"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
368,192 | <p>I have this little function</p>
<pre><code>function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
</code></pre>
<p>Which whatever I try, simply outputs the php code as the html source, and not the result of the php code. This was previously working fine, and I am not sure what I have changed to result in this behavior.</p>
<p>I have pasted all the code now. An error is generated by a link that calls updateByQuery, preventing makewindows from being parsed correctly..I think. I am not sure what is wrong with updateByQuery however:</p>
<pre><code>function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
</code></pre>
| [
{
"answer_id": 368216,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "http://localhost/yourpage.php file://yourpage.php"
},
{
"answer_id": 368231,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 1,
"selected": true,
"text": "<?php echo \"This is a test\"; ?>\n <?php \necho \"function makewindows(){var child1 = window.open (\\\"about:blank\\\"); \" .\n\"child1.document.write(\\\"\" . htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES) . \"\\\");\" . \"child1.document.close(); }\"; \n?>\n"
},
{
"answer_id": 368372,
"author": "cLFlaVA",
"author_id": 45109,
"author_profile": "https://Stackoverflow.com/users/45109",
"pm_score": 0,
"selected": false,
"text": "function makewindows(){\n var child1 = window.open (\"about:blank\");\n child1.document.open();\n child1.document.write(\"<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>\");\n child1.document.close(); \n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
368,194 | <p>I'm using <a href="https://tablelayout.dev.java.net/" rel="nofollow noreferrer">TableLayout</a> for my swing GUI. Initially only some basic labels, buttons and text fields where required which I could later on access by:</p>
<pre><code>public Component getComponent(String componentName) {
return getComponent(componentName, this.frame.getContentPane());
}
private Component getComponent(String componentName, Component component) {
Component found = null;
if (component.getName() != null && component.getName().equals(componentName)) {
found = component;
} else {
for (Component child : ((Container) component).getComponents()) {
found = getComponent(componentName, child);
if (found != null)
break;
}
}
return found;
}
</code></pre>
<p>Unfortunately I ran into issues after using using <code>JScrollPane</code> to support scrolling in <code>JTextArea</code> and JTable's, which I did with:</p>
<pre><code>JTextArea ta = new JTextArea();
ta.setName("fooburg");
JScrollPane scr = new JScrollPane(ta);
frame.getContentPane().add(scr, "1, 1"); // EDIT: changed, tkx bruno
</code></pre>
<p>After suggestions, I've been able to access through <code>getComponent("fooburg")</code> the desired component (the version above is the final one). Many thanks to Dan and Bruno!</p>
| [
{
"answer_id": 368216,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "http://localhost/yourpage.php file://yourpage.php"
},
{
"answer_id": 368231,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 1,
"selected": true,
"text": "<?php echo \"This is a test\"; ?>\n <?php \necho \"function makewindows(){var child1 = window.open (\\\"about:blank\\\"); \" .\n\"child1.document.write(\\\"\" . htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES) . \"\\\");\" . \"child1.document.close(); }\"; \n?>\n"
},
{
"answer_id": 368372,
"author": "cLFlaVA",
"author_id": 45109,
"author_profile": "https://Stackoverflow.com/users/45109",
"pm_score": 0,
"selected": false,
"text": "function makewindows(){\n var child1 = window.open (\"about:blank\");\n child1.document.open();\n child1.document.write(\"<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>\");\n child1.document.close(); \n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33429/"
] |
368,200 | <p>Simple question. How do you disable the text selection of DocumentViewer in WPF? This is the feature where an XPS document is displayed by the viewer and then text can be highlighted via mouse. The highlighted text can also be copied but I have already disabled this. I just don't know how to disable the highlighting.</p>
<p>Thanks!</p>
| [
{
"answer_id": 415155,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<Style TargetType=\"{x:Type ScrollViewer}\" x:Key=\"CustomScrollPresenter\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ScrollViewer}\">\n <Grid Background=\"{TemplateBinding Panel.Background}\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n </Grid.RowDefinitions>\n <Rectangle Grid.Column=\"1\" Grid.Row=\"1\" Fill=\"{DynamicResource {x:Static SystemColors.ControlBrushKey}}\" />\n <ScrollContentPresenter \n PreviewMouseLeftButtonDown=\"ScrollContentPresenter_PreviewMouseLeftButtonDown\"\n Grid.Column=\"0\" \n Grid.Row=\"0\" \n Margin=\"{TemplateBinding Control.Padding}\" \n Content=\"{TemplateBinding ContentControl.Content}\" \n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" \n CanContentScroll=\"{TemplateBinding ScrollViewer.CanContentScroll}\" />\n <ScrollBar \n x:Name=\"PART_VerticalScrollBar\"\n Grid.Column=\"1\" \n Grid.Row=\"0\" \n Minimum=\"0\" \n Maximum=\"{TemplateBinding ScrollViewer.ScrollableHeight}\" \n ViewportSize=\"{TemplateBinding ScrollViewer.ViewportHeight}\" \n Value=\"{Binding Path=VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}\" \n Visibility=\"{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}\" \n Cursor=\"Arrow\" AutomationProperties.AutomationId=\"VerticalScrollBar\" />\n <ScrollBar \n x:Name=\"PART_HorizontalScrollBar\"\n Orientation=\"Horizontal\" Grid.Column=\"0\" Grid.Row=\"1\" Minimum=\"0\" \n Maximum=\"{TemplateBinding ScrollViewer.ScrollableWidth}\" ViewportSize=\"{TemplateBinding ScrollViewer.ViewportWidth}\" Value=\"{Binding Path=HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}\" Visibility=\"{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}\" Cursor=\"Arrow\" AutomationProperties.AutomationId=\"HorizontalScrollBar\" />\n\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n <Style\n x:Key=\"MyDVStyleExtend\"\n BasedOn=\"{StaticResource {x:Type DocumentViewer}}\"\n TargetType=\"{x:Type DocumentViewer}\">\n\n <Setter Property=\"Template\"> \n <Setter.Value>\n\n <ControlTemplate TargetType=\"DocumentViewer\">\n <Border BorderThickness=\"2,2,2,2\"\n BorderBrush=\"SlateBlue\" Focusable=\"False\">\n <Grid Background=\"{StaticResource GridBackground}\" \n KeyboardNavigation.TabNavigation=\"Local\">\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width =\"*\"/> \n </Grid.ColumnDefinitions> \n\n <ScrollViewer Style=\"{StaticResource CustomScrollPresenter}\" Grid.Column =\"0\" \n CanContentScroll=\"True\"\n HorizontalScrollBarVisibility=\"Auto\"\n x:Name=\"PART_ContentHost\"\n IsTabStop=\"True\"/>\n\n </Grid>\n </Border>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n\n </Style>\n private void ScrollContentPresenter_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n e.Handled = true;\n }\n"
},
{
"answer_id": 17471774,
"author": "Ben",
"author_id": 2550704,
"author_profile": "https://Stackoverflow.com/users/2550704",
"pm_score": 1,
"selected": false,
"text": "<DockPanel Name=\"pnlTouchTaker\" \n VerticalAlignment=\"Bottom\" HorizontalAlignment=\"Left\"\n Background=\"Transparent\">\n </DockPanel>\n"
},
{
"answer_id": 52221816,
"author": "Péter Hidvégi",
"author_id": 4994278,
"author_profile": "https://Stackoverflow.com/users/4994278",
"pm_score": 0,
"selected": false,
"text": "DocumentViewerInstance.GetType().GetProperty(\"IsSelectionEnabled\", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(DocumentViewerInstance, false, null);\n IsFocusable=false IsHitTestVisible = false"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,215 | <p>Considering the following table</p>
<p>I have a large table from which I can query to get the following table</p>
<pre><code>type no of times type occurs
101 450
102 562
103 245
111 25
112 28
113 21
</code></pre>
<p>Now suppose I wanted to get a table which shows me the sum of no of times type occurs
for type starting with 1 then starting with 10,11,12,13.......19 then starting with 2, 20,21, 22, 23...29 and so on.</p>
<p>Something like this </p>
<pre><code>1 1331 10 1257
11 74
12 ..
13 ..
.. ..
2 ... 20 ..
21 ..
</code></pre>
<p>Hope I am clear
Thanks </p>
| [
{
"answer_id": 415155,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<Style TargetType=\"{x:Type ScrollViewer}\" x:Key=\"CustomScrollPresenter\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ScrollViewer}\">\n <Grid Background=\"{TemplateBinding Panel.Background}\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n </Grid.RowDefinitions>\n <Rectangle Grid.Column=\"1\" Grid.Row=\"1\" Fill=\"{DynamicResource {x:Static SystemColors.ControlBrushKey}}\" />\n <ScrollContentPresenter \n PreviewMouseLeftButtonDown=\"ScrollContentPresenter_PreviewMouseLeftButtonDown\"\n Grid.Column=\"0\" \n Grid.Row=\"0\" \n Margin=\"{TemplateBinding Control.Padding}\" \n Content=\"{TemplateBinding ContentControl.Content}\" \n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" \n CanContentScroll=\"{TemplateBinding ScrollViewer.CanContentScroll}\" />\n <ScrollBar \n x:Name=\"PART_VerticalScrollBar\"\n Grid.Column=\"1\" \n Grid.Row=\"0\" \n Minimum=\"0\" \n Maximum=\"{TemplateBinding ScrollViewer.ScrollableHeight}\" \n ViewportSize=\"{TemplateBinding ScrollViewer.ViewportHeight}\" \n Value=\"{Binding Path=VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}\" \n Visibility=\"{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}\" \n Cursor=\"Arrow\" AutomationProperties.AutomationId=\"VerticalScrollBar\" />\n <ScrollBar \n x:Name=\"PART_HorizontalScrollBar\"\n Orientation=\"Horizontal\" Grid.Column=\"0\" Grid.Row=\"1\" Minimum=\"0\" \n Maximum=\"{TemplateBinding ScrollViewer.ScrollableWidth}\" ViewportSize=\"{TemplateBinding ScrollViewer.ViewportWidth}\" Value=\"{Binding Path=HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}\" Visibility=\"{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}\" Cursor=\"Arrow\" AutomationProperties.AutomationId=\"HorizontalScrollBar\" />\n\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n <Style\n x:Key=\"MyDVStyleExtend\"\n BasedOn=\"{StaticResource {x:Type DocumentViewer}}\"\n TargetType=\"{x:Type DocumentViewer}\">\n\n <Setter Property=\"Template\"> \n <Setter.Value>\n\n <ControlTemplate TargetType=\"DocumentViewer\">\n <Border BorderThickness=\"2,2,2,2\"\n BorderBrush=\"SlateBlue\" Focusable=\"False\">\n <Grid Background=\"{StaticResource GridBackground}\" \n KeyboardNavigation.TabNavigation=\"Local\">\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width =\"*\"/> \n </Grid.ColumnDefinitions> \n\n <ScrollViewer Style=\"{StaticResource CustomScrollPresenter}\" Grid.Column =\"0\" \n CanContentScroll=\"True\"\n HorizontalScrollBarVisibility=\"Auto\"\n x:Name=\"PART_ContentHost\"\n IsTabStop=\"True\"/>\n\n </Grid>\n </Border>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n\n </Style>\n private void ScrollContentPresenter_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n e.Handled = true;\n }\n"
},
{
"answer_id": 17471774,
"author": "Ben",
"author_id": 2550704,
"author_profile": "https://Stackoverflow.com/users/2550704",
"pm_score": 1,
"selected": false,
"text": "<DockPanel Name=\"pnlTouchTaker\" \n VerticalAlignment=\"Bottom\" HorizontalAlignment=\"Left\"\n Background=\"Transparent\">\n </DockPanel>\n"
},
{
"answer_id": 52221816,
"author": "Péter Hidvégi",
"author_id": 4994278,
"author_profile": "https://Stackoverflow.com/users/4994278",
"pm_score": 0,
"selected": false,
"text": "DocumentViewerInstance.GetType().GetProperty(\"IsSelectionEnabled\", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(DocumentViewerInstance, false, null);\n IsFocusable=false IsHitTestVisible = false"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
368,219 | <p>I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.</p>
<p>With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.</p>
<p>At the moment the code looks like (code simplified to aid clarity!): </p>
<pre><code><select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</code></pre>
<p>What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!</p>
<p>Any assistance much appreciated :)</p>
<p>Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!</p>
| [
{
"answer_id": 368232,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": true,
"text": "onchange <html>\n <head>\n <script type=\"text/javascript\">\n window.onload = function() {\n var eSelect = document.getElementById('transfer_reason');\n var optOtherReason = document.getElementById('otherdetail');\n eSelect.onchange = function() {\n if(eSelect.selectedIndex === 2) {\n optOtherReason.style.display = 'block';\n } else {\n optOtherReason.style.display = 'none';\n }\n }\n }\n </script>\n </head>\n <body>\n <select id=\"transfer_reason\" name=\"transfer_reason\">\n <option value=\"x\">Reason 1</option>\n <option value=\"y\">Reason 2</option>\n <option value=\"other\">Other Reason</option>\n </select>\n <div id=\"otherdetail\" style=\"display: none;\">More Detail Here Please</div>\n</body>\n</html>\n"
},
{
"answer_id": 368292,
"author": "suitedupgeek",
"author_id": 42428,
"author_profile": "https://Stackoverflow.com/users/42428",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\nwindow.onload = function() {\n var eSelect = document.getElementById('transfer_reason');\n var optOtherReason = document.getElementById('otherdetail');\n eSelect.onchange = function() {\n if(eSelect.value === \"Other\") {\n optOtherReason.style.display = 'block';\n } else {\n optOtherReason.style.display = 'none';\n }\n }\n }\n </script>\n"
},
{
"answer_id": 368298,
"author": "Tuminoid",
"author_id": 40657,
"author_profile": "https://Stackoverflow.com/users/40657",
"pm_score": 3,
"selected": false,
"text": "<select id=\"transfer_reason\" name=\"transfer_reason\" onchange=\"document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';\">\n <option value=\"x\">Reason 1</option>\n <option value=\"y\">Reason 2</option>\n <option value=\"other\">Other Reason</option>\n</select>\n<div id=\"otherdetail\" style=\"display: none;\">More Detail Here Please</div>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42428/"
] |
368,253 | <p>I have a <code>NSTimer</code> object that I need to invalidate if a user taps on a button or if they exit a view.</p>
<p>So I have:</p>
<pre><code>[myNSTimer invalidate];
</code></pre>
<p>inside my button handler and inside <code>viewWillDisappear</code>. If user taps on a button and then exists a view the app throws an exception because <code>myNSTimer</code> has already been invalidated.
What I need to do in the <code>viewWillDisappear</code> method is check if the <code>myNSTimer</code> has been invalidated or not. How do I do that?</p>
<p>I've tried:</p>
<pre><code>if(myNSTimer != nil)
[myNSTimer invalidate];
</code></pre>
<p>but that didn't work.</p>
| [
{
"answer_id": 368263,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 6,
"selected": true,
"text": "release -[NSTimer isValid] -invalidate -isValid"
},
{
"answer_id": 368379,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 3,
"selected": false,
"text": "[myNSTimer invalidate]; \nmyNSTimer = nil;\n"
},
{
"answer_id": 12835501,
"author": "Yunus Nedim Mehel",
"author_id": 936957,
"author_profile": "https://Stackoverflow.com/users/936957",
"pm_score": 2,
"selected": false,
"text": "[timer invalidate];\n[timer release];\ntimer = nil;\n timer = [[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(aSelector) userInfo:nil repeats:YES] retain];\n"
},
{
"answer_id": 36731072,
"author": "Crashalot",
"author_id": 144088,
"author_profile": "https://Stackoverflow.com/users/144088",
"pm_score": 1,
"selected": false,
"text": "if timer.valid {\n timer.invalidate()\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44091/"
] |
368,260 | <p>Sometimes Eclipse comes up saying "hey you should debug this line!!!" but doesn't actually close the program. I can then continue to play big two, and even go through the same events that caused the error the first time and get another error box to pop up!</p>
<p>The bug is simple, I'll fix it, I just want to know why some bugs are terminal and some are not? What's the difference?</p>
| [
{
"answer_id": 368297,
"author": "Bent André Solheim",
"author_id": 44380,
"author_profile": "https://Stackoverflow.com/users/44380",
"pm_score": 2,
"selected": false,
"text": "public class ThreadTest {\n\n public static void main(String[] args) {\n\n Runnable test = new Runnable() {\n\n public void run() {\n try {\n System.out.println(\"Sleeping\");\n Thread.sleep(5000);\n System.out.println(\"Slept\");\n } catch (InterruptedException e) {\n }\n }\n };\n\n Thread t = new Thread(test);\n //t.setDaemon(true);\n t.start();\n\n System.out.println(\"Waiting to fail\");\n throw new RuntimeException(\"Error\");\n }\n}\n"
},
{
"answer_id": 368328,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "Account -= Interest;\n"
},
{
"answer_id": 368860,
"author": "Jared",
"author_id": 44757,
"author_profile": "https://Stackoverflow.com/users/44757",
"pm_score": 2,
"selected": false,
"text": "public class TestMain {\n public static void main(String[] args) {\n Thread t1 = new Thread() {\n public void run() {\n while(true) {\n System.out.println(\"A\");\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"t1 interrupted.\");\n }\n }\n }\n };\n t1.setDaemon(false);\n\n Thread t2 = new Thread() {\n public void run() {\n int count = 0;\n while(true) {\n if(count < 5) {\n System.out.println(\"B\");\n count++;\n } else {\n throw new RuntimeException(\"Intentional RuntimeException!\");\n }\n try {\n Thread.sleep(2000);\n } catch (InterruptedException e) {\n System.out.println(\"t2 interrupted.\");\n }\n }\n }\n };\n t2.setDaemon(false);\n t1.start();\n t2.start();\n }\n}\n t1.setDaemon(false) t1.setDaemon(true)"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
368,262 | <p>I am compiling a c++ static library in vs2008, and in the solution i also have a startup project that uses the lib, and that works fine. </p>
<p>But when using the lib in another solution i get an run-time check failure.
"The value of ESP was not properly saved across a functioncall"
Stepping through the code i noticed a function foo() jumping to bar() instead right before the crash. The functions in question are just regular functions and no function pointers.</p>
<p>Anyone has any clue what might be going on, and why it works when using the lib's from the same solution?</p>
<p>edit: the functions (methods) are part of a class, if that helps.</p>
| [
{
"answer_id": 370228,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 5,
"selected": true,
"text": "class Foo { virtual void f(); };\n class Foo { virtual void g(); virtual void f(); };\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46357/"
] |
368,265 | <p>I want to make a very simple event bus which will allow any client to subscribe to a particular type of event and when any publisher pushes an event on the bus using <code>EventBus.PushEvent()</code> method only the clients that subscribed to that particular event type will get the event.</p>
<p>I am using C# and .NET 2.0.</p>
| [
{
"answer_id": 1681066,
"author": "Volker von Einem",
"author_id": 104631,
"author_profile": "https://Stackoverflow.com/users/104631",
"pm_score": 2,
"selected": false,
"text": "[Publishes(\"TimerTick\")]\npublic event EventHandler Expired;\nprivate void OnTick(Object sender, EventArgs e)\n{\n timer.Stop();\n OnExpired(this);\n}\n\n[SubscribesTo(\"TimerTick\")]\npublic void OnTimerExpired(Object sender, EventArgs e)\n{\n EventHandler handlers = ChangeLight;\n if(handlers != null)\n {\n handlers(this, EventArgs.Empty);\n }\n currentLight = ( currentLight + 1 ) % 3;\n timer.Duration = lightTimes[currentLight];\n timer.Start();\n}\n"
},
{
"answer_id": 8560275,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 5,
"selected": false,
"text": "messageHub.Publish(new MyMessage());\n messageHub.Subscribe<MyMessage>((m) => { MessageBox.Show(\"Message Received!\"); });\nmessageHub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show(\"Message Received!\"); }, (m) => m.Content == \"Testing\");\n Install-Package TinyMessenger\n"
},
{
"answer_id": 23489097,
"author": "duo",
"author_id": 1005138,
"author_profile": "https://Stackoverflow.com/users/1005138",
"pm_score": 3,
"selected": false,
"text": "public class EventBus\n{\n public static EventBus Instance { get { return instance ?? (instance = new EventBus()); } }\n\n public void Register(object listener)\n {\n if (!listeners.Any(l => l.Listener == listener))\n listeners.Add(new EventListenerWrapper(listener));\n }\n\n public void Unregister(object listener)\n {\n listeners.RemoveAll(l => l.Listener == listener);\n }\n\n public void PostEvent(object e)\n {\n listeners.Where(l => l.EventType == e.GetType()).ToList().ForEach(l => l.PostEvent(e));\n }\n\n private static EventBus instance;\n\n private EventBus() { }\n\n private List<EventListenerWrapper> listeners = new List<EventListenerWrapper>();\n\n private class EventListenerWrapper\n {\n public object Listener { get; private set; }\n public Type EventType { get; private set; }\n\n private MethodBase method;\n\n public EventListenerWrapper(object listener)\n {\n Listener = listener;\n\n Type type = listener.GetType();\n\n method = type.GetMethod(\"OnEvent\");\n if (method == null)\n throw new ArgumentException(\"Class \" + type.Name + \" does not containt method OnEvent\");\n\n ParameterInfo[] parameters = method.GetParameters();\n if (parameters.Length != 1)\n throw new ArgumentException(\"Method OnEvent of class \" + type.Name + \" have invalid number of parameters (should be one)\");\n\n EventType = parameters[0].ParameterType;\n }\n\n public void PostEvent(object e)\n {\n method.Invoke(Listener, new[] { e });\n }\n } \n}\n public class OnProgressChangedEvent\n{\n\n public int Progress { get; private set; }\n\n public OnProgressChangedEvent(int progress)\n {\n Progress = progress;\n }\n}\n\npublic class SomeForm : Form\n{\n // ...\n\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n EventBus.Instance.Register(this);\n }\n\n public void OnEvent(OnProgressChangedEvent e)\n {\n progressBar.Value = e.Progress;\n }\n\n protected override void OnClosed(EventArgs e)\n {\n base.OnClosed(e);\n EventBus.Instance.Unregister(this);\n }\n}\n\npublic class SomeWorkerSomewhere\n{\n void OnDoWork()\n {\n // ...\n\n EventBus.Instance.PostEvent(new OnProgressChangedEvent(progress));\n\n // ...\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46358/"
] |
368,271 | <p>I would like to know how to modify the below code to strip <code>=20</code> characters at the end of many lines, and mainly to sort the messages chronologically from first received or sent to last. I am not sure if this would be an internal Perl routine or not. </p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
use Mail::Box::Manager;
my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
access => 'r',
);
my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";
for my $msg ($folder->messages)
{
my $to = join( ', ', map { $_->format } $msg->to );
my $from = join( ', ', map { $_->format } $msg->from );
my $date = localtime( $msg->timestamp );
my $subject = $msg->subject;
my $body = $msg->body;
# Strip all quoted text
$body =~ s/^>.*$//msg;
print <<"";
From: $from
To: $to
Date: $date
$body
}
</code></pre>
<p>When trying to run this I get the following errors:</p>
<p>"my" variable $msg masks earlier declaration in same scope at x.pl line 16.
syntax error at x.pl line 15, near ") ) "
syntax error at x.pl line 31, near "}"
(Might be a runaway multi-line << string starting on line 25)
Execution of x.pl aborted due to compilation errors.</p>
<p>I am not sure as to why, as the syntax seems fine.</p>
| [
{
"answer_id": 368309,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 3,
"selected": true,
"text": "=20 $msg->body $msg->decoded->string Mail::Message::timestamp ...\nfor my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages) )\n...\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
368,280 | <p>As made clear in update 3 on <a href="https://stackoverflow.com/questions/367440/javascript-associative-array-without-tostring-etc#367454">this answer</a>, this notation:</p>
<pre><code>var hash = {};
hash[X]
</code></pre>
<p>does not actually hash the object <code>X</code>; it actually just converts <code>X</code> to a string (via <code>.toString()</code> if it's an object, or some other built-in conversions for various primitive types) and then looks that string up, without hashing it, in "<code>hash</code>". Object equality is also not checked - if two different objects have the same string conversion, they will just overwrite each other.</p>
<p>Given this - are there any efficient implementations of hashmaps in JavaScript?</p>
<p>(For example, the second Google result of <a href="http://www.google.com/search?rlz=1C1GGLS_en-USUS299US303&sourceid=chrome&ie=UTF-8&q=javascript%20hashmap" rel="noreferrer"><code>javascript hashmap</code></a> yields an implementation which is O(n) for any operation. Various other results ignore the fact that different objects with equivalent string representations overwrite each other.</p>
| [
{
"answer_id": 368504,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 10,
"selected": true,
"text": "var key = function(obj){\n // Some unique object-dependent key\n return obj.totallyUniqueEmployeeIdKey; // Just an example\n};\n\nvar dict = {};\n\ndict[key(obj1)] = obj1;\ndict[key(obj2)] = obj2;\n Object Object dict[key] = value"
},
{
"answer_id": 369009,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 4,
"selected": false,
"text": "HashMap = function(){\n this._dict = [];\n}\n\nHashMap.prototype._get = function(key){\n for(var i=0, couplet; couplet = this._dict[i]; i++){\n if(couplet[0] === key){\n return couplet;\n }\n }\n}\n\nHashMap.prototype.put = function(key, value){\n var couplet = this._get(key);\n if(couplet){\n couplet[1] = value;\n }else{\n this._dict.push([key, value]);\n }\n return this; // for chaining\n}\nHashMap.prototype.get = function(key){\n var couplet = this._get(key);\n if(couplet){\n return couplet[1];\n }\n}\n var color = {}; // Unique object instance\nvar shape = {}; // Unique object instance\nvar map = new HashMap();\nmap.put(color, \"blue\");\nmap.put(shape, \"round\");\nconsole.log(\"Item is\", map.get(color), \"and\", map.get(shape));\n HashMap = function(){\n this._dict = {};\n}\n\nHashMap.prototype._shared = {id: 1};\nHashMap.prototype.put = function put(key, value){\n if(typeof key == \"object\"){\n if(!key.hasOwnProperty._id){\n key.hasOwnProperty = function(key){\n return Object.prototype.hasOwnProperty.call(this, key);\n }\n key.hasOwnProperty._id = this._shared.id++;\n }\n this._dict[key.hasOwnProperty._id] = value;\n }else{\n this._dict[key] = value;\n }\n return this; // for chaining\n}\n\nHashMap.prototype.get = function get(key){\n if(typeof key == \"object\"){\n return this._dict[key.hasOwnProperty._id];\n }\n return this._dict[key];\n}\n"
},
{
"answer_id": 383540,
"author": "Christoph",
"author_id": 48015,
"author_profile": "https://Stackoverflow.com/users/48015",
"pm_score": 7,
"selected": false,
"text": "toString() 5 '5' toString() '[object Object]' hasOwnProperty() __hash function hash(value) {\n return (typeof value) + ' ' + (value instanceof Object ?\n (value.__hash || (value.__hash = ++arguments.callee.current)) :\n value.toString());\n}\n\nhash.current = 0;\n Map Map hash() // Linking the key-value-pairs is optional.\n// If no argument is provided, linkItems === undefined, i.e. !== false\n// --> linking will be enabled\nfunction Map(linkItems) {\n this.current = undefined;\n this.size = 0;\n\n if(linkItems === false)\n this.disableLinking();\n}\n\nMap.noop = function() {\n return this;\n};\n\nMap.illegal = function() {\n throw new Error(\"illegal operation for maps without linking\");\n};\n\n// Map initialisation from an existing object\n// doesn't add inherited properties if not explicitly instructed to:\n// omitting foreignKeys means foreignKeys === undefined, i.e. == false\n// --> inherited properties won't be added\nMap.from = function(obj, foreignKeys) {\n var map = new Map;\n\n for(var prop in obj) {\n if(foreignKeys || obj.hasOwnProperty(prop))\n map.put(prop, obj[prop]);\n }\n\n return map;\n};\n\nMap.prototype.disableLinking = function() {\n this.link = Map.noop;\n this.unlink = Map.noop;\n this.disableLinking = Map.noop;\n this.next = Map.illegal;\n this.key = Map.illegal;\n this.value = Map.illegal;\n this.removeAll = Map.illegal;\n\n return this;\n};\n\n// Overwrite in Map instance if necessary\nMap.prototype.hash = function(value) {\n return (typeof value) + ' ' + (value instanceof Object ?\n (value.__hash || (value.__hash = ++arguments.callee.current)) :\n value.toString());\n};\n\nMap.prototype.hash.current = 0;\n\n// --- Mapping functions\n\nMap.prototype.get = function(key) {\n var item = this[this.hash(key)];\n return item === undefined ? undefined : item.value;\n};\n\nMap.prototype.put = function(key, value) {\n var hash = this.hash(key);\n\n if(this[hash] === undefined) {\n var item = { key : key, value : value };\n this[hash] = item;\n\n this.link(item);\n ++this.size;\n }\n else this[hash].value = value;\n\n return this;\n};\n\nMap.prototype.remove = function(key) {\n var hash = this.hash(key);\n var item = this[hash];\n\n if(item !== undefined) {\n --this.size;\n this.unlink(item);\n\n delete this[hash];\n }\n\n return this;\n};\n\n// Only works if linked\nMap.prototype.removeAll = function() {\n while(this.size)\n this.remove(this.key());\n\n return this;\n};\n\n// --- Linked list helper functions\n\nMap.prototype.link = function(item) {\n if(this.size == 0) {\n item.prev = item;\n item.next = item;\n this.current = item;\n }\n else {\n item.prev = this.current.prev;\n item.prev.next = item;\n item.next = this.current;\n this.current.prev = item;\n }\n};\n\nMap.prototype.unlink = function(item) {\n if(this.size == 0)\n this.current = undefined;\n else {\n item.prev.next = item.next;\n item.next.prev = item.prev;\n if(item === this.current)\n this.current = item.next;\n }\n};\n\n// --- Iterator functions - only work if map is linked\n\nMap.prototype.next = function() {\n this.current = this.current.next;\n};\n\nMap.prototype.key = function() {\n return this.current.key;\n};\n\nMap.prototype.value = function() {\n return this.current.value;\n};\n var map = new Map;\n\nmap.put('spam', 'eggs').\n put('foo', 'bar').\n put('foo', 'baz').\n put({}, 'an object').\n put({}, 'another object').\n put(5, 'five').\n put(5, 'five again').\n put('5', 'another five');\n\nfor(var i = 0; i++ < map.size; map.next())\n document.writeln(map.hash(map.key()) + ' : ' + map.value());\n string spam : eggs\nstring foo : baz\nobject 1 : an object\nobject 2 : another object\nnumber 5 : five again\nstring 5 : another five\n toString() toString() toString() Object.prototype Map"
},
{
"answer_id": 384552,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 2,
"selected": false,
"text": "hash[\"X\"] hash.X hash[x] eval(\"hash.\"+x.toString())"
},
{
"answer_id": 1106232,
"author": "Lambder",
"author_id": 135892,
"author_profile": "https://Stackoverflow.com/users/135892",
"pm_score": 3,
"selected": false,
"text": "/*\n =====================================================================\n @license MIT\n @author Lambder\n @copyright 2009 Lambder.\n @end\n =====================================================================\n */\nvar HashMap = function() {\n this.initialize();\n}\n\nHashMap.prototype = {\n hashkey_prefix: \"<#HashMapHashkeyPerfix>\",\n hashcode_field: \"<#HashMapHashkeyPerfix>\",\n\n initialize: function() {\n this.backing_hash = {};\n this.code = 0;\n },\n /*\n Maps value to key returning previous association\n */\n put: function(key, value) {\n var prev;\n if (key && value) {\n var hashCode = key[this.hashcode_field];\n if (hashCode) {\n prev = this.backing_hash[hashCode];\n } else {\n this.code += 1;\n hashCode = this.hashkey_prefix + this.code;\n key[this.hashcode_field] = hashCode;\n }\n this.backing_hash[hashCode] = value;\n }\n return prev;\n },\n /*\n Returns value associated with given key\n */\n get: function(key) {\n var value;\n if (key) {\n var hashCode = key[this.hashcode_field];\n if (hashCode) {\n value = this.backing_hash[hashCode];\n }\n }\n return value;\n },\n /*\n Deletes association by given key.\n Returns true if the association existed, false otherwise\n */\n del: function(key) {\n var success = false;\n if (key) {\n var hashCode = key[this.hashcode_field];\n if (hashCode) {\n var prev = this.backing_hash[hashCode];\n this.backing_hash[hashCode] = undefined;\n if(prev !== undefined)\n success = true;\n }\n }\n return success;\n }\n}\n\n//// Usage\n\n// Creation\n\nvar my_map = new HashMap();\n\n// Insertion\n\nvar a_key = {};\nvar a_value = {struct: \"structA\"};\nvar b_key = {};\nvar b_value = {struct: \"structB\"};\nvar c_key = {};\nvar c_value = {struct: \"structC\"};\n\nmy_map.put(a_key, a_value);\nmy_map.put(b_key, b_value);\nvar prev_b = my_map.put(b_key, c_value);\n\n// Retrieval\n\nif(my_map.get(a_key) !== a_value){\n throw(\"fail1\")\n}\nif(my_map.get(b_key) !== c_value){\n throw(\"fail2\")\n}\nif(prev_b !== b_value){\n throw(\"fail3\")\n}\n\n// Deletion\n\nvar a_existed = my_map.del(a_key);\nvar c_existed = my_map.del(c_key);\nvar a2_existed = my_map.del(a_key);\n\nif(a_existed !== true){\n throw(\"fail4\")\n}\nif(c_existed !== false){\n throw(\"fail5\")\n}\nif(a2_existed !== false){\n throw(\"fail6\")\n}\n"
},
{
"answer_id": 5577422,
"author": "Michael Spector",
"author_id": 398309,
"author_profile": "https://Stackoverflow.com/users/398309",
"pm_score": 4,
"selected": false,
"text": "function HashMap() {\n this.buckets = {};\n}\n\nHashMap.prototype.put = function(key, value) {\n var hashCode = key.hashCode();\n var bucket = this.buckets[hashCode];\n if (!bucket) {\n bucket = new Array();\n this.buckets[hashCode] = bucket;\n }\n for (var i = 0; i < bucket.length; ++i) {\n if (bucket[i].key.equals(key)) {\n bucket[i].value = value;\n return;\n }\n }\n bucket.push({ key: key, value: value });\n}\n\nHashMap.prototype.get = function(key) {\n var hashCode = key.hashCode();\n var bucket = this.buckets[hashCode];\n if (!bucket) {\n return null;\n }\n for (var i = 0; i < bucket.length; ++i) {\n if (bucket[i].key.equals(key)) {\n return bucket[i].value;\n }\n }\n}\n\nHashMap.prototype.keys = function() {\n var keys = new Array();\n for (var hashKey in this.buckets) {\n var bucket = this.buckets[hashKey];\n for (var i = 0; i < bucket.length; ++i) {\n keys.push(bucket[i].key);\n }\n }\n return keys;\n}\n\nHashMap.prototype.values = function() {\n var values = new Array();\n for (var hashKey in this.buckets) {\n var bucket = this.buckets[hashKey];\n for (var i = 0; i < bucket.length; ++i) {\n values.push(bucket[i].value);\n }\n }\n return values;\n}\n"
},
{
"answer_id": 11320927,
"author": "g00dnatur3",
"author_id": 1500191,
"author_profile": "https://Stackoverflow.com/users/1500191",
"pm_score": 2,
"selected": false,
"text": "var map = new Map(); // Creates an \"in-memory\" map\nvar map = new Map(\"storageId\"); // Creates a map that is loaded/persisted using html5 storage\n function Map(storageId) {\n this.current = undefined;\n this.size = 0;\n this.storageId = storageId;\n if (this.storageId) {\n this.keys = new Array();\n this.disableLinking();\n }\n}\n\nMap.noop = function() {\n return this;\n};\n\nMap.illegal = function() {\n throw new Error(\"illegal operation for maps without linking\");\n};\n\n// Map initialisation from an existing object\n// doesn't add inherited properties if not explicitly instructed to:\n// omitting foreignKeys means foreignKeys === undefined, i.e. == false\n// --> inherited properties won't be added\nMap.from = function(obj, foreignKeys) {\n var map = new Map;\n for(var prop in obj) {\n if(foreignKeys || obj.hasOwnProperty(prop))\n map.put(prop, obj[prop]);\n }\n return map;\n};\n\nMap.prototype.disableLinking = function() {\n this.link = Map.noop;\n this.unlink = Map.noop;\n this.disableLinking = Map.noop;\n\n this.next = Map.illegal;\n this.key = Map.illegal;\n this.value = Map.illegal;\n// this.removeAll = Map.illegal;\n\n\n return this;\n};\n\n// Overwrite in Map instance if necessary\nMap.prototype.hash = function(value) {\n return (typeof value) + ' ' + (value instanceof Object ?\n (value.__hash || (value.__hash = ++arguments.callee.current)) :\n value.toString());\n};\n\nMap.prototype.hash.current = 0;\n\n// --- Mapping functions\n\nMap.prototype.get = function(key) {\n var item = this[this.hash(key)];\n if (item === undefined) {\n if (this.storageId) {\n try {\n var itemStr = localStorage.getItem(this.storageId + key);\n if (itemStr && itemStr !== 'undefined') {\n item = JSON.parse(itemStr);\n this[this.hash(key)] = item;\n this.keys.push(key);\n ++this.size;\n }\n } catch (e) {\n console.log(e);\n }\n }\n }\n return item === undefined ? undefined : item.value;\n};\n\nMap.prototype.put = function(key, value) {\n var hash = this.hash(key);\n\n if(this[hash] === undefined) {\n var item = { key : key, value : value };\n this[hash] = item;\n\n this.link(item);\n ++this.size;\n }\n else this[hash].value = value;\n if (this.storageId) {\n this.keys.push(key);\n try {\n localStorage.setItem(this.storageId + key, JSON.stringify(this[hash]));\n } catch (e) {\n console.log(e);\n }\n }\n return this;\n};\n\nMap.prototype.remove = function(key) {\n var hash = this.hash(key);\n var item = this[hash];\n if(item !== undefined) {\n --this.size;\n this.unlink(item);\n\n delete this[hash];\n }\n if (this.storageId) {\n try {\n localStorage.setItem(this.storageId + key, undefined);\n } catch (e) {\n console.log(e);\n }\n }\n return this;\n};\n\n// Only works if linked\nMap.prototype.removeAll = function() {\n if (this.storageId) {\n for (var i=0; i<this.keys.length; i++) {\n this.remove(this.keys[i]);\n }\n this.keys.length = 0;\n } else {\n while(this.size)\n this.remove(this.key());\n }\n return this;\n};\n\n// --- Linked list helper functions\n\nMap.prototype.link = function(item) {\n if (this.storageId) {\n return;\n }\n if(this.size == 0) {\n item.prev = item;\n item.next = item;\n this.current = item;\n }\n else {\n item.prev = this.current.prev;\n item.prev.next = item;\n item.next = this.current;\n this.current.prev = item;\n }\n};\n\nMap.prototype.unlink = function(item) {\n if (this.storageId) {\n return;\n }\n if(this.size == 0)\n this.current = undefined;\n else {\n item.prev.next = item.next;\n item.next.prev = item.prev;\n if(item === this.current)\n this.current = item.next;\n }\n};\n\n// --- Iterator functions - only work if map is linked\n\nMap.prototype.next = function() {\n this.current = this.current.next;\n};\n\nMap.prototype.key = function() {\n if (this.storageId) {\n return undefined;\n } else {\n return this.current.key;\n }\n};\n\nMap.prototype.value = function() {\n if (this.storageId) {\n return undefined;\n }\n return this.current.value;\n};\n"
},
{
"answer_id": 11412442,
"author": "Milos Cuculovic",
"author_id": 1018270,
"author_profile": "https://Stackoverflow.com/users/1018270",
"pm_score": 5,
"selected": false,
"text": "var map = {\n 'map_name_1': map_value_1,\n 'map_name_2': map_value_2,\n 'map_name_3': map_value_3,\n 'map_name_4': map_value_4\n }\n alert(map['map_name_1']); // Gives the value of map_value_1\n\n... etc. ...\n"
},
{
"answer_id": 18320379,
"author": "Ingo Bürk",
"author_id": 1675492,
"author_profile": "https://Stackoverflow.com/users/1675492",
"pm_score": 1,
"selected": false,
"text": "HashMap ArrayList qx.Class.define( 'jsava.util.HashMap', {\n extend: jsava.util.AbstractMap,\n implement: [jsava.util.Map, jsava.io.Serializable, jsava.lang.Cloneable],\n\n construct: function () {\n var args = Array.prototype.slice.call( arguments ),\n initialCapacity = this.self( arguments ).DEFAULT_INITIAL_CAPACITY,\n loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;\n\n switch( args.length ) {\n case 1:\n if( qx.Class.implementsInterface( args[0], jsava.util.Map ) ) {\n initialCapacity = Math.max( ((args[0].size() / this.self( arguments ).DEFAULT_LOAD_FACTOR) | 0) + 1,\n this.self( arguments ).DEFAULT_INITIAL_CAPACITY );\n loadFactor = this.self( arguments ).DEFAULT_LOAD_FACTOR;\n } else {\n initialCapacity = args[0];\n }\n break;\n case 2:\n initialCapacity = args[0];\n loadFactor = args[1];\n break;\n }\n\n if( initialCapacity < 0 ) {\n throw new jsava.lang.IllegalArgumentException( 'Illegal initial capacity: ' + initialCapacity );\n }\n if( initialCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {\n initialCapacity = this.self( arguments ).MAXIMUM_CAPACITY;\n }\n if( loadFactor <= 0 || isNaN( loadFactor ) ) {\n throw new jsava.lang.IllegalArgumentException( 'Illegal load factor: ' + loadFactor );\n }\n\n var capacity = 1;\n while( capacity < initialCapacity ) {\n capacity <<= 1;\n }\n\n this._loadFactor = loadFactor;\n this._threshold = (capacity * loadFactor) | 0;\n this._table = jsava.JsavaUtils.emptyArrayOfGivenSize( capacity, null );\n this._init();\n },\n\n statics: {\n serialVersionUID: 1,\n\n DEFAULT_INITIAL_CAPACITY: 16,\n MAXIMUM_CAPACITY: 1 << 30,\n DEFAULT_LOAD_FACTOR: 0.75,\n\n _hash: function (hash) {\n hash ^= (hash >>> 20) ^ (hash >>> 12);\n return hash ^ (hash >>> 7) ^ (hash >>> 4);\n },\n\n _indexFor: function (hashCode, length) {\n return hashCode & (length - 1);\n },\n\n Entry: qx.Class.define( 'jsava.util.HashMap.Entry', {\n extend: jsava.lang.Object,\n implement: [jsava.util.Map.Entry],\n\n construct: function (hash, key, value, nextEntry) {\n this._value = value;\n this._next = nextEntry;\n this._key = key;\n this._hash = hash;\n },\n\n members: {\n _key: null,\n _value: null,\n /** @type jsava.util.HashMap.Entry */\n _next: null,\n /** @type Number */\n _hash: 0,\n\n getKey: function () {\n return this._key;\n },\n\n getValue: function () {\n return this._value;\n },\n\n setValue: function (newValue) {\n var oldValue = this._value;\n this._value = newValue;\n return oldValue;\n },\n\n equals: function (obj) {\n if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.HashMap.Entry ) ) {\n return false;\n }\n\n /** @type jsava.util.HashMap.Entry */\n var entry = obj,\n key1 = this.getKey(),\n key2 = entry.getKey();\n if( key1 === key2 || (key1 !== null && key1.equals( key2 )) ) {\n var value1 = this.getValue(),\n value2 = entry.getValue();\n if( value1 === value2 || (value1 !== null && value1.equals( value2 )) ) {\n return true;\n }\n }\n\n return false;\n },\n\n hashCode: function () {\n return (this._key === null ? 0 : this._key.hashCode()) ^\n (this._value === null ? 0 : this._value.hashCode());\n },\n\n toString: function () {\n return this.getKey() + '=' + this.getValue();\n },\n\n /**\n * This method is invoked whenever the value in an entry is\n * overwritten by an invocation of put(k,v) for a key k that's already\n * in the HashMap.\n */\n _recordAccess: function (map) {\n },\n\n /**\n * This method is invoked whenever the entry is\n * removed from the table.\n */\n _recordRemoval: function (map) {\n }\n }\n } )\n },\n\n members: {\n /** @type jsava.util.HashMap.Entry[] */\n _table: null,\n /** @type Number */\n _size: 0,\n /** @type Number */\n _threshold: 0,\n /** @type Number */\n _loadFactor: 0,\n /** @type Number */\n _modCount: 0,\n /** @implements jsava.util.Set */\n __entrySet: null,\n\n /**\n * Initialization hook for subclasses. This method is called\n * in all constructors and pseudo-constructors (clone, readObject)\n * after HashMap has been initialized but before any entries have\n * been inserted. (In the absence of this method, readObject would\n * require explicit knowledge of subclasses.)\n */\n _init: function () {\n },\n\n size: function () {\n return this._size;\n },\n\n isEmpty: function () {\n return this._size === 0;\n },\n\n get: function (key) {\n if( key === null ) {\n return this.__getForNullKey();\n }\n\n var hash = this.self( arguments )._hash( key.hashCode() );\n for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];\n entry !== null; entry = entry._next ) {\n /** @type jsava.lang.Object */\n var k;\n if( entry._hash === hash && ((k = entry._key) === key || key.equals( k )) ) {\n return entry._value;\n }\n }\n\n return null;\n },\n\n __getForNullKey: function () {\n for( var entry = this._table[0]; entry !== null; entry = entry._next ) {\n if( entry._key === null ) {\n return entry._value;\n }\n }\n\n return null;\n },\n\n containsKey: function (key) {\n return this._getEntry( key ) !== null;\n },\n\n _getEntry: function (key) {\n var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() );\n for( var entry = this._table[this.self( arguments )._indexFor( hash, this._table.length )];\n entry !== null; entry = entry._next ) {\n /** @type jsava.lang.Object */\n var k;\n if( entry._hash === hash\n && ( ( k = entry._key ) === key || ( key !== null && key.equals( k ) ) ) ) {\n return entry;\n }\n }\n\n return null;\n },\n\n put: function (key, value) {\n if( key === null ) {\n return this.__putForNullKey( value );\n }\n\n var hash = this.self( arguments )._hash( key.hashCode() ),\n i = this.self( arguments )._indexFor( hash, this._table.length );\n for( var entry = this._table[i]; entry !== null; entry = entry._next ) {\n /** @type jsava.lang.Object */\n var k;\n if( entry._hash === hash && ( (k = entry._key) === key || key.equals( k ) ) ) {\n var oldValue = entry._value;\n entry._value = value;\n entry._recordAccess( this );\n return oldValue;\n }\n }\n\n this._modCount++;\n this._addEntry( hash, key, value, i );\n return null;\n },\n\n __putForNullKey: function (value) {\n for( var entry = this._table[0]; entry !== null; entry = entry._next ) {\n if( entry._key === null ) {\n var oldValue = entry._value;\n entry._value = value;\n entry._recordAccess( this );\n return oldValue;\n }\n }\n\n this._modCount++;\n this._addEntry( 0, null, value, 0 );\n return null;\n },\n\n __putForCreate: function (key, value) {\n var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),\n i = this.self( arguments )._indexFor( hash, this._table.length );\n for( var entry = this._table[i]; entry !== null; entry = entry._next ) {\n /** @type jsava.lang.Object */\n var k;\n if( entry._hash === hash\n && ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {\n entry._value = value;\n return;\n }\n }\n\n this._createEntry( hash, key, value, i );\n },\n\n __putAllForCreate: function (map) {\n var iterator = map.entrySet().iterator();\n while( iterator.hasNext() ) {\n var entry = iterator.next();\n this.__putForCreate( entry.getKey(), entry.getValue() );\n }\n },\n\n _resize: function (newCapacity) {\n var oldTable = this._table,\n oldCapacity = oldTable.length;\n if( oldCapacity === this.self( arguments ).MAXIMUM_CAPACITY ) {\n this._threshold = Number.MAX_VALUE;\n return;\n }\n\n var newTable = jsava.JsavaUtils.emptyArrayOfGivenSize( newCapacity, null );\n this._transfer( newTable );\n this._table = newTable;\n this._threshold = (newCapacity * this._loadFactor) | 0;\n },\n\n _transfer: function (newTable) {\n var src = this._table,\n newCapacity = newTable.length;\n for( var j = 0; j < src.length; j++ ) {\n var entry = src[j];\n if( entry !== null ) {\n src[j] = null;\n do {\n var next = entry._next,\n i = this.self( arguments )._indexFor( entry._hash, newCapacity );\n entry._next = newTable[i];\n newTable[i] = entry;\n entry = next;\n } while( entry !== null );\n }\n }\n },\n\n putAll: function (map) {\n var numKeyToBeAdded = map.size();\n if( numKeyToBeAdded === 0 ) {\n return;\n }\n\n if( numKeyToBeAdded > this._threshold ) {\n var targetCapacity = (numKeyToBeAdded / this._loadFactor + 1) | 0;\n if( targetCapacity > this.self( arguments ).MAXIMUM_CAPACITY ) {\n targetCapacity = this.self( arguments ).MAXIMUM_CAPACITY;\n }\n\n var newCapacity = this._table.length;\n while( newCapacity < targetCapacity ) {\n newCapacity <<= 1;\n }\n if( newCapacity > this._table.length ) {\n this._resize( newCapacity );\n }\n }\n\n var iterator = map.entrySet().iterator();\n while( iterator.hasNext() ) {\n var entry = iterator.next();\n this.put( entry.getKey(), entry.getValue() );\n }\n },\n\n remove: function (key) {\n var entry = this._removeEntryForKey( key );\n return entry === null ? null : entry._value;\n },\n\n _removeEntryForKey: function (key) {\n var hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),\n i = this.self( arguments )._indexFor( hash, this._table.length ),\n prev = this._table[i],\n entry = prev;\n\n while( entry !== null ) {\n var next = entry._next,\n /** @type jsava.lang.Object */\n k;\n if( entry._hash === hash\n && ( (k = entry._key) === key || ( key !== null && key.equals( k ) ) ) ) {\n this._modCount++;\n this._size--;\n if( prev === entry ) {\n this._table[i] = next;\n } else {\n prev._next = next;\n }\n entry._recordRemoval( this );\n return entry;\n }\n prev = entry;\n entry = next;\n }\n\n return entry;\n },\n\n _removeMapping: function (obj) {\n if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {\n return null;\n }\n\n /** @implements jsava.util.Map.Entry */\n var entry = obj,\n key = entry.getKey(),\n hash = (key === null) ? 0 : this.self( arguments )._hash( key.hashCode() ),\n i = this.self( arguments )._indexFor( hash, this._table.length ),\n prev = this._table[i],\n e = prev;\n\n while( e !== null ) {\n var next = e._next;\n if( e._hash === hash && e.equals( entry ) ) {\n this._modCount++;\n this._size--;\n if( prev === e ) {\n this._table[i] = next;\n } else {\n prev._next = next;\n }\n e._recordRemoval( this );\n return e;\n }\n prev = e;\n e = next;\n }\n\n return e;\n },\n\n clear: function () {\n this._modCount++;\n var table = this._table;\n for( var i = 0; i < table.length; i++ ) {\n table[i] = null;\n }\n this._size = 0;\n },\n\n containsValue: function (value) {\n if( value === null ) {\n return this.__containsNullValue();\n }\n\n var table = this._table;\n for( var i = 0; i < table.length; i++ ) {\n for( var entry = table[i]; entry !== null; entry = entry._next ) {\n if( value.equals( entry._value ) ) {\n return true;\n }\n }\n }\n\n return false;\n },\n\n __containsNullValue: function () {\n var table = this._table;\n for( var i = 0; i < table.length; i++ ) {\n for( var entry = table[i]; entry !== null; entry = entry._next ) {\n if( entry._value === null ) {\n return true;\n }\n }\n }\n\n return false;\n },\n\n clone: function () {\n /** @type jsava.util.HashMap */\n var result = null;\n try {\n result = this.base( arguments );\n } catch( e ) {\n if( !qx.Class.isSubClassOf( e.constructor, jsava.lang.CloneNotSupportedException ) ) {\n throw e;\n }\n }\n\n result._table = jsava.JsavaUtils.emptyArrayOfGivenSize( this._table.length, null );\n result.__entrySet = null;\n result._modCount = 0;\n result._size = 0;\n result._init();\n result.__putAllForCreate( this );\n\n return result;\n },\n\n _addEntry: function (hash, key, value, bucketIndex) {\n var entry = this._table[bucketIndex];\n this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );\n if( this._size++ >= this._threshold ) {\n this._resize( 2 * this._table.length );\n }\n },\n\n _createEntry: function (hash, key, value, bucketIndex) {\n var entry = this._table[bucketIndex];\n this._table[bucketIndex] = new (this.self( arguments ).Entry)( hash, key, value, entry );\n this._size++;\n },\n\n keySet: function () {\n var keySet = this._keySet;\n return keySet !== null ? keySet : ( this._keySet = new this.KeySet( this ) );\n },\n\n values: function () {\n var values = this._values;\n return values !== null ? values : ( this._values = new this.Values( this ) );\n },\n\n entrySet: function () {\n return this.__entrySet0();\n },\n\n __entrySet0: function () {\n var entrySet = this.__entrySet;\n return entrySet !== null ? entrySet : ( this.__entrySet = new this.EntrySet( this ) );\n },\n\n /** @private */\n HashIterator: qx.Class.define( 'jsava.util.HashMap.HashIterator', {\n extend: jsava.lang.Object,\n implement: [jsava.util.Iterator],\n\n type: 'abstract',\n\n /** @protected */\n construct: function (thisHashMap) {\n this.__thisHashMap = thisHashMap;\n this._expectedModCount = this.__thisHashMap._modCount;\n if( this.__thisHashMap._size > 0 ) {\n var table = this.__thisHashMap._table;\n while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {\n // do nothing\n }\n }\n },\n\n members: {\n __thisHashMap: null,\n\n /** @type jsava.util.HashMap.Entry */\n _next: null,\n /** @type Number */\n _expectedModCount: 0,\n /** @type Number */\n _index: 0,\n /** @type jsava.util.HashMap.Entry */\n _current: null,\n\n hasNext: function () {\n return this._next !== null;\n },\n\n _nextEntry: function () {\n if( this.__thisHashMap._modCount !== this._expectedModCount ) {\n throw new jsava.lang.ConcurrentModificationException();\n }\n\n var entry = this._next;\n if( entry === null ) {\n throw new jsava.lang.NoSuchElementException();\n }\n\n if( (this._next = entry._next) === null ) {\n var table = this.__thisHashMap._table;\n while( this._index < table.length && ( this._next = table[this._index++] ) === null ) {\n // do nothing\n }\n }\n\n this._current = entry;\n return entry;\n },\n\n remove: function () {\n if( this._current === null ) {\n throw new jsava.lang.IllegalStateException();\n }\n\n if( this.__thisHashMap._modCount !== this._expectedModCount ) {\n throw new jsava.lang.ConcurrentModificationException();\n }\n\n var key = this._current._key;\n this._current = null;\n this.__thisHashMap._removeEntryForKey( key );\n this._expectedModCount = this.__thisHashMap._modCount;\n }\n }\n } ),\n\n _newKeyIterator: function () {\n return new this.KeyIterator( this );\n },\n\n _newValueIterator: function () {\n return new this.ValueIterator( this );\n },\n\n _newEntryIterator: function () {\n return new this.EntryIterator( this );\n },\n\n /** @private */\n ValueIterator: qx.Class.define( 'jsava.util.HashMap.ValueIterator', {\n extend: jsava.util.HashMap.HashIterator,\n\n construct: function (thisHashMap) {\n this.base( arguments, thisHashMap );\n },\n\n members: {\n next: function () {\n return this._nextEntry()._value;\n }\n }\n } ),\n\n /** @private */\n KeyIterator: qx.Class.define( 'jsava.util.HashMap.KeyIterator', {\n extend: jsava.util.HashMap.HashIterator,\n\n construct: function (thisHashMap) {\n this.base( arguments, thisHashMap );\n },\n\n members: {\n next: function () {\n return this._nextEntry().getKey();\n }\n }\n } ),\n\n /** @private */\n EntryIterator: qx.Class.define( 'jsava.util.HashMap.EntryIterator', {\n extend: jsava.util.HashMap.HashIterator,\n\n construct: function (thisHashMap) {\n this.base( arguments, thisHashMap );\n },\n\n members: {\n next: function () {\n return this._nextEntry();\n }\n }\n } ),\n\n /** @private */\n KeySet: qx.Class.define( 'jsava.util.HashMap.KeySet', {\n extend: jsava.util.AbstractSet,\n\n construct: function (thisHashMap) {\n this.base( arguments );\n this.__thisHashMap = thisHashMap;\n },\n\n members: {\n __thisHashMap: null,\n\n iterator: function () {\n return this.__thisHashMap._newKeyIterator();\n },\n\n size: function () {\n return this.__thisHashMap._size;\n },\n\n contains: function (obj) {\n return this.__thisHashMap.containsKey( obj );\n },\n\n remove: function (obj) {\n return this.__thisHashMap._removeEntryForKey( obj ) !== null;\n },\n\n clear: function () {\n this.__thisHashMap.clear();\n }\n }\n } ),\n\n /** @private */\n Values: qx.Class.define( 'jsava.util.HashMap.Values', {\n extend: jsava.util.AbstractCollection,\n\n construct: function (thisHashMap) {\n this.base( arguments );\n this.__thisHashMap = thisHashMap;\n },\n\n members: {\n __thisHashMap: null,\n\n iterator: function () {\n return this.__thisHashMap._newValueIterator();\n },\n\n size: function () {\n return this.__thisHashMap._size;\n },\n\n contains: function (obj) {\n return this.__thisHashMap.containsValue( obj );\n },\n\n clear: function () {\n this.__thisHashMap.clear();\n }\n }\n } ),\n\n /** @private */\n EntrySet: qx.Class.define( 'jsava.util.HashMap.EntrySet', {\n extend: jsava.util.AbstractSet,\n\n construct: function (thisHashMap) {\n this.base( arguments );\n this.__thisHashMap = thisHashMap;\n },\n\n members: {\n __thisHashMap: null,\n\n iterator: function () {\n return this.__thisHashMap._newEntryIterator();\n },\n\n size: function () {\n return this.__thisHashMap._size;\n },\n\n contains: function (obj) {\n if( obj === null || !qx.Class.implementsInterface( obj, jsava.util.Map.Entry ) ) {\n return false;\n }\n\n /** @implements jsava.util.Map.Entry */\n var entry = obj,\n candidate = this.__thisHashMap._getEntry( entry.getKey() );\n return candidate !== null && candidate.equals( entry );\n },\n\n remove: function (obj) {\n return this.__thisHashMap._removeMapping( obj ) !== null;\n },\n\n clear: function () {\n this.__thisHashMap.clear();\n }\n }\n } )\n }\n} );\n"
},
{
"answer_id": 19923386,
"author": "Nox73",
"author_id": 1752901,
"author_profile": "https://Stackoverflow.com/users/1752901",
"pm_score": 3,
"selected": false,
"text": "var wm1 = new WeakMap(),\n wm2 = new WeakMap(),\n wm3 = new WeakMap();\nvar o1 = {},\n o2 = function(){},\n o3 = window;\n\nwm1.set(o1, 37);\nwm1.set(o2, \"azerty\");\nwm2.set(o1, o2); // A value can be anything, including an object or a function\nwm2.set(o3, undefined);\nwm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!\n\nwm1.get(o2); // \"azerty\"\nwm2.get(o2); // Undefined, because there is no value for o2 on wm2\nwm2.get(o3); // Undefined, because that is the set value\n\nwm1.has(o2); // True\nwm2.has(o2); // False\nwm2.has(o3); // True (even if the value itself is 'undefined')\n\nwm3.set(o1, 37);\nwm3.get(o1); // 37\nwm3.clear();\nwm3.get(o1); // Undefined, because wm3 was cleared and there is no value for o1 anymore\n\nwm1.has(o1); // True\nwm1.delete(o1);\nwm1.has(o1); // False\n"
},
{
"answer_id": 20109120,
"author": "skozin",
"author_id": 804678,
"author_profile": "https://Stackoverflow.com/users/804678",
"pm_score": 2,
"selected": false,
"text": "_hash _id Array.prototype.indexOf var Dict = (function(){\n // Internet Explorer 8 and earlier does not have any Array.prototype.indexOf\n function indexOfPolyfill(val) {\n for (var i = 0, l = this.length; i < l; ++i) {\n if (this[i] === val) {\n return i;\n }\n }\n return -1;\n }\n\n function Dict(){\n this.keys = [];\n this.values = [];\n if (!this.keys.indexOf) {\n this.keys.indexOf = indexOfPolyfill;\n }\n };\n\n Dict.prototype.has = function(key){\n return this.keys.indexOf(key) != -1;\n };\n\n Dict.prototype.get = function(key, defaultValue){\n var index = this.keys.indexOf(key);\n return index == -1 ? defaultValue : this.values[index];\n };\n\n Dict.prototype.set = function(key, value){\n var index = this.keys.indexOf(key);\n if (index == -1) {\n this.keys.push(key);\n this.values.push(value);\n } else {\n var prevValue = this.values[index];\n this.values[index] = value;\n return prevValue;\n }\n };\n\n Dict.prototype.delete = function(key){\n var index = this.keys.indexOf(key);\n if (index != -1) {\n this.keys.splice(index, 1);\n return this.values.splice(index, 1)[0];\n }\n };\n\n Dict.prototype.clear = function(){\n this.keys.splice(0, this.keys.length);\n this.values.splice(0, this.values.length);\n };\n\n return Dict;\n})();\n var a = {}, b = {},\n c = { toString: function(){ return '1'; } },\n d = 1, s = '1', u = undefined, n = null,\n dict = new Dict();\n\n// Keys and values can be anything\ndict.set(a, 'a');\ndict.set(b, 'b');\ndict.set(c, 'c');\ndict.set(d, 'd');\ndict.set(s, 's');\ndict.set(u, 'u');\ndict.set(n, 'n');\n\ndict.get(a); // 'a'\ndict.get(b); // 'b'\ndict.get(s); // 's'\ndict.get(u); // 'u'\ndict.get(n); // 'n'\n// etc.\n delete clear"
},
{
"answer_id": 20787512,
"author": "Oriol",
"author_id": 1529630,
"author_profile": "https://Stackoverflow.com/users/1529630",
"pm_score": 5,
"selected": false,
"text": "WeakMap Map Map Map WeakMap"
},
{
"answer_id": 21101412,
"author": "ovnia",
"author_id": 2180005,
"author_profile": "https://Stackoverflow.com/users/2180005",
"pm_score": 0,
"selected": false,
"text": "var HashMap = function (TKey, TValue) {\n var db = [];\n var keyType, valueType;\n\n (function () {\n keyType = TKey;\n valueType = TValue;\n })();\n\n var getIndexOfKey = function (key) {\n if (typeof key !== keyType)\n throw new Error('Type of key should be ' + keyType);\n for (var i = 0; i < db.length; i++) {\n if (db[i][0] == key)\n return i;\n }\n return -1;\n }\n\n this.add = function (key, value) {\n if (typeof key !== keyType) {\n throw new Error('Type of key should be ' + keyType);\n } else if (typeof value !== valueType) {\n throw new Error('Type of value should be ' + valueType);\n }\n var index = getIndexOfKey(key);\n if (index === -1)\n db.push([key, value]);\n else\n db[index][1] = value;\n return this;\n }\n\n this.get = function (key) {\n if (typeof key !== keyType || db.length === 0)\n return null;\n for (var i = 0; i < db.length; i++) {\n if (db[i][0] == key)\n return db[i][1];\n }\n return null;\n }\n\n this.size = function () {\n return db.length;\n }\n\n this.keys = function () {\n if (db.length === 0)\n return [];\n var result = [];\n for (var i = 0; i < db.length; i++) {\n result.push(db[i][0]);\n }\n return result;\n }\n\n this.values = function () {\n if (db.length === 0)\n return [];\n var result = [];\n for (var i = 0; i < db.length; i++) {\n result.push(db[i][1]);\n }\n return result;\n }\n\n this.randomize = function () {\n if (db.length === 0)\n return this;\n var currentIndex = db.length, temporaryValue, randomIndex;\n while (0 !== currentIndex) {\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex--;\n temporaryValue = db[currentIndex];\n db[currentIndex] = db[randomIndex];\n db[randomIndex] = temporaryValue;\n }\n return this;\n }\n\n this.iterate = function (callback) {\n if (db.length === 0)\n return false;\n for (var i = 0; i < db.length; i++) {\n callback(db[i][0], db[i][1]);\n }\n return true;\n }\n}\n var a = new HashMap(\"string\", \"number\");\na.add('test', 1132)\n .add('test14', 666)\n .add('1421test14', 12312666)\n .iterate(function (key, value) {console.log('a['+key+']='+value)});\n/*\na[test]=1132\na[test14]=666\na[1421test14]=12312666 \n*/\na.randomize();\n/*\na[1421test14]=12312666\na[test]=1132\na[test14]=666\n*/\n"
},
{
"answer_id": 26087781,
"author": "Jamel Toms",
"author_id": 1592679,
"author_profile": "https://Stackoverflow.com/users/1592679",
"pm_score": 6,
"selected": false,
"text": "Map"
},
{
"answer_id": 33866427,
"author": "Riyafa Abdul Hameed",
"author_id": 3599535,
"author_profile": "https://Stackoverflow.com/users/3599535",
"pm_score": 5,
"selected": false,
"text": "var myMap = new Map();\nvar keyString = \"a string\",\n keyObj = {},\n keyFunc = function () {};\n\n// Setting the values\nmyMap.set(keyString, \"value associated with 'a string'\");\nmyMap.set(keyObj, \"value associated with keyObj\");\nmyMap.set(keyFunc, \"value associated with keyFunc\");\n\nmyMap.size; // 3\n\n// Getting the values\nmyMap.get(keyString); // \"value associated with 'a string'\"\nmyMap.get(keyObj); // \"value associated with keyObj\"\nmyMap.get(keyFunc); // \"value associated with keyFunc\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
368,281 | <p>I'm pulling my hair out on this one.</p>
<p>I have a site which is version controlled using Subversion. I use aptana (eclipse, subclipse) to do the svn. I have been checking in and out files, updating etc and everything is fine. However the system we have been building has been adding its own files and folders.</p>
<p>When I try to commit these, it tells me <code><path></code> is not a working copy. If I try to do a cleanup then it gives the same error. I found I can manually add each file to version control but this throws the same error. Doing an update doesn't help, refreshing the workspace does not do anything either. Cleanup seems to die after the error and then the directory is locked.</p>
<p>I know you're supposed to add files using SVN, but how on earth do you work with generated files? How do I get around this "<code><folder></code> is not a working copy directory" error? How do I get Subversion to just look at the files and add them to its repository?</p>
| [
{
"answer_id": 368293,
"author": "Keltia",
"author_id": 16143,
"author_profile": "https://Stackoverflow.com/users/16143",
"pm_score": 0,
"selected": false,
"text": "svn svn svn"
},
{
"answer_id": 368307,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 5,
"selected": true,
"text": "svn add svn commit"
},
{
"answer_id": 826128,
"author": "Sam",
"author_id": 101750,
"author_profile": "https://Stackoverflow.com/users/101750",
"pm_score": 5,
"selected": false,
"text": "cp -r A A~ # backup, since A was not in the repo\nrm -rf A # removed locked directory\nsvn rm A # remove A from pending commit\nmv ~A A # restore backup\nsvn add A # re-add to pending commit\nsvn cleanup # (had to cleanup several parent folders higher as well)\n"
},
{
"answer_id": 39188616,
"author": "Alireza Alallah",
"author_id": 3977996,
"author_profile": "https://Stackoverflow.com/users/3977996",
"pm_score": 0,
"selected": false,
"text": "move svn update tortoisteSVN"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28241/"
] |
368,288 | <p>I'm having trouble with the following two items:</p>
<ul>
<li>How to retrieve all of the subkey values in ClassesRoot\Typelib, and;</li>
<li>How to find a match for a known value (path/dll name) in the array of subkey values.</li>
</ul>
<p>As background info, I'm trying to find a way to check if a DLL has been registered. Someone mentioned that checking ClassesRoot\Typelib for the DLL was one way of doing it, since I know the directory location and name of the DLL, but nothing else.</p>
<p>Does anyone have any tips? Cheers.</p>
| [
{
"answer_id": 368397,
"author": "WOPR",
"author_id": 46255,
"author_profile": "https://Stackoverflow.com/users/46255",
"pm_score": 1,
"selected": false,
"text": "public void Foo()\n{\n foreach (string s in Microsoft.Win32.Registry.CurrentUser.GetSubKeyNames())\n {\n Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(s);\n // check here for the dll value and exit if found\n // recurse down the tree...\n }\n}\n"
},
{
"answer_id": 368580,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": true,
"text": "public static bool IsRegistered(string name, string dllPath)\n{\n RegistryKey typeLibKey = Registry.ClassesRoot.OpenSubKey(\"TypeLib\");\n foreach (string libIdKeyName in typeLibKey.GetSubKeyNames())\n {\n RegistryKey libIdKey = typeLibKey.OpenSubKey(libIdKeyName);\n foreach (string versionKeyName in libIdKey.GetSubKeyNames())\n {\n RegistryKey versionKey = libIdKey.OpenSubKey(versionKeyName);\n string regName = (string)versionKey.GetValue(\"\");\n if (regName == name)\n {\n foreach (string itterKeyName in versionKey.GetSubKeyNames())\n {\n int throwawayint;\n if (int.TryParse(itterKeyName, out throwawayint))\n {\n RegistryKey itterKey = versionKey.OpenSubKey(itterKeyName);\n string regDllPath = (string)itterKey.OpenSubKey(\"win32\").GetValue(\"\");\n if (regDllPath == dllPath)\n {\n return true;\n }\n }\n }\n }\n }\n }\n\n return false;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2493/"
] |
368,295 | <p>I'm using <code>FontMetrics.getHeight()</code> to get the height of the string, but it gives me a wrong value, cutting off the descenders of string characters. Is there a better function I can use?</p>
| [
{
"answer_id": 368308,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 4,
"selected": false,
"text": "getMaxDescent() getMaxAscent() getLineMetrics()"
},
{
"answer_id": 368448,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "getHeight() getHeight getAscent getDescent"
},
{
"answer_id": 12495108,
"author": "ranieribt",
"author_id": 938261,
"author_profile": "https://Stackoverflow.com/users/938261",
"pm_score": 6,
"selected": true,
"text": "getStringBounds() GlyphVector Graphics2D public class StringBoundsPanel extends JPanel\n{\n public StringBoundsPanel()\n {\n setBackground(Color.white);\n setPreferredSize(new Dimension(400, 247));\n }\n\n @Override\n protected void paintComponent(Graphics g)\n {\n super.paintComponent(g);\n\n Graphics2D g2 = (Graphics2D) g;\n\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n // must be called before getStringBounds()\n g2.setFont(getDesiredFont());\n\n String str = \"My Text\";\n float x = 140, y = 128;\n\n Rectangle bounds = getStringBounds(g2, str, x, y);\n\n g2.setColor(Color.red);\n g2.drawString(str, x, y);\n\n g2.setColor(Color.blue);\n g2.draw(bounds);\n\n g2.dispose();\n }\n\n private Rectangle getStringBounds(Graphics2D g2, String str,\n float x, float y)\n {\n FontRenderContext frc = g2.getFontRenderContext();\n GlyphVector gv = g2.getFont().createGlyphVector(frc, str);\n return gv.getPixelBounds(null, x, y);\n }\n\n private Font getDesiredFont()\n {\n return new Font(Font.SANS_SERIF, Font.BOLD, 28);\n }\n\n private void startUI()\n {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(this);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n\n public static void main(String[] args) throws Exception\n {\n final StringBoundsPanel tb = new StringBoundsPanel();\n\n SwingUtilities.invokeAndWait(new Runnable()\n {\n public void run()\n {\n tb.startUI();\n }\n });\n }\n}\n"
},
{
"answer_id": 15686930,
"author": "Florin Mircea",
"author_id": 1984683,
"author_profile": "https://Stackoverflow.com/users/1984683",
"pm_score": 2,
"selected": false,
"text": "public int getFontPixelHeight(float inSize, Paint sourcePaint, String tRange)\n{\n // It is assumed that the font is already set in the sourcePaint\n\n int bW = 250, bH = 250; // bitmap's width and height\n int firstContact = -1, lastContact = -2; // Used when scanning the pixel rows. Initial values are set so that if no pixels found, the returned result is zero.\n int tX = (int)(bW - inSize)/2, tY = (int)(bH - inSize)/2; // Used for a rough centering of the displayed characters\n\n int tSum = 0;\n\n // Preserve the original paint attributes\n float oldSize = sourcePaint.getTextSize();\n int oldColor = sourcePaint.getColor();\n // Set the size/color\n sourcePaint.setTextSize(inSize); sourcePaint.setColor(Color.WHITE);\n\n // Create the temporary bitmap/canvas\n Bitmap.Config bConf = Bitmap.Config.ARGB_8888;\n Bitmap hld = Bitmap.createBitmap(250, 250, bConf);\n Canvas canv = new Canvas(hld);\n\n for (int i = 0; i < bH; i++)\n {\n for (int j = 0; j < bW; j++)\n {\n hld.setPixel(j, i, 0); // Zero all pixel values. This might seem redundant, but I am not quite sure that creating a blank bitmap means the pixel color value is indeed zero, and I need them to be zero so the addition performed below is correct.\n }\n }\n\n // Display all characters overlapping at the same position\n for (int i = 0; i < tRange.length(); i++)\n {\n canv.drawText(\"\" + tRange.charAt(i), tX, tY, sourcePaint);\n }\n\n for (int i = 0; i < bH; i++)\n {\n for (int j = 0; j < bW; j++)\n {\n tSum = tSum + hld.getPixel(j, i);\n }\n\n if (tSum > 0) // If we found at least a pixel, save row index and exit loop\n {\n firstContact = i;\n tSum = 0; // Reset\n break;\n } \n }\n\n for (int i = bH - 1; i > 0 ; i--)\n {\n for (int j = 0; j < bW; j++)\n {\n tSum = tSum + hld.getPixel(j, i);\n }\n\n if (tSum > 0) // If we found at least a pixel, save row index and exit loop\n {\n lastContact = i;\n break;\n } \n }\n\n // Restore the initial attributes, just in case the paint was passed byRef somehow\n sourcePaint.setTextSize(oldSize);\n sourcePaint.setColor(oldColor);\n\n return lastContact - firstContact + 1;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476/"
] |
368,323 | <p>i've got the following linq2sql query, and i'm setting the result to a POCO. One of my POCO properties is an enumeration.</p>
<pre><code>public IQueryable<Models.Achievement> GetAchievements()
{
return from a in _sqlDatabase.Achievements
select new Models.Achievement
{
// Note: ToEnum is an extension method that converts an int -> the enum.
AchievementType = a.AchievementTypeId.ToEnum<Models.AchievementType>(),
DateTimeCreated = a.DateTimeCreated,
UserId = a.UserId
};
}
</code></pre>
<p>When i run the query, i get the following error.</p>
<pre><code>System.NotSupportedException: Method 'Models.AchievementType
ToEnum[AchievementType](int)' has no supported translation to SQL.
</code></pre>
<p>hmm. is there a way i can be tricky enough to make the result int get converted to my custom enum?</p>
| [
{
"answer_id": 368335,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "select new {..., AchievementType = (AchievementType) foo.Bar, ...}\n Models.Achievement Where"
},
{
"answer_id": 368342,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 0,
"selected": false,
"text": " AchievementType achievementType{\n get\n {\n return this.AchievementTypeId.ToEnum<Models.AchievementType>();\n }\n set\n {\n this.AchievementTypeId = (int)value;\n }\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
368,329 | <p>Besides the fact that <code>$_REQUEST</code> reads from cookies, are there any reasons why I should use <code>$_GET</code> and <code>$_POST</code> instead of <code>$_REQUEST</code>? What are theoretical and practical reasons for doing so?</p>
| [
{
"answer_id": 368337,
"author": "Karsten",
"author_id": 28144,
"author_profile": "https://Stackoverflow.com/users/28144",
"pm_score": 2,
"selected": false,
"text": "$_GET['foo'] = 'bar'\n$_POST['foo'] = 'baz'\n $_REQUEST['foo'] == 'bar'"
},
{
"answer_id": 368339,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": false,
"text": "$_POST"
},
{
"answer_id": 368461,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "$_REQUEST"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26155/"
] |
368,338 | <p>can I pass a cursor in a procedure?</p>
<pre><code>CURSOR BLT_CURSOR IS
SELECT BLT.sol_id,
BLT.bill_id,
BLT.bank_id
FROM BLT;
</code></pre>
<p>Is my cursor.</p>
<pre><code>Procedure abc(i want to pass the cursor here)
</code></pre>
<p>How do I do it.</p>
| [
{
"answer_id": 368533,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": false,
"text": "PROCEDURE abc( p_cursor IN SYS_REFCURSOR) IS\n v_sol_id blt.sol_id%TYPE;\n v_bill_id blt.bill_id%TYPE;\n v_bank_id blt.bank_id%TYPE;\nBEGIN\n LOOP\n FETCH p_cursor INTO v_sol_id, v_bill_id, v_bank_id;\n EXIT WHEN p_cursor%NOTFOUND;\n ...\n END LOOP;\nEND;\n DECLARE\n v_cursor SYS_REFCURSOR;\nBEGIN\n OPEN v_cursor FOR\n SELECT BLT.sol_id,\n BLT.bill_id,\n BLT.bank_id\n FROM BLT;\n abc (v_cursor);\n CLOSE v_cursor;\nEND;\n"
},
{
"answer_id": 53363358,
"author": "Sylwester Santorowski",
"author_id": 7523727,
"author_profile": "https://Stackoverflow.com/users/7523727",
"pm_score": 1,
"selected": false,
"text": "--Create the table and fill it with data\nDROP TABLE dbo.StackOverflow_MyTable\nGO\nCREATE TABLE dbo.StackOverflow_MyTable (\n MyChar varchar(10),\n MyDate datetime,\n MyNum numeric(10,2)\n PRIMARY KEY (MyChar))\nGO\nINSERT INTO dbo.StackOverflow_MyTable SELECT 'A1', '2018-01-13', 123.45\nINSERT INTO dbo.StackOverflow_MyTable SELECT 'B2', '2018-01-14', 123.46\nINSERT INTO dbo.StackOverflow_MyTable SELECT 'C3', '2018-01-15', 123.47\nGO\n/* Create the procedure which returns the cursor variable based on select statement\n The cursor must be opened here. Otherwise it throws an Error:\n The variable '@MyCursorVar' does not currently have a cursor allocated to it\n*/\nDROP PROCEDURE dbo.StackOverflow_OpenCursor\nGO\nCREATE PROCEDURE dbo.StackOverflow_OpenCursor @SelectSQL nvarchar(128), @MyCursorVar CURSOR VARYING OUTPUT\n AS\n DECLARE @SQL nvarchar(256)\n SET @SQL=' SET @MyCursorVar = CURSOR FOR '+@SelectSQL+'\n OPEN @MyCursorVar'\n\n EXEC sp_executesql @SQL, N'@MyCursorVar CURSOR OUTPUT', @MyCursorVar OUTPUT\nGO\n\n--Create the procedure which browses the table using the cursor variable\nDROP PROCEDURE dbo.StackOverflow_BrowseCursor\nGO\nCREATE PROCEDURE dbo.StackOverflow_BrowseCursor @SelectSQL nvarchar(128)\n AS\n --Create the cursor variable based on select statement and OPEN the cursor\n DECLARE @MyCursorVar CURSOR\n EXEC dbo.StackOverflow_OpenCursor @SelectSQL, @MyCursorVar OUTPUT\n\n --Declare the variables corresponding to table column\n DECLARE @MyChar varchar(10), @MyDate datetime, @MyNum numeric(10,2)\n --Browse record by record\n WHILE 1=1\n BEGIN\n FETCH NEXT FROM @MyCursorVar INTO @MyChar, @MyDate, @MyNum\n IF @@FETCH_STATUS <> 0 BREAK\n PRINT @MyChar --Here you might call any other procedure or dataset update\n PRINT @MyDate\n PRINT @MyNum\n END\n --release the cursor resources\n CLOSE @MyCursorVar\n DEALLOCATE @MyCursorVar\nGO\n\n--How to call the cursor browsing \nDECLARE @SelectSQL nvarchar(128)\nSET @SelectSQL = 'SELECT MyChar, MyDate, MyNum FROM dbo.StackOverflow_MyTable ORDER BY MyChar'\nEXEC dbo.StackOverflow_BrowseCursor @SelectSQL\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,351 | <p>Given the following table in SQL Server 2005:</p>
<pre><code>ID Col1 Col2 Col3
-- ---- ---- ----
1 3 34 76
2 32 976 24
3 7 235 3
4 245 1 792
</code></pre>
<p>What is the best way to write the query that yields the following result (i.e. one that yields the final column - a column containing the minium values out of Col1, Col2, and Col 3 <strong>for each row</strong>)?</p>
<pre><code>ID Col1 Col2 Col3 TheMin
-- ---- ---- ---- ------
1 3 34 76 3
2 32 976 24 24
3 7 235 3 3
4 245 1 792 1
</code></pre>
<p><strong><em>UPDATE:</em></strong></p>
<p>For clarification (as I have said in the coments) in the real scenario the database is <strong>properly normalized</strong>. These "array" columns are not in an actual table but are in a result set that is required in a report. And the new requirement is that the report also needs this MinValue column. I can't change the underlying result set and therefore I was looking to T-SQL for a handy "get out of jail card".</p>
<p>I tried the CASE approach mentioned below and it works, although it is a bit cumbersome. It is also more complicated than stated in the answers because you need to cater for the fact that there are two min values in the same row.</p>
<p>Anyway, I thought I'd post my current solution which, given my constraints, works pretty well. It uses the UNPIVOT operator:</p>
<pre><code>with cte (ID, Col1, Col2, Col3)
as
(
select ID, Col1, Col2, Col3
from TestTable
)
select cte.ID, Col1, Col2, Col3, TheMin from cte
join
(
select
ID, min(Amount) as TheMin
from
cte
UNPIVOT (Amount for AmountCol in (Col1, Col2, Col3)) as unpvt
group by ID
) as minValues
on cte.ID = minValues.ID
</code></pre>
<p>I'll say upfront that I don't expect this to offer the best performance, but given the circumstances (I can't redesign all the queries just for the new MinValue column requirement), it is a pretty elegant "get out of jail card".</p>
| [
{
"answer_id": 368381,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 7,
"selected": true,
"text": "Select Id,\n Case When Col1 < Col2 And Col1 < Col3 Then Col1\n When Col2 < Col1 And Col2 < Col3 Then Col2 \n Else Col3\n End As TheMin\nFrom YourTableNameHere\n"
},
{
"answer_id": 368388,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 2,
"selected": false,
"text": " select case when col1 <= col2 and col1 <= col3 then col1\n case when col2 <= col1 and col2 <= col3 then col2\n case when col3 <= col1 and col3 <= col2 then col3\n as 'TheMin'\n end\n\nfrom Table T\n"
},
{
"answer_id": 368394,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "ID Col Val\n-- --- ---\n 1 1 3\n 1 2 34\n 1 3 76\n\n 2 1 32\n 2 2 976\n 2 3 24\n\n 3 1 7\n 3 2 235\n 3 3 3\n\n 4 1 245\n 4 2 1\n 4 3 792\n ID/Col Col select min(val) from tbl where col = 2 Col1/2/3 ID Col1 Col2 Col3 MinVal\n-- ---- ---- ---- ------\n 1 3 34 76 3\n 2 32 976 24 24\n 3 7 235 3 3\n 4 245 1 792 1\n select"
},
{
"answer_id": 368402,
"author": "Phil Corcoran",
"author_id": 45381,
"author_profile": "https://Stackoverflow.com/users/45381",
"pm_score": 1,
"selected": false,
"text": "select *,\ncase when column1 < columnl2 And column1 < column3 then column1\nwhen columnl2 < column1 And columnl2 < column3 then columnl2\nelse column3\nend As minValue\nfrom tbl_example\n"
},
{
"answer_id": 368412,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": false,
"text": "Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin\nFrom YourTable T\n Inner Join (\n Select A.Id, Min(A.Col1) As TheMin\n From (\n Select Id, Col1\n From YourTable\n\n Union All\n\n Select Id, Col2\n From YourTable\n\n Union All\n\n Select Id, Col3\n From YourTable\n ) As A\n Group By A.Id\n ) As A\n On T.Id = A.Id\n"
},
{
"answer_id": 368787,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 1,
"selected": false,
"text": ";WITH res\n AS ( SELECT t.YourID ,\n CAST(( SELECT Col1 AS c01 ,\n Col2 AS c02 ,\n Col3 AS c03 ,\n Col4 AS c04 ,\n Col5 AS c05\n FROM YourTable AS cols\n WHERE YourID = t.YourID\n FOR\n XML AUTO ,\n ELEMENTS\n ) AS XML) AS colslist\n FROM YourTable AS t\n )\n SELECT YourID ,\n colslist.query('for $c in //cols return min(data($c/*))').value('.',\n 'real') AS YourMin ,\n colslist.query('for $c in //cols return avg(data($c/*))').value('.',\n 'real') AS YourAvg ,\n colslist.query('for $c in //cols return max(data($c/*))').value('.',\n 'real') AS YourMax\n FROM res\n"
},
{
"answer_id": 7249663,
"author": "Lamprey",
"author_id": 920512,
"author_profile": "https://Stackoverflow.com/users/920512",
"pm_score": 1,
"selected": false,
"text": "DECLARE @Foo TABLE (ID INT, Col1 INT, Col2 INT, Col3 INT)\n\nINSERT @Foo (ID, Col1, Col2, Col3)\nVALUES\n(1, 3, 34, 76),\n(2, 32, 976, 24),\n(3, 7, 235, 3),\n(4, 245, 1, 792)\n\nSELECT\n ID,\n Col1,\n Col2,\n Col3,\n (\n SELECT MIN(T.Col)\n FROM\n (\n SELECT Foo.Col1 AS Col UNION ALL\n SELECT Foo.Col2 AS Col UNION ALL\n SELECT Foo.Col3 AS Col \n ) AS T\n ) AS TheMin\nFROM\n @Foo AS Foo\n"
},
{
"answer_id": 12160692,
"author": "Georgios",
"author_id": 1630457,
"author_profile": "https://Stackoverflow.com/users/1630457",
"pm_score": 3,
"selected": false,
"text": "create function f_min_int(@a as int, @b as int) \nreturns int\nas\nbegin\n return case when @a < @b then @a else coalesce(@b,@a) end\nend\n select col1, col2, col3, dbo.f_min_int(dbo.f_min_int(col1,col2),col3)\n select col1, col2, col3, col4, col5,\ndbo.f_min_int(dbo.f_min_int(dbo.f_min_int(dbo.f_min_int(col1,col2),col3),col4),col5)\n"
},
{
"answer_id": 18496970,
"author": "Israel Margulies",
"author_id": 1346806,
"author_profile": "https://Stackoverflow.com/users/1346806",
"pm_score": 1,
"selected": false,
"text": "select case when 0 in (PAGE1STATUS ,PAGE2STATUS ,PAGE3STATUS,\nPAGE4STATUS,PAGE5STATUS ,PAGE6STATUS) then 0 else 1 end\nFROM CUSTOMERS_FORMS\n"
},
{
"answer_id": 22833781,
"author": "user3493139",
"author_id": 3493139,
"author_profile": "https://Stackoverflow.com/users/3493139",
"pm_score": 5,
"selected": false,
"text": "select least(col1, col2, col3) FROM yourtable\n"
},
{
"answer_id": 28810615,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 4,
"selected": false,
"text": "SELECT CASE\n WHEN Col1 <= Col2 AND Col1 <= Col3 THEN Col1\n WHEN Col2 <= Col3 THEN Col2\n ELSE Col3\nEND AS [Min Value] FROM [Your Table]\n SELECT CASE\n WHEN Col1 <= Col2 AND Col1 <= Col3 AND Col1 <= Col4 AND Col1 <= Col5 THEN Col1\n WHEN Col2 <= Col3 AND Col2 <= Col4 AND Col2 <= Col5 THEN Col2\n WHEN Col3 <= Col4 AND Col3 <= Col5 THEN Col3\n WHEN Col4 <= Col5 THEN Col4\n ELSE Col5\nEND AS [Min Value] FROM [Your Table]\n <= CASE"
},
{
"answer_id": 29834765,
"author": "Nizam",
"author_id": 358614,
"author_profile": "https://Stackoverflow.com/users/358614",
"pm_score": 6,
"selected": false,
"text": "CROSS APPLY SELECT ID, Col1, Col2, Col3, MinValue\nFROM YourTable\nCROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A\n"
},
{
"answer_id": 34561497,
"author": "user3438020",
"author_id": 3438020,
"author_profile": "https://Stackoverflow.com/users/3438020",
"pm_score": 1,
"selected": false,
"text": "--==================== this gets minimums and global min\nif object_id('tempdb..#temp1') is not null\n drop table #temp1\nif object_id('tempdb..#temp2') is not null\n drop table #temp2\n\nselect r.recordid , r.ReferenceNumber, i.InventionTitle, RecordDate, i.ReceivedDate\n, min(fi.uploaddate) [Min File Upload], min(fi.CorrespondenceDate) [Min File Correspondence]\ninto #temp1\nfrom record r \njoin Invention i on i.inventionid = r.recordid\nleft join LnkRecordFile lrf on lrf.recordid = r.recordid\nleft join fileinformation fi on fi.fileid = lrf.fileid\nwhere r.recorddate > '2015-05-26'\n group by r.recordid, recorddate, i.ReceivedDate,\n r.ReferenceNumber, i.InventionTitle\n\n\n\nselect recordid, recorddate [min date]\ninto #temp2\nfrom #temp1\n\nupdate #temp2\nset [min date] = ReceivedDate \nfrom #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid\nwhere t1.ReceivedDate < [min date] and t1.ReceivedDate > '2001-01-01'\n\nupdate #temp2 \nset [min date] = t1.[Min File Upload]\nfrom #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid\nwhere t1.[Min File Upload] < [min date] and t1.[Min File Upload] > '2001-01-01'\n\nupdate #temp2\nset [min date] = t1.[Min File Correspondence]\nfrom #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid\nwhere t1.[Min File Correspondence] < [min date] and t1.[Min File Correspondence] > '2001-01-01'\n\n\nselect t1.*, t2.[min date] [LOWEST DATE]\nfrom #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid\norder by t1.recordid\n"
},
{
"answer_id": 34589665,
"author": "dsz",
"author_id": 1331446,
"author_profile": "https://Stackoverflow.com/users/1331446",
"pm_score": 6,
"selected": false,
"text": "SELECT ID, Col1, Col2, Col3, \n (SELECT MIN(Col) FROM (VALUES (Col1), (Col2), (Col3)) AS X(Col)) AS TheMin\nFROM Table\n"
},
{
"answer_id": 47220333,
"author": "Tino Jose Thannippara",
"author_id": 3890187,
"author_profile": "https://Stackoverflow.com/users/3890187",
"pm_score": 1,
"selected": false,
"text": "SELECT [ID],\n (\n SELECT MIN([value].[MinValue])\n FROM\n (\n VALUES\n ([Col1]),\n ([Col1]),\n ([Col2]),\n ([Col3])\n ) AS [value] ([MinValue])\n ) AS [MinValue]\nFROM Table;\n"
},
{
"answer_id": 55747020,
"author": "Rao",
"author_id": 3336667,
"author_profile": "https://Stackoverflow.com/users/3336667",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE #tempTable (ID int, columnName varchar(20), dataValue int)\n\nINSERT INTO #tempTable \n SELECT ID, 'Col1', Col1\n FROM sourceTable\n WHERE Col1 IS NOT NULL\nINSERT INTO #tempTable \n SELECT ID, 'Col2', Col2\n FROM sourceTable\n WHERE Col2 IS NOT NULL\nINSERT INTO #tempTable \n SELECT ID, 'Col3', Col3\n FROM sourceTable\n WHERE Col3 IS NOT NULL\n\nSELECT ID\n , min(dataValue) AS 'Min'\n , max(dataValue) AS 'Max'\n , max(dataValue) - min(dataValue) AS 'Diff' \n FROM #tempTable \n GROUP BY ID\n columnName max"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21379/"
] |
368,359 | <p>I have a long running function in MATLAB that I tried to speed up by adding caching and wound up slowing down my performance significantly. My code is basically searching for continuous "horizontal" lines in an edge detected image and the original code looks something like this:</p>
<pre><code>function lineLength = getLineLength(img, startRow, startCol)
[nRows, nCols] = size(img);
lineLength = 0;
if startRow < 1 || startRow > nRows
return;
end
for curCol = startCol:nCols
if img(curCol)
lineLength = lineLength + 1;
continue;
elseif lineLength > 0
lengths = zeros(2,1);
lengths(1) = getLineLength(img, startRow - 1, curCol);
lengths(2) = getLineLength(img, startRow + 1, curCol);
increment = max(lengths);
lineLength = lineLength + increment;
end
break; %// At this point the end of the current line has been reached
end
end function
</code></pre>
<p>Since performance in this function is not what I would like, I thought I would add caching of the length from any point something like the following:</p>
<pre><code>function lineLength = getLineLength(img, startRow, startCol)
persistent pointCache;
if startRow == 0 && startCol == 0
pointCache = zeros(size(img, 1), size(img, 2), 2);
end
[nRows, nCols] = size(img);
lineLength = 0;
if startRow < 1 || startRow > nRows
return;
end
for curCol = startCol:nCols
if pointCache(startRow, curCol, 2)
lineLength = lineLength + pointCache(startRow, curCol, 1);
break;
end
if img(curCol)
lineLength = lineLength + 1;
continue;
elseif lineLength > 0
lengths = zeros(2,1);
lengths(1) = getLineLength(img, startRow - 1, curCol);
lengths(2) = getLineLength(img, startRow + 1, curCol);
increment = max(lengths);
lineLength = lineLength + increment;
end
break; %// At this point the end of the current line has been reached
end
pointCache(startRow, startCol, 1) = lineLength;
pointCache(startRow, startCol, 2) = 1;
end function
</code></pre>
<p>What surprised me is that implementing this caching actually made my performance worse, rather than better. My best guesses are that either the <code>global</code> variable is getting me in trouble, or its the extra memory use, but I don't have enough MATLAB experience to know.</p>
<p><strong>Edited...</strong></p>
<p>As Gautam correctly pointed out that there was a bug in the original code that was ignoring the results of the recursion. This is what the actual code does. I'm sure it's obvious, but MATLAB is not my native language so if there's a more MATLABy way to do this, I'd love the suggestions.</p>
| [
{
"answer_id": 368391,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 0,
"selected": false,
"text": "for every pixel p in img\n if (pixel p set)\n linelength = 1\n p2 = p\n while (pixel p2 set) and (p2 in same column as p)\n p++ // don't check lines twice\n p2++\n linelength++\n endwhile\n endif\n"
},
{
"answer_id": 368654,
"author": "Marc",
"author_id": 8478,
"author_profile": "https://Stackoverflow.com/users/8478",
"pm_score": 2,
"selected": false,
"text": "persistent profile on profile report"
},
{
"answer_id": 371944,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "sum cumsum diff bsxfun accumarray"
},
{
"answer_id": 376884,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 0,
"selected": false,
"text": "lineLengths = max(cumsum(img~=0, 1), 1)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
] |
368,362 | <p>Sample data:
!!Part|123456,ABCDEF,ABC132!!</p>
<p>The comma delimited list can be any number of any combination of alphas and numbers </p>
<p>I want a regex to match the entries in the comma separated list:</p>
<p>What I have is:
!!PART\|(\w+)(?:,{1}(\w+))*!!</p>
<p>Which seems to do the job, the thing is I want to retrieve them in order into an ArrayList or similar so in the sample data I would want:</p>
<ul>
<li>1 - 132456</li>
<li>2 - ABCDEF</li>
<li>3 - ABC123</li>
</ul>
<p>The code I have is:</p>
<pre><code>string partRegularExpression = @"!!PART\|(\w+)(?:,{1}(\w+))*!!"
Match match = Regex.Match(tag, partRegularExpression);
ArrayList results = new ArrayList();
foreach (Group group in match.Groups)
{
results.Add(group.Value);
}
</code></pre>
<p>But that's giving me unexpected results. What am I missing?</p>
<p>Thanks</p>
<p><strong>Edit:</strong>
A solution would be to use a regex like !!PART\|(\w+(?:,??\w+)*)!! to capture the comma separated list and then split that as suggested by Marc Gravell</p>
<p>I am still curious for a working regex for this however :o)</p>
| [
{
"answer_id": 368389,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": " if (tag.StartsWith(\"!!Part|\") && tag.EndsWith(\"!!\"))\n {\n tag = tag.Substring(7, tag.Length - 9);\n string[] data = tag.Split(',');\n }\n"
},
{
"answer_id": 368418,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "string testString = \"!!Part|123456,ABCDEF,ABC132!!\";\nforeach(string component in testString.Split(\"|!,\".ToCharArray(),StringSplitOptions.RemoveEmptyEntries) )\n{\n Console.WriteLine(component);\n}\n Part\n123456\nABCDEF\nABC132\n"
},
{
"answer_id": 368421,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 1,
"selected": false,
"text": "(?:^!!PART\\|){0,1}(?<value>.*?)(?:,|!!$)\n string tag = \"!!Part|123456,ABCDEF,ABC132!!\";\n\n string partRegularExpression = @\"(?:^!!PART\\|){0,1}(?<value>.*?)(?:,|!!$)\";\n ArrayList results = new ArrayList();\n\n Regex extractNumber = new Regex(partRegularExpression, RegexOptions.IgnoreCase);\n MatchCollection matches = extractNumber.Matches(tag);\n foreach (Match match in matches)\n {\n results.Add(match.Groups[\"value\"].Value);\n } \n\n foreach (string s in results)\n {\n Console.WriteLine(s);\n }\n"
},
{
"answer_id": 368426,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": true,
"text": "string csv = tag.Substring(7, tag.Length - 9);\nstring[] values = csv.Split(new char[] { ',' });\n Regex csvRegex = new Regex(@\"!!Part\\|(?:(?<value>\\w+),?)+!!\");\nList<string> valuesRegex = new List<string>();\nforeach (Capture capture in csvRegex.Match(tag).Groups[\"value\"].Captures)\n{\n valuesRegex.Add(capture.Value);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39643/"
] |
368,369 | <p>I'm working on a site similar to digg in the respect that users can submit "stories". </p>
<p>I keep track of how many "votes" and "similar adds" each item got. Similar adds are defined as two users adding the same "link". </p>
<p>Here is <em>part</em> of the algorithm (essentially the most important):</p>
<pre><code>y = day number
sy = number of adds on day y
∑ y[1:10] sy / y
</code></pre>
<p>So basically calculate the number of "similar adds" on a specified day and divide by the number of seconds since the content was posted. Do this for the past 10 days (as an example). </p>
<p>However, I'm not sure how to implement this so that it performs well. Every method I can think of will be really slow. </p>
<p>The only way I can think of implementing this is by calculating the number of adds for the past 10 days for each item submitted will take forever. (so a sql command with a group by date executed 10 times for the past 10 days - obviously this method sucks).</p>
<p>Even if I keep a table that I update once a day (and run the above sql in the background), that will still be ridiculously slow once the database gets large. Plus the rating will be "outdated" since it's not live (e.g. breaking news "items" will never reach the top). </p>
<p>Does anyone have any experience of how to go about doing this?</p>
| [
{
"answer_id": 368509,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "select sum(dayval)\nfrom\n( select count(*) / (current_date-day+1) dayval\n from votes\n where story_id = 123\n and day >= current_date - 9\n group by (current_date-day+1)\n)\n"
},
{
"answer_id": 2858903,
"author": "frankster",
"author_id": 147813,
"author_profile": "https://Stackoverflow.com/users/147813",
"pm_score": 1,
"selected": false,
"text": "const float WeightFactor = 0.70; //for example\nfloat PreviousAverage = GetPreviousAverage();\nfloat CurrentValue = GetVoteCountToday();\n\nfloat NewAverage = (WeightFactor * CurrentValue) + ( (1-WeightFactor) * PreviousAverage);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
368,384 | <p>After deploying our huge distributed system to one of our clients we experience an unexpected error. During the investigation we replace the assembly causing the error with one where we have added some diagnostic code. The dll we use is built in debug mode. And suddenly it all works!</p>
<p>Replacing the debug dll with the release version (with the diagnostic code) makes it crash again. </p>
<p>There are no precompiler directives, conditional debug attributes etc. in our code. The problem has been found in two different installation sites, while it works fine in several more.</p>
<p>(The project has a mix of C# and VB.NET, the troublesom assembly is VB.NET.., if that makes any difference)</p>
<p>So the question is: <strong><em>What do you do in situations like this? And what can be the cause - in general?</em></strong> Any advice on debugging this issue is welcome.</p>
| [
{
"answer_id": 368408,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "Debug.WriteLine [Conditional(...)] [Conditional(\"DEBUG\")] static string Bar { get; set; }\n static void Main()\n {\n Bar = \"I'm broken\";\n Debug.WriteLine(Foo());\n Console.WriteLine(Bar);\n }\n // note Foo only called in DEBUG builds\n static string Foo()\n {\n Bar = \"I'm working\";\n return \"mwahahah\";\n }\n string foo = Foo();\nDebug.WriteLine(foo);\n"
},
{
"answer_id": 368429,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": false,
"text": "Debug.Assert(ImportantMethod());\n"
},
{
"answer_id": 1132045,
"author": "twon33",
"author_id": 88701,
"author_profile": "https://Stackoverflow.com/users/88701",
"pm_score": 1,
"selected": false,
"text": "void MyFunction() \n{ \n Foo f = new Foo();\n SomeFunction(f.SomeProp);\n}\n f SomeFunction() SomeProp GC.KeepAlive(f) SomeFunction f KeepAlive()"
},
{
"answer_id": 51526567,
"author": "Thiago Carvalho",
"author_id": 9068979,
"author_profile": "https://Stackoverflow.com/users/9068979",
"pm_score": 2,
"selected": false,
"text": "StackTrace stackTrace = new StackTrace();\nMethodBase methodBase = stackTrace.GetFrame(2).GetMethod();\n GetFrame(2)"
},
{
"answer_id": 52993495,
"author": "Ant",
"author_id": 11529,
"author_profile": "https://Stackoverflow.com/users/11529",
"pm_score": 0,
"selected": false,
"text": "var isThisMyAssembly = System.Reflection.Assembly.GetCallingAssembly();\n MethodImplAttribute [MethodImpl(MethodImplOptions.NoInlining)]\nvoid DoSomeThings()\n{\n var isThisMyAssembly = System.Reflection.Assembly.GetCallingAssembly();\n //do stuff\n}\n Assembly.GetExecutingAssembly()"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22621/"
] |
368,385 | <p>Is it possible to implement <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> in pure C? </p>
<p>I assume it isn't possible in any sane way, but perhaps is it possible using some kind of dirty trick. Overloading the standard <code>free</code> function comes to mind or perhaps overwriting the return address on the stack so that when the function returns, it calls some other function that somehow releases resources? Or maybe with some setjmp/longjmp trick?</p>
<p>This is of a purely academic interest and I have no intention of actually writing such unportable and crazy code but I'm wondering if that is at all possible.</p>
| [
{
"answer_id": 368444,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "free"
},
{
"answer_id": 368731,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": true,
"text": "cleanup #include <stdio.h>\n\nvoid scoped(int * pvariable) {\n printf(\"variable (%d) goes out of scope\\n\", *pvariable);\n}\n\nint main(void) {\n printf(\"before scope\\n\");\n {\n int watched __attribute__((cleanup (scoped)));\n watched = 42;\n }\n printf(\"after scope\\n\");\n}\n before scope\nvariable (42) goes out of scope\nafter scope\n"
},
{
"answer_id": 3207408,
"author": "Jerry Coffin",
"author_id": 179910,
"author_profile": "https://Stackoverflow.com/users/179910",
"pm_score": 3,
"selected": false,
"text": "int f(int x) { \n int vla[x];\n\n // ...\n}\n int f(int x) { \n int *vla=malloc(sizeof(int) *x);\n /* ... */\n free vla;\n}\n"
},
{
"answer_id": 16993429,
"author": "Keldon Alleyne",
"author_id": 1117740,
"author_profile": "https://Stackoverflow.com/users/1117740",
"pm_score": 4,
"selected": false,
"text": "cleanup() /* Publicly known method */\nvoid SomeFunction() {\n /* Create raii object, which holds records of object pointers and a\n destruction method for that object (or null if not needed). */\n Raii raii;\n RaiiCreate(&raii);\n\n /* Call function implementation */\n SomeFunctionImpl(&raii);\n\n /* This method calls the destruction code for each object. */\n RaiiDestroyAll(&raii);\n}\n\n/* Hidden method that carries out implementation. */\nvoid SomeFunctionImpl(Raii *raii) {\n MyStruct *object;\n MyStruct *eventually_destroyed_object;\n int *pretend_value;\n\n /* Create a MyStruct object, passing the destruction method for\n MyStruct objects. */\n object = RaiiAdd(raii, MyStructCreate(), MyStructDestroy);\n\n /* Create a MyStruct object (adding it to raii), which will later\n be removed before returning. */\n eventually_destroyed_object = RaiiAdd(raii,\n MyStructCreate(), MyStructDestroy);\n\n /* Create an int, passing a null destruction method. */\n pretend_value = RaiiAdd(raii, malloc(sizeof(int)), 0);\n\n /* ... implementation ... */\n\n /* Destroy object (calling destruction method). */\n RaiiDestroy(raii, eventually_destroyed_object);\n\n /* or ... */\n RaiiForgetAbout(raii, eventually_destroyed_object);\n}\n SomeFunction /* Declares Matrix * MatrixMultiply(Matrix * first, Matrix * second, Network * network) */\nRTN_RAII(Matrix *, MatrixMultiply, Matrix *, first, Matrix *, second, Network *, network, {\n Processor *processor = RaiiAdd(raii, ProcessorCreate(), ProcessorDestroy);\n Matrix *result = MatrixCreate();\n processor->multiply(result, first, second);\n return processor;\n});\n\nvoid SomeOtherCode(...) {\n /* ... */\n Matrix * result = MatrixMultiply(first, second, network);\n /* ... */\n}\n"
},
{
"answer_id": 23290270,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nstatic char* watched2;\n\n__attribute__((constructor))\nstatic void init_static_vars()\n{\n printf(\"variable (%p) is initialazed, initial value (%p)\\n\", &watched2, watched2);\n watched2=malloc(1024);\n}\n\n\n__attribute__((destructor))\nstatic void destroy_static_vars()\n{\n printf(\"variable (%p), value( %p) goes out of scope\\n\", &watched2, watched2);\n free(watched2);\n}\n\nint main(void)\n{\n printf(\"exit from main, variable (%p) value(%p) is static\\n\", &watched2, watched2);\n return 0;\n}\n >./example\nvariable (0x600aa0) is initialazed, initial value ((nil))\nexit from main, variable (0x600aa0) value(0x16df010) is static\nvariable (0x600aa0), value( 0x16df010) goes out of scope\n"
},
{
"answer_id": 55892374,
"author": "smart master",
"author_id": 8237156,
"author_profile": "https://Stackoverflow.com/users/8237156",
"pm_score": 0,
"selected": false,
"text": "my implementation of raii for c in pure c and minimal asm\n@ https://github.com/smartmaster/sml_clang_raii\n\n**RAII for C language in pure C and ASM**\n\n**featurs : **\n\n-easy and graceful to use\n- no need seperate free cleanup functions\n- able to cleanup any resources or call any function on scope exits\n\n\n**User guide : **\n\n-add source files in src folder to your project\n-include sml_raii_clang.h in.c file\n-annote resource and its cleanup functions\n void sml_raii_clang_test()\n{\n //start a scope, the scope name can be any string\n SML_RAII_BLOCK_START(0);\n\n\n SML_RAII_VOLATILE(WCHAR*) resA000 = calloc(128, sizeof(WCHAR)); //allocate memory resource\n SML_RAII_START(0, resA000); //indicate starting a cleanup code fragment, here 'resA000' can be any string you want\n if (resA000) //cleanup code fragment\n {\n free(resA000);\n resA000 = NULL;\n }\n SML_RAII_END(0, resA000); //indicate end of a cleanup code fragment\n\n\n //another resource\n //////////////////////////////////////////////////////////////////////////\n SML_RAII_VOLATILE(WCHAR*) res8000 = calloc(128, sizeof(WCHAR));\n SML_RAII_START(0, D000);\n if (res8000)\n {\n free(res8000);\n res8000 = NULL;\n }\n SML_RAII_END(0, D000);\n\n\n //scope ended, will call all annoated cleanups\n SML_RAII_BLOCK_END(0);\n SML_RAII_LABEL(0, resA000); //if code is optimized, we have to put labels after SML_RAII_BLOCK_END\n SML_RAII_LABEL(0, D000);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15109/"
] |
368,414 | <p>I have a view which is selecting rows from a table in a different database. I'd like to grant select access to the view, but not direct access to the base table. The view has a where clause restricting the number of rows.</p>
<p>Can I grant select to the view and not the base table, or do I need to switch to a stored procedure? I would rather not do it the latter way.</p>
| [
{
"answer_id": 368428,
"author": "James Orr",
"author_id": 41457,
"author_profile": "https://Stackoverflow.com/users/41457",
"pm_score": 4,
"selected": false,
"text": "GRANT SELECT ON [viewname] TO [user]\n"
},
{
"answer_id": 6383578,
"author": "Kosmo",
"author_id": 802935,
"author_profile": "https://Stackoverflow.com/users/802935",
"pm_score": 4,
"selected": false,
"text": "ALTER AUTHORIZATION ON test.vTestView TO dbo"
},
{
"answer_id": 58541021,
"author": "Amani",
"author_id": 12268685,
"author_profile": "https://Stackoverflow.com/users/12268685",
"pm_score": 0,
"selected": false,
"text": "Create view Schema1.viewName1 as (select * from plaplapla) Schema1 Create view Schema2.viewName2 as (select * from schema1.viewName1) schema2 select * from viewName2 deleted viewNmae1 from Schema1 ViewName2"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37591/"
] |
368,430 | <p>I am working on creating a .asmx webservice to meet the specific needs of an integration environment and for the life of me I cannot figure out how to get one section of it to work. The key is that the request WSDL needs to be something like the following. (Note I removed the soap envelope and namespace information)</p>
<pre><code><methodOne>
<myValue>string</myValue>
<myDemoGroup>
<myDemoGroupItem>string</myDemoGroupItem>
<myDemoGroupItem2>string</myDemoGroupItem2>
</myDemoGroup>
<myComplexGroup>
<mySubStructure>
<subItem1>string</subItem1>
<subItem2>string</subItem2>
</mySubStructure>
</myComplexGroup
</methodOne>
</code></pre>
<p>Now, I know how to take care of most of this, the method one tag is handled by the name of my parameter, and then the items inside are simply elements in the class. SO something like this gets everything except for "MyComplexGroup"</p>
<pre><code>[Web Method]
public void MyWebMethod(MyWebMethodRequest methodOne)
{
//Do my stuff
}
public class MyWebMethodRequest
{
public string myValue {get; set;}
public MyDemoGroupInfo myDemoGroup {get; set;}
}
public class MyDemoGroupInfo
{
public string myDemoGroupItem {get; set;}
public string myDemoGroupItem2 {get; set;}
}
</code></pre>
<p>The question is how to I define the "myComplexGroup" to allow the creation of multiple mySubStructure elements, while still outputting all items to the WSDL.</p>
<p>If I continue on and do something like this</p>
<pre><code>public class MyComplexGroupInfo
{
public List<MySubStructureInfo> mySubStructure {get; set;}
}
public class MySubStructureInfo
{
public string subItem1 {get; set;}
public string subItem2 {get; set;}
}
</code></pre>
<p>I can then add <code>public MyComplexGroupInfo myComplexGroup {get; set;}</code> to the object and I will get part of it, but instead of listing subItem1 and subItem2 it simply says MySubStructureInfo with nil set to one.</p>
<p>How can I get around this?</p>
| [
{
"answer_id": 368479,
"author": "Ihar Voitka",
"author_id": 46313,
"author_profile": "https://Stackoverflow.com/users/46313",
"pm_score": 3,
"selected": true,
"text": "wsdl.exe /serverInterface"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13279/"
] |
368,432 | <p>Is there any way to set the style for the lineends for the TCanvas.LineTo method? It seems to default to rounded ends, which looks very bad for several lines in a row of different colours when Pen.Width is set to a large value (e.g. 9).</p>
<p>It looks like this (rounded ends):</p>
<pre><code> ********........******
**********........******
**********........******
********........******
</code></pre>
<p>(where * is e.g. blue and . is yellow)</p>
<p>It is even worse if the two outer lines are drawn after the middle line:</p>
<pre><code> ********........******
**********......********
**********......********
********........******
</code></pre>
<p>I'd like it to look like this (streight ends):</p>
<pre><code> ********........******
********........******
********........******
********........******
</code></pre>
<p>Pen does not seem to offer any setting for this and neither does the LineTo method. Is there maybe a windows API function I could call?</p>
| [
{
"answer_id": 368606,
"author": "Uli Gerhardt",
"author_id": 1431618,
"author_profile": "https://Stackoverflow.com/users/1431618",
"pm_score": 3,
"selected": true,
"text": "PS_ENDCAP_* PS_JOIN_*"
},
{
"answer_id": 59089189,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "procedure TForm1.FormCreate(Sender: TObject);\n var LogBrush:TLOGBRUSH;\nbegin\n ZeroMemory(@LogBrush, SizeOf(LogBrush));\n LogBrush.lbColor:=ColorToRGB(Canvas.Pen.Color);\n LogBrush.lbHatch:=0;\n\n DeleteObject(Canvas.Pen.Handle);\n Canvas.Pen.Handle:=ExtCreatePen(PS_Geometric or PS_Solid or PS_EndCap_Square or PS_Join_Miter, 10, LogBrush, 0, nil);\nend;\n\nprocedure TForm1.FormPaint(Sender: TObject);\nbegin\n Canvas.MoveTo(0, 0);\n Canvas.LineTo(50, 50);\nend; \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21506/"
] |
368,438 | <p>I have to work on some code that's using generic lists to store a collection of custom objects.</p>
<p>Then it does something like the following to check if a given object's in the collection and do something if so:</p>
<pre><code>List<CustomObject> customObjects;
//fill up the list
List<CustomObject> anotherListofCustomObjects;
//fill it up
//...
foreach (CustomObject myCustomObject in customObjects)
{
if (anotherListofCustomObjects.Contains(myCustomObject))
{
//do stuff
}
}
</code></pre>
<p>Problem is is taking forever to process 7000 objects like that.</p>
<p>This is not my code - I am just trying to come up options to improve it - Looks to me it would be much faster to use a dictionary to get the stuff by key instead of looping through the whole collection like the above.</p>
<p>Suggestions?</p>
| [
{
"answer_id": 368457,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "Dictionary<CustomObject,CustomObject> ...\n ContainsKey GetHashCode() Equals() IEquatable<CustomObject> CustomObject IEqualityComparer<CustomObject>"
},
{
"answer_id": 368465,
"author": "Frans Bouma",
"author_id": 44991,
"author_profile": "https://Stackoverflow.com/users/44991",
"pm_score": 3,
"selected": false,
"text": "foreach(CustomObject c in customObjects.Intersect(anotherListOfCustomObjects))\n{\n // do stuff.\n}\n"
},
{
"answer_id": 368486,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "System.Collections.ObjectModel.KeyedCollection<TKey, TItem>"
},
{
"answer_id": 368548,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "BinarySearch HashSet<CustomObject> HashSet<CustomObject>"
},
{
"answer_id": 368841,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 0,
"selected": false,
"text": "new HashSet<CustomObject>().Join()\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
368,450 | <p>Is there a tool that will show me what applications are writing to the hard drive in real time? I'm thinking something like Task Manager but for I/O. I've got a number of background processes running, and can never tell when Visual Studio is holding everything up, or some other process is hogging the disk (especially when the processor is running at less than 20%).</p>
| [
{
"answer_id": 30905723,
"author": "duhaime",
"author_id": 1727392,
"author_profile": "https://Stackoverflow.com/users/1727392",
"pm_score": 2,
"selected": false,
"text": "Task Manager Performance Resource Monitor"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
368,459 | <p>For example I have two tables. The first table is student while the second table are the courses that the a student is taking. How can I use a select statement so that I can see two columns student and courses so that the courses are separated by commas.</p>
<p>Thanks.</p>
| [
{
"answer_id": 368489,
"author": "Ian Varley",
"author_id": 37539,
"author_profile": "https://Stackoverflow.com/users/37539",
"pm_score": 0,
"selected": false,
"text": "SELECT \n S.*,\n SC.*\n FROM\n Students S\n INNER JOIN Student_Courses SC\n ON S.student_id = SC.student_id\n"
},
{
"answer_id": 368495,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 0,
"selected": false,
"text": "'Jade', 'Math, English, History'\n'Kieveli', 'History, Biology, Physics'\n CREATE FUNCTION commacourselist(@studentname varchar(100))\nRETURNS @List varchar(4096)\nAS\nBEGIN\n\nDECLARE @coursename varchar(100)\n\nDECLARE FOR\nSELECT course.name FROM course WHERE course.studentname = @studentname\nOPEN coursecursor\n\nFETCH NEXT FROM coursecursor INTO @coursename \nWHILE @@FETCH_STATUS = 0\nBEGIN\n IF @List = ''\n BEGIN\n SET @List = @coursename\n END\n ELSE\n BEGIN\n SET @List = @List + ',' + @coursename \n END\n FETCH NEXT FROM coursecursor INTO @coursename \nEND\nCLOSE coursecursor \nDEALLOCATE coursecursor \n\nRETURN\nEND\nGO\n SELECT student.name, \n commacourselist( student.name ) \nFROM student\n"
},
{
"answer_id": 368650,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 5,
"selected": true,
"text": "Students(\n STU_PKEY Int Identity(1,1) Constraint PK_Students_StuPKey Primary Key,\n STU_NAME nvarchar(64)\n)\n\nCourses(\n CRS_PKEY Int Identity(1, 1) Constraint PK_Courses_CrsPKey Primary Key,\n STU_KEY Int Constraint FK_Students_StuPKey Foreign Key References Students(STU_PKEY),\n CRS_NAME nvarchar(64)\n)\n Select s.STU_PKEY, s.STU_NAME As Student,\n Stuff((\n Select ',' + c.CRS_NAME\n From Courses c\n Where s.STU_PKEY = c.STU_KEY\n For XML Path('')\n ), 1, 1, '') As Courses \nFrom Students s\nGroup By s.STU_PKEY, s.STU_NAME\n"
},
{
"answer_id": 5717753,
"author": "D. Kermott",
"author_id": 715362,
"author_profile": "https://Stackoverflow.com/users/715362",
"pm_score": 2,
"selected": false,
"text": "create table Project (ProjectId int, Description varchar(50));\ninsert into Project values (1, 'Chase tail, change directions');\ninsert into Project values (2, 'ping-pong ball in clothes dryer');\n\ncreate table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));\ninsert into ProjectResource values (1, 1, 'Adam');\ninsert into ProjectResource values (1, 2, 'Kerry');\ninsert into ProjectResource values (1, 3, 'Tom');\ninsert into ProjectResource values (2, 4, 'David');\ninsert into ProjectResource values (2, 5, 'Jeff');\n\nSELECT *, \n (SELECT Name + ' ' AS [text()] \n FROM ProjectResource pr \n WHERE pr.ProjectId = p.ProjectId \n FOR XML PATH ('')) \nAS ResourceList \nFROM Project p\n\n-- ProjectId Description ResourceList\n-- 1 Chase tail, change directions Adam Kerry Tom \n-- 2 ping-pong ball in clothes dryer David Jeff \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,463 | <p>We are in the process of designing a simple service-oriented architecture using WCF as the implementation framework. There are a handful of services that a few applications use. These services are mostly used internally, so a basic authentication and authorization scheme (such as Windows-based) is enough.</p>
<p>We want, however, expose some of the services to some business partners. The set of services they have access to depend on the contract. Kind of a standard architecture.</p>
<p>I think we can implement a <em>service gateway</em> which authenticates the requests and relays them to the correct internal service endpoint (this resembles simple ESB), so we can centralize the authentication/authorization code and expose one single endpoint to the world. I looked at some available ESB toolkits, but they seem way too complex for this purpose. We do not need to integrate a lot of different services, but just to expose some of them to the Internet.</p>
<p>How can I design and implement such a relay/router in WCF, keeping it very simple? I have read <a href="http://www.microsoft.com/mspress/books/9610.aspx" rel="nofollow noreferrer">Inside Windows Communication Foundation</a>, which is a good book, but I'm still not confident enough on how to begin.</p>
| [
{
"answer_id": 368536,
"author": "Joseph DeCarlo",
"author_id": 46362,
"author_profile": "https://Stackoverflow.com/users/46362",
"pm_score": 3,
"selected": true,
"text": "[OperationContract(Namespace=\"www.fu.com\", Action=\"*\")]\nvoid CallThis(Message msg);\n"
},
{
"answer_id": 368801,
"author": "Dario Solera",
"author_id": 16026,
"author_profile": "https://Stackoverflow.com/users/16026",
"pm_score": 2,
"selected": false,
"text": "[OperationContract(Action=\"*\", ReplyAction=\"*\")]\nMessage CallThis(Message msg);\n public Message CallThis(Message message) {\n MessageBuffer buffer = message.CreateBufferedCopy(524288);\n Message output = buffer.CreateMessage();\n output.Headers.To = <INTERNAL_SERVICE_URI>;\n\n BasicHttpBinding binding = new BasicHttpBinding();\n IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(<INTERNAL_SERVICE_URI>);\n factory.Open();\n\n IRequestChannel channel = factory.CreateChannel(new EndpointAddress(<INTERNAL_SERVICE_URI>));\n channel.Open();\n\n Message result = channel.Request(output);\n\n message.Close();\n output.Close();\n factory.Close();\n channel.Close();\n\n return result;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16026/"
] |
368,468 | <p>i wonder if there is a simple way to remove already registered types from a unity container or at least replace existing Interface/Type mappings with another one.
is it enough to just map another class type to an interface and the old one is overwritten?</p>
<hr>
<p>this should not happen very often. actually hardly any time, but there are situations were i want to replace a service implemeting some interface with another without having the other parts disturbed.</p>
| [
{
"answer_id": 5437437,
"author": "Eric Bock",
"author_id": 70863,
"author_profile": "https://Stackoverflow.com/users/70863",
"pm_score": 4,
"selected": false,
"text": "\npublic interface IService\n{\n void DoSomething();\n}\n\npublic class SomeService : IService\n{\n public void DoSomething();\n}\n\npublic class AnotherService : IService\n{\n public void DoSomething();\n}\n \ncontainer.RegisterType<IService, SomeService>();\n \ncontainer.RegisterType<IService, AnotherService>();\n \ncontainer.RegisterType<IService>(new InjectionFactory(x =>\n{\n // this would be some complicated procedure\n return new AnotherService();\n}));\n \ncontainer.RegisterType<IService, AnotherService>(new InjectionFactory(x =>\n{\n return new AnotherService();\n}));\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
368,480 | <p>I am trying to display an HTML page inside another SharePoint webpart page.</p>
<p>I used the Out-of-the-box page viewer webpart, but the page viewer webpart displays a disabled scrollbar inside it.</p>
<p>I also tried using a content editor webpart with an IFRAME tag in it, but still it didnt't work.</p>
<p>This is the code i used in the content editor webpart. </p>
<pre><code><iframe name="Iframe" src="URL1" scrolling="no"
FRAMEBORDER="0" style="width:100%; border:0; height:100%; overflow:hidden;">
</iframe>
</code></pre>
| [
{
"answer_id": 9439688,
"author": "Karlo",
"author_id": 1231877,
"author_profile": "https://Stackoverflow.com/users/1231877",
"pm_score": 2,
"selected": false,
"text": "#s4-workspace {\n\n overflow-y: hidden !important;\n\n overflow-x: hidden !important;\n\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
368,490 | <p>I am looking to determine from a large code base, what files are actually being used over a period of time. I need to know about CFM pages and CFCs as well as any included CFM files etc. </p>
<p>I know I can get <em>some</em> of this info using logging in application.cfm, or by using IIS, but I will still be missing any include files and any CFCs used. </p>
<p>Is there any way to get CF to log every file it executes? Ideally I would like to keep any new coding to a minimum or just in one place. </p>
<p>Thanks,
Ciarán </p>
| [
{
"answer_id": 371405,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 3,
"selected": true,
"text": "classic.cfm"
},
{
"answer_id": 383266,
"author": "Stewart Robinson",
"author_id": 47424,
"author_profile": "https://Stackoverflow.com/users/47424",
"pm_score": -1,
"selected": false,
"text": "<cfparam name=\"server.st_FileLog\" default=\"#structNew()#\">\n<cfparam name=\"server.st_FileLog[thisFile]\" default=\"1\">\n <cfoutput><code>#structKeyList(server.st_FileLog,chr(13))#</code></cfoutput>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446733/"
] |
368,494 | <p>I have a WCF service that has been hosted on a Windows Service and uses the BasicHttp endpoint to serve Windows Mobile devices that has been connected to it.</p>
<p>The problem is that with the Device Emulator. I can connect to the service and using it without any problems, but with an actual device. I receive the error:</p>
<blockquote>
<p>WCF The request failed with HTTP status 405: Method Not Allowed.</p>
</blockquote>
<p>I have used following code to implement the service.</p>
<pre><code>BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.UseDefaultWebProxy = false;
m_ServiceHost.AddServiceEndpoint(typeof(IKooft), basicHttpBinding, "KooftService");
m_ServiceHost.Open();
</code></pre>
<p>How can I solve this problem?</p>
| [
{
"answer_id": 29384299,
"author": "Oğuzhan Soykan",
"author_id": 3514288,
"author_profile": "https://Stackoverflow.com/users/3514288",
"pm_score": 1,
"selected": false,
"text": "[OperationContract]\n[WebInvoke(Method = \"POST\", ResponseFormat = WebMessageFormat.Json)]\nstring CheckService();\n WebInvoke Method=\"POST\""
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34623/"
] |
368,505 | <p>Is it possible to select column data using the ordinal_position for a table column? I know using ordinal positions is a bad practice but for a one-off data import process I need to be able to use the ordinal position to get the column data.</p>
<p>So for example </p>
<pre><code>create table Test(
Col1 int,
Col2 nvarchar(10)
)
</code></pre>
<p>instead of using</p>
<pre><code>select Col2 from Test
</code></pre>
<p>can I write</p>
<pre><code>select "2" from Test -- for illustration purposes only
</code></pre>
| [
{
"answer_id": 368525,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": false,
"text": "select table_name, column_name, ordinal_position, data_type\nfrom information_schema.columns\norder by 1,3\n"
},
{
"answer_id": 368555,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 3,
"selected": false,
"text": "select * from information_schema.columns\n"
},
{
"answer_id": 368578,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 4,
"selected": false,
"text": "declare @col1 as varchar(128)\ndeclare @col2 as varchar(128)\ndeclare @sq1 as varchar(8000) \n\nselect @col1 = column_name from information_schema.columns where table_name = 'tablename'\nand ordinal_position = @position\n\nselect @col2 = column_name from information_schema.columns where table_name = 'tablename'\nand ordinal_position = @position2\n\nset @sql = 'select ' + col1 ',' + col2 'from tablename' \n\nexec(@sql)\n"
},
{
"answer_id": 6002816,
"author": "craigl",
"author_id": 753734,
"author_profile": "https://Stackoverflow.com/users/753734",
"pm_score": 1,
"selected": false,
"text": "declare @tmp table(field1 sql_variant, field2 int, field3 sql_variant)\n\ninsert into @tmp\nselect * from Test\n\nselect field2 from @tmp\n"
},
{
"answer_id": 32009395,
"author": "Pavel Sinkevich",
"author_id": 1839430,
"author_profile": "https://Stackoverflow.com/users/1839430",
"pm_score": 4,
"selected": false,
"text": "select NULL as C1, NULL as C2 where 1 = 0 \n-- Returns empty table with predefined column names\nunion all\nselect * from Test \n-- There should be exactly 2 columns, but names and data type doesn't matter\n"
},
{
"answer_id": 34741150,
"author": "Damien Goor",
"author_id": 2021761,
"author_profile": "https://Stackoverflow.com/users/2021761",
"pm_score": 1,
"selected": false,
"text": " SELECT \n CASE YourColumnNumber \n WHEN \"1\" THEN Col1\n WHEN \"2\" THEN Col2\n ELSE \"?\"\n END AS Result\n FROM Test\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] |
368,542 | <p>I was thinking of implementing shortcut keys in a pet web application, I am developing for me. I am using c# and asp.net. </p>
<p>I have seen very few web-sites( frankly I remember only g-mail), which have shortcut keys. </p>
<p>Has anyone ever implemented shortcut keys for a web application, if yes how to go about it?</p>
<p>Thanks. </p>
| [
{
"answer_id": 20795304,
"author": "pratik patel",
"author_id": 3106345,
"author_profile": "https://Stackoverflow.com/users/3106345",
"pm_score": -1,
"selected": false,
"text": "use this javascript on your master page this work using keycode.........\n\n\n------------------------------------------ \n\nvar isfocused=false; \n document.onkeydown = overrideKeyboardEvent;\ndocument.onkeyup = overrideKeyboardEvent;\nvar keyIsDown = {};\nvar get_focused=\"\";\nfunction overrideKeyboardEvent(e){\n switch(e.type){\n case \"keydown\":\n if(!keyIsDown[e.keyCode]){\n keyIsDown[e.keyCode] = true;\n // do key down stuff here\n if (e.keyCode == 40) {\n var t = new Array;\n t = document.getElementsByTagName(\"input\");\n var n = \"1\";\n for (var r = 0; r < t.length; r++) {\n if (t[r].type == \"checkbox\") {\n var i = document.cookie.split(\";\");\n var s = y = i[0].substr(i[0].indexOf(\"=\") + 1);\n if (s.toLowerCase().indexOf(\"active\") != -1) {\n if (n == \"2\") {\n document.getElementById(t[r].id).focus();\n document.cookie = \"aa\" + \"=\" + t[r].id;\n return false\n }\n if (t[r].id == s) {\n n = \"2\"\n }\n } else {\n document.getElementById(t[r].id).focus();\n document.cookie = \"aa\" + \"=\" + t[r].id;\n return false\n }\n }\n }\n }\n if( e.keyCode==115)\n { e.preventDefault();\n var c = new Array();\n c = document.getElementsByTagName('input');\n for (var i=0;i<c.length;i++)\n {\n if(c[i].type=='submit' && c[i].value=='Submit' || c[i].type=='submit' && c[i].value=='Summary Report' )\n { \n e.preventDefault();\n document.getElementById(''+c[i].id+'').click();\n }\n }\n\n return ;\n\n }\n if( e.keyCode==27 )\n {\n window.location = document.referrer;\n }\n if( e.keyCode==46 )\n {\n var c=new Array();\n c=document.getElementsByTagName('tr');\n for(var i=0;i<c.length;i++)\n {\n if(c[i].onclick!=null)\n {\n if(c[i].onclick.toString().indexOf('OnUserSelected')!=-1 && c[i].onclick.toString().indexOf(''+get_focused+'')!=-1)\n { \n var children =new Array();\n if(c[i].innerHTML.indexOf('remove')!=-1)\n {\n children = c[i].innerHTML.split('remove');\n var gg=children[1];\n var get1=new Array();\n get1=gg.split('id=\"');\n\n // document.getElementById('ctl00_ContentPlaceHolder2_hidden111').value='1111';\n var a= document.getElementById(''+get1[1]+'remove').click();\n return false;\n //__doPostBack(''+get1[1]+'remove','');\n }\n else\n {\n children = c[i].innerHTML.split('delete');\n var gg=children[1];\n var get1=new Array();\n get1=gg.split('id=\"');\n\n // document.getElementById('ctl00_ContentPlaceHolder2_hidden111').value='1111';\n var a= document.getElementById(''+get1[1]+'d`enter code here`elete').click();\n return false;\n }\n\n\n }\n }\n }\n }\n if( e.keyCode==112 )\n { \n e.preventDefault();\n var c=new Array();\n c=document.getElementsByTagName('a');\n\n for(i=0;i<c.length;i++)\n {\n if(c[i].innerText.indexOf('Add New')!=-1 || c[i].innerText.indexOf('Back to')!=-1)\n {\n window.location=''+c[i].href+'';\n }\n }\n\n }\n if( e.keyCode==113)\n {\n if(get_focused!=\"\")\n {\n var c=new Array();\n c=document.getElementsByTagName('input');\n\n for(var i=0;i<c.length;i++)\n {\n if(c[i].type=='hidden')\n {\n\n if(c[i].id.indexOf('hidden111')!=-1)\n {\n document.getElementById(''+c[i].id+'').value='00';\n document.getElementById(''+c[i].id+'').value=get_focused;\n __doPostBack(c[i].id,\"\");\n }\n } \n }\n\n\n }\n }\n if (e.keyCode == 38) {\n\n var t = new Array;\n t = document.getElementsByTagName(\"input\");\n var n = \"1\";\n for (var r = 0; r < t.length; r++) {\n if (t[r].type == \"checkbox\") {\n var i = document.cookie.split(\";\");\n var s = y = i[0].substr(i[0].indexOf(\"=\") + 1);\n if (s.toLowerCase().indexOf(\"active\") != -1) {\n if (t[r].id == s) {\n n = \"2\"\n }\n if (n == \"2\") {\n var f = 0;\n while (f == 0) {\n if (t[r - 1].type == \"checkbox\") {\n f = 1\n } else {\n r--\n }\n }\n document.getElementById(t[r - 1].id).focus();\n document.cookie = \"aa\" + \"=\" + t[r - 1].id;\n return false\n }\n }\n }\n }\n }\n }\n break;\n case \"keyup\":\n delete(keyIsDown[e.keyCode]);\n // do key up stuff here\n break;\n }\n\n //e.preventDefault();\n return true;\n}\nfunction disabledEventPropagation(e) {\n if (e) {\n if (e.stopPropagation) {\n e.stopPropagation()\n } else if (window.event) {\n window.event.cancelBubble = true\n }\n }\n}\ndocument.body.setAttribute(\"onunload\",\"getdeleted()\");\nfunction getdeleted()\n{\n document.cookie=\"aa\" + \"=\" +\"\";\n}\n0\nfunction OnUserSelected(source,eventArgs) {\n\n if(document.getElementById('ctl00_ContentPlaceHolder2_hidden111').value!='1111')\n { \n\n var hdnValueID = 'ctl00_ContentPlaceHolder2_hidden111';\n try\n {\n document.getElementById(hdnValueID).value =source;\n\n document.getElementById(hdnValueID).value = eventArgs;\n __doPostBack(hdnValueID, \"\");\n }\n\n catch(errorr)\n\n {\n alert(errorr);\n }\n }\n else\n {\n get_focused =eventArgs;\n\n document.getElementById('ctl00_ContentPlaceHolder2_hidden111').value='';\n\n\n }\n }\n"
},
{
"answer_id": 25562657,
"author": "Anil Kumar",
"author_id": 3989181,
"author_profile": "https://Stackoverflow.com/users/3989181",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n if (window.captureEvents) {\n window.captureEvents(Event.KeyUp);\n window.onkeyup = executeCode;\n }\n else if (window.attachEvent) {\n document.attachEvent('onkeyup', executeCode);\n }\n\n function executeCode(evt) {\n if (evt == null) {\n evt = window.event;\n }\n var theKey = parseInt(evt.keyCode, 10);\n switch (theKey) {\n case 35: // End\n document.getElementById(\"<%=btnSave.ClientID%>\").click();\n //document.getElementById('ctl00_ContentPlaceHolder1_btnHome').click(); \n\n break;\n case 36: // F8\n document.getElementById('btnreset').click();\n break;\n case 120: // F9\n // document.getElementById('Button1').click();\n\n break;\n case 87: //w\n if (window.event.altKey)\n document.getElementById('buttonid').click();\n break;\n }\n evt.returnValue = false;\n return false;\n }\n\n</script>\n\n\n <asp:Button ID=\"btnSave\" runat=\"server\" Text=\"Button\" />\n </asp:Content>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
</code></pre>
| [
{
"answer_id": 368550,
"author": "Mapad",
"author_id": 28165,
"author_profile": "https://Stackoverflow.com/users/28165",
"pm_score": 6,
"selected": true,
"text": "def determine_period(universe_array):\n period=0\n tmp=universe_array\n while True:\n tmp=apply_rules(tmp)#aplly_rules is a another function\n period+=1\n if numpy.array_equal(tmp,universe_array) is True:\n return period\n if period>12: #i wrote this line to stop it..but seems its doesnt work....help..\n return 0\n else: \n return period\n break while True break return def determine_period(universe_array):\n period=0\n tmp=universe_array\n while True:\n tmp=apply_rules(tmp)#aplly_rules is a another function\n period+=1\n if numpy.array_equal(tmp,universe_array) is True:\n break\n if period>12: #i wrote this line to stop it..but seems its doesnt work....help..\n period = 0\n break\n\n return period\n"
},
{
"answer_id": 368554,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "def determine_period(universe_array):\n period=0\n tmp=universe_array\n while period<12:\n tmp=apply_rules(tmp)#aplly_rules is a another function\n if numpy.array_equal(tmp,universe_array) is True:\n break \n period+=1\n\n return period\n"
},
{
"answer_id": 369204,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "is if numpy.array_equal(tmp,universe_array) is True:\n break\n if numpy.array_equal(tmp,universe_array):\n break\n is"
},
{
"answer_id": 372313,
"author": "Suraj",
"author_id": 39446,
"author_profile": "https://Stackoverflow.com/users/39446",
"pm_score": 0,
"selected": false,
"text": "def determine_period(universe_array):\n tmp = universe_array\n for period in xrange(1, 13):\n tmp = apply_rules(tmp)\n if numpy.array_equal(tmp, universe_array):\n return period\n return 0\n"
},
{
"answer_id": 68153775,
"author": "tkirk1222",
"author_id": 16310422,
"author_profile": "https://Stackoverflow.com/users/16310422",
"pm_score": 0,
"selected": false,
"text": "while True:\n line = input('> ')\n if line == 'done':\n break\n print(line)\nprint('Done!')\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44354/"
] |
368,551 | <p>Given a list of strings, what is the best method for concatenating these strings into a comma separated list with no comma at the end. (VB.NET or C#) (Using either StringBuilder or String Concat.)</p>
<pre><code>Dim strResult As String = ""
Dim lstItems As New List(Of String)
lstItems.Add("Hello")
lstItems.Add("World")
For Each strItem As String In lstItems
If strResult.Length > 0 Then
strResult = strResult & ", "
End If
strResult = strResult & strItem
Next
MessageBox.Show(strResult)
</code></pre>
| [
{
"answer_id": 368564,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "Dim Result As String\nDim Items As New List(Of String)\nItems.Add(\"Hello\")\nItems.Add(\"World\")\n\nResult = String.Join(\",\", Items)\nMessageBox.Show(Result)\n Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As String\n Dim delim As String = \"\"\n Dim result As New Text.StringBuilder(\"\")\n\n For Each item As String In items\n If Not IgnoreEmptyEntries OrElse Not String.IsNullOrEmpty(item) Then\n result.Append(delim).Append(item)\n delim = delimiter\n End If\n Next\n Return result.ToString()\nEnd Function\n Dim Result As String = String.Join(\",\" Items.Where(Function(i) Not String.IsNullOrWhitespace(i)))\n"
},
{
"answer_id": 368569,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 1,
"selected": false,
"text": "For Each Item In Collection:\n Add Item To String\n If Not Last Item, Add Comma\n For Each Item In Collection:\n If Not First Item, Add Comma\n Add Item To String\n"
},
{
"answer_id": 368588,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "Separator = \"\"\nFor Each Item In Collection\n Add Separator + Item To String\n Separator = \", \"\n"
},
{
"answer_id": 368598,
"author": "Pete Montgomery",
"author_id": 40759,
"author_profile": "https://Stackoverflow.com/users/40759",
"pm_score": 3,
"selected": false,
"text": "lstItems.ToConcatenatedString(s => s, \", \")\n lstItems\n .Where(s => s.Length > 0)\n .ToConcatenatedString(s => s, \", \")\n public static class EnumerableExtensions\n{\n\n /// <summary>\n /// Creates a string from the sequence by concatenating the result\n /// of the specified string selector function for each element.\n /// </summary>\n public static string ToConcatenatedString<T>(\n this IEnumerable<T> source,\n Func<T, string> stringSelector)\n {\n return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);\n }\n\n /// <summary>\n /// Creates a string from the sequence by concatenating the result\n /// of the specified string selector function for each element.\n /// </summary>\n /// <param name=\"separator\">The string which separates each concatenated item.</param>\n public static string ToConcatenatedString<T>(\n this IEnumerable<T> source,\n Func<T, string> stringSelector,\n string separator)\n {\n var b = new StringBuilder();\n bool needsSeparator = false; // don't use for first item\n\n foreach (var item in source)\n {\n if (needsSeparator)\n b.Append(separator);\n\n b.Append(stringSelector(item));\n needsSeparator = true;\n }\n\n return b.ToString();\n }\n}\n"
},
{
"answer_id": 368641,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 3,
"selected": false,
"text": "Dim Result As String\nDim Items As New List(Of String)\nItems.Add(\"Hello\")\nItems.Add(\"World\")\nResult = String.Join(\",\", Items.ToArray().Where(Function(i) Not String.IsNullOrEmpty(i))\nMessageBox.Show(Result)\n"
},
{
"answer_id": 368769,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 1,
"selected": false,
"text": "public static string ListToCsv<T>(List<T> list)\n {\n CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();\n\n list.ForEach(delegate(T item)\n {\n commaStr.Add(item.ToString());\n });\n\n\n return commaStr.ToString();\n }\n"
},
{
"answer_id": 370305,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 0,
"selected": false,
"text": "\nstrResult = \"\"\nstrSeparator = \"\"\nfor i as integer = 0 to arrItems.Length - 1\n if arrItems(i) <> \"test\" and arrItems(i) <> \"point\" then\n strResult = strResult & strSeparator & arrItem(i)\n strSeparator = \", \"\n end if\nnext\n"
},
{
"answer_id": 370372,
"author": "awaisj",
"author_id": 46520,
"author_profile": "https://Stackoverflow.com/users/46520",
"pm_score": 0,
"selected": false,
"text": "Dim strResult As String = \"\"\nDim separator = \",\"\nDim lstItems As New List(Of String)\nlstItems.Add(\"Hello\")\nlstItems.Add(\"World\")\nFor Each strItem As String In lstItems\n strResult = String.Concat(strResult, separator)\nNext\nstrResult = strResult.TrimEnd(separator.ToCharArray())\nMessageBox.Show(strResult)\n String.TrimEnd() function"
},
{
"answer_id": 799540,
"author": "Daniel Fortunov",
"author_id": 5975,
"author_profile": "https://Stackoverflow.com/users/5975",
"pm_score": 3,
"selected": false,
"text": "StringBuilder Concat String.Join string result = String.Join(\",\", items.ToArray());\n"
},
{
"answer_id": 1173966,
"author": "Brad",
"author_id": 70130,
"author_profile": "https://Stackoverflow.com/users/70130",
"pm_score": 2,
"selected": false,
"text": "StringBuilder Concat using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Net;\nusing System.Configuration;\n\nnamespace ConsoleApplication\n{\n class Program\n {\n static void Main(string[] args)\n {\n CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();\n string[] itemList = { \"Test1\", \"Test2\", \"Test3\" };\n commaStr.AddRange(itemList);\n Console.WriteLine(commaStr.ToString()); //Outputs Test1,Test2,Test3\n Console.ReadLine();\n }\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21826/"
] |
368,557 | <p>I have a small program to order and sort email messages, outputting to a textfile using <code>$msg->decoded->string</code>. The perl program outputs to <code>stdout</code>, and I redirect it to a txt file. However, gedit is unable to open this text file because of a character set problem, and I would like to know how to restore or set a character set with perl.</p>
<p>The program is now thus:</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
use Mail::Box::Manager;
open (MYFILE, '>>data.txt');
my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
access => 'r',
);
my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";
for my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages)
{
my $to = join( ', ', map { $_->format } $msg->to );
my $from = join( ', ', map { $_->format } $msg->from );
my $date = localtime( $msg->timestamp );
my $subject = $msg->subject;
my $body = $msg->decoded->string;
# Strip all quoted text
$body =~ s/^>.*$//msg;
print MYFILE <<"";
From: $from
To: $to
Date: $date
$body
}
</code></pre>
<p>However I get the same problem that I am unable to open the file with gedit, even though it works with vi or such. If there are non unicode characters in the file, would this break it?</p>
| [
{
"answer_id": 368696,
"author": "Dave Vogt",
"author_id": 35189,
"author_profile": "https://Stackoverflow.com/users/35189",
"pm_score": 1,
"selected": false,
"text": "open my $fh, '>:encoding(UTF-8)', $file;\n binmode(STDOUT, ':encoding(UTF-8)');\n perldoc -f open\nperldoc -f binmode\nperldoc IO::File\n"
},
{
"answer_id": 368748,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": true,
"text": "$message->contentType"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
368,603 | <p>I need to write a 'simple' util to convert from ASCII to EBCDIC? </p>
<p>The Ascii is coming from Java, Web and going to an AS400. I've had a google around, can't seem to find a easy solution (maybe coz there isn't one :( ). I was hoping for an opensource util or paid for util that has already been written. </p>
<p>Like this maybe? </p>
<pre><code>Converter.convertToAscii(String textFromAS400)
Converter.convertToEBCDIC(String textFromJava)
</code></pre>
<p>Thanks, </p>
<p>Scott</p>
| [
{
"answer_id": 368632,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 2,
"selected": false,
"text": "String(byte[] bytes, [int offset, int length,] String enc)"
},
{
"answer_id": 27737881,
"author": "dmolony",
"author_id": 1043868,
"author_profile": "https://Stackoverflow.com/users/1043868",
"pm_score": 0,
"selected": false,
"text": "public static final int[] ebc2asc = new int[256];\npublic static final int[] asc2ebc = new int[256];\n\nstatic\n{\n byte[] values = new byte[256];\n for (int i = 0; i < 256; i++)\n values[i] = (byte) i;\n\n try\n {\n String s = new String (values, \"CP1047\");\n char[] chars = s.toCharArray ();\n for (int i = 0; i < 256; i++)\n {\n int val = chars[i];\n ebc2asc[i] = val;\n asc2ebc[val] = i;\n }\n }\n catch (UnsupportedEncodingException e)\n {\n e.printStackTrace ();\n }\n}\n"
},
{
"answer_id": 29402665,
"author": "leo_con",
"author_id": 4740154,
"author_profile": "https://Stackoverflow.com/users/4740154",
"pm_score": 2,
"selected": false,
"text": "package javaapplication1;\n\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\n\nimport java.nio.charset.CharacterCodingException;\n\nimport java.nio.charset.Charset;\n\nimport java.nio.charset.CharsetDecoder;\n\nimport java.nio.charset.CharsetEncoder;\n\npublic class ConvertBetweenCharacterSetEncodingsWithCharBuffer {\n\n public static void main(String[] args) {\n\n //String cadena = \"@@@@@@@@@@@@@@@ñâæÃÈÄóöó@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ÔÁâãÅÙÃÁÙÄ@ÄÅÂÉã@âæÉãÃÈ@@@@@@@@\";\n String cadena = \"ñâæÃÈÄóöó\";\n System.out.println(Convert(cadena,\"CP1047\",\"ISO-8859-1\"));\n cadena = \"1SWCHD363\";\n System.out.println(Convert(cadena,\"ISO-8859-1\",\"CP1047\"));\n\n }\n\n public static String Convert (String strToConvert,String in, String out){\n try {\n\n Charset charset_in = Charset.forName(out);\n Charset charset_out = Charset.forName(in);\n\n CharsetDecoder decoder = charset_out.newDecoder();\n\n CharsetEncoder encoder = charset_in.newEncoder();\n\n CharBuffer uCharBuffer = CharBuffer.wrap(strToConvert);\n\n ByteBuffer bbuf = encoder.encode(uCharBuffer);\n\n CharBuffer cbuf = decoder.decode(bbuf);\n\n String s = cbuf.toString();\n\n //System.out.println(\"Original String is: \" + s);\n return s;\n\n } catch (CharacterCodingException e) {\n\n //System.out.println(\"Character Coding Error: \" + e.getMessage());\n return \"\";\n\n }\n\n\n}\n\n}\n"
},
{
"answer_id": 41831492,
"author": "Shawn",
"author_id": 7106420,
"author_profile": "https://Stackoverflow.com/users/7106420",
"pm_score": 1,
"selected": false,
"text": "DSPFFD *LIB*/*FILE* Cp1047 Cp37 Cp037"
},
{
"answer_id": 42009452,
"author": "Gustavo Vieira de Souza",
"author_id": 6318424,
"author_profile": "https://Stackoverflow.com/users/6318424",
"pm_score": 1,
"selected": false,
"text": "public class Converter{\n\n public static void main(String[] args) {\n\n Charset charsetEBCDIC = Charset.forName(\"CP037\");\n Charset charsetACSII = Charset.forName(\"US-ASCII\");\n\n String ebcdic = \"(((((((\";\n System.out.println(\"String EBCDIC: \" + ebcdic);\n System.out.println(\"String converted to ASCII: \" + convertTO(ebcdic, charsetEBCDIC, charsetACSII));\n\n String ascII = \"MMMMMM\";\n System.out.println(\"String ASCII: \" + ascII);\n System.out.println(\"String converted to EBCDIC: \" + convertTO(ascII, charsetACSII, charsetEBCDIC));\n }\n\n public static String convertTO(String dados, Charset encondingFrom, Charset encondingTo) {\n return new String(dados.getBytes(encondingFrom), encondingTo);\n }\n}\n"
},
{
"answer_id": 45865294,
"author": "Meower68",
"author_id": 251767,
"author_profile": "https://Stackoverflow.com/users/251767",
"pm_score": 1,
"selected": false,
"text": " AS400PackedDecimal convertedCustId = new AS400PackedDecimal(11, 0);\n byte[] packedCust = convertedCustId.toBytes((int) custId);\n\n String packedCustStr = new String(packedCust, \"Cp037\");\n\n StringBuilder jcommData = new StringBuilder();\n jcommData.append(String.format(\"%6s\", packedCustStr));\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31751/"
] |
368,612 | <p>I have an .Net Froms application that displays web pages through a WebBrowser control.</p>
<p>Is there anyway that I can detect if the control shows a '<em>Page not found</em>' or '<em>Cannot display webpage</em>' error?
There doesn't seem to be any error event handlers.</p>
| [
{
"answer_id": 368734,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 5,
"selected": true,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n SHDocVw.WebBrowser instance = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;\n instance.NavigateError += new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(instance_NavigateError);\n webBrowser1.Navigate(\"http://www.google.com/foo\");\n}\n\nvoid instance_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)\n{\n // Do whatever you want with the error \n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
368,613 | <p>I've got a collection of records to process, and the processing can be parallelized, so I've created an <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html" rel="nofollow noreferrer">ExecutorService</a> (via <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()" rel="nofollow noreferrer">Executors#newCachedThreadPool()</a>). The processing of an individual record is, itself, composed of parallelizable steps, so I'd like to use another <code>ExecutorService</code>. Is there an easy way to make this new one use the same underlying thread pool? Is it even desirable? Thanks.</p>
| [
{
"answer_id": 368671,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 2,
"selected": false,
"text": "public class Task implements Runnable {\n private final ExecutorService threadPool;\n private final SubTask[] subtasks;\n\n public Task(ExecutorService threadPool) {\n this.threadPool = threadPool;\n this.subtasks = createSubtasksIGuess();\n }\n\n public void run() {\n for(SubTask sub : subtasks)\n threadPool.submit(sub);\n }\n}\n"
},
{
"answer_id": 368689,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 4,
"selected": true,
"text": "ExecutorService ExecutorService Executor"
},
{
"answer_id": 368798,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 3,
"selected": false,
"text": "ExecutorService AbstractExecutorService ExecutorService ExecutorService"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] |
368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/" rel="noreferrer">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest it. I would count myself among them, but I do actually use it.</p>
<p>I've used setuptools for enough projects to be aware of its deficiencies, and I would prefer something better. I don't particularly like the egg format and how it's deployed. With all of setuptools' problems, I haven't found a better alternative.</p>
<p>My understanding of tools like <a href="http://pip.openplans.org/" rel="noreferrer">pip</a> is that it's meant to be an easy_install replacement (not setuptools). In fact, pip uses some setuptools components, right?</p>
<p>Most of my packages make use of a setuptools-aware setup.py, which declares all of the dependencies. When they're ready, I'll build an sdist, bdist, and bdist_egg, and upload them to pypi.</p>
<p>If I wanted to switch to using pip, what kind of changes would I need to make to rid myself of easy_install dependencies? Where are the dependencies declared? I'm guessing that I would need to get away from using the egg format, and provide just source distributions. If so, how do i generate the egg-info directories? or do I even need to?</p>
<p>How would this change my usage of virtualenv? Doesn't virtualenv use easy_install to manage the environments?</p>
<p>How would this change my usage of the setuptools provided "develop" command? Should I not use that? What's the alternative?</p>
<p>I'm basically trying to get a picture of what my development workflow will look like.</p>
<p>Before anyone suggests it, I'm not looking for an OS-dependent solution. I'm mainly concerned with debian linux, but deb packages are not an option, for the reasons Ian Bicking outlines <a href="http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/" rel="noreferrer">here</a>.</p>
| [
{
"answer_id": 370062,
"author": "ianb",
"author_id": 20218,
"author_profile": "https://Stackoverflow.com/users/20218",
"pm_score": 6,
"selected": true,
"text": "python -c 'import setuptools; __file__=\"setup.py\"; execfile(__file__)' \\\n install \\\n --single-version-externally-managed\n --single-version-externally-managed python setup.py install setup.py install_requires setup.py python setup.py develop pip install -e svn+http://mysite/svn/Project/trunk#egg=Project src/project setup.py develop pip install -vv"
},
{
"answer_id": 23160495,
"author": "FutureNerd",
"author_id": 310710,
"author_profile": "https://Stackoverflow.com/users/310710",
"pm_score": 2,
"selected": false,
"text": "python.org distribute setuptools setuptools pip pip pyvenv wheel buildout"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
368,642 | <p>I'm getting the error when accessing a Stored Procedure in SQL Server</p>
<pre><code>Server Error in '/' Application.
Procedure or function 'ColumnSeek' expects parameter '@template', which was not supplied.
</code></pre>
<p>This is happening when I call a Stored Procedure with a parameter through .net's data connection to sql <code>(System.data.SqlClient)</code>, even though I am supplying the parameter. Here is my code.</p>
<pre><code>SqlConnection sqlConn = new SqlConnection(connPath);
sqlConn.Open();
//METADATA RETRIEVAL
string sqlCommString = "QCApp.dbo.ColumnSeek";
SqlCommand metaDataComm = new SqlCommand(sqlCommString, sqlConn);
metaDataComm.CommandType = CommandType.StoredProcedure;
SqlParameter sp = metaDataComm.Parameters.Add("@template",SqlDbType.VarChar,50);
sp.Value = Template;
SqlDataReader metadr = metaDataComm.ExecuteReader();
</code></pre>
<p>And my Stored Procedure is:</p>
<pre><code> USE [QCApp]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ColumnSeek]
@template varchar(50)
AS
EXEC('SELECT Column_Name, Data_Type
FROM [QCApp].[INFORMATION_SCHEMA].[COLUMNS]
WHERE TABLE_NAME = ' + @template);
</code></pre>
<p>I'm trying to figure out what I'm doing wrong here.</p>
<p><strong>Edit:</strong> As it turns out, Template was null because I was getting its value from a parameter passed through the URL and I screwed up the url param passing (I was using <code>@</code> for and instead of <code>&</code>)</p>
| [
{
"answer_id": 368659,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "AS\nSELECT Column_Name, ...\nFROM ...\nWHERE TABLE_NAME = @template\n 'Column_Name' WHERE TABLE_NAME = Column_Name EXEC sp_ExecuteSQL"
},
{
"answer_id": 2766541,
"author": "Brian",
"author_id": 121219,
"author_profile": "https://Stackoverflow.com/users/121219",
"pm_score": 8,
"selected": false,
"text": "cmd.CommandType = CommandType.StoredProcedure;\n"
},
{
"answer_id": 4243656,
"author": "sangram",
"author_id": 416482,
"author_profile": "https://Stackoverflow.com/users/416482",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE UserPreference_Search\n @UserPreferencesId int,\n @SpecialOfferMails char(1),\n @NewsLetters char(1),\n @UserLoginId int,\n @Currency varchar(50)\nAS\nDECLARE @QueryString nvarchar(4000)\n\nSET @QueryString = 'SELECT UserPreferencesId,SpecialOfferMails,NewsLetters,UserLoginId,Currency FROM UserPreference'\nIF(@UserPreferencesId IS NOT NULL)\nBEGIN\nSET @QueryString = @QueryString + ' WHERE UserPreferencesId = @DummyUserPreferencesId';\nEND\n\nIF(@SpecialOfferMails IS NOT NULL)\nBEGIN\nSET @QueryString = @QueryString + ' WHERE SpecialOfferMails = @DummySpecialOfferMails';\nEND\n\nIF(@NewsLetters IS NOT NULL)\nBEGIN\nSET @QueryString = @QueryString + ' WHERE NewsLetters = @DummyNewsLetters';\nEND\n\nIF(@UserLoginId IS NOT NULL)\nBEGIN\nSET @QueryString = @QueryString + ' WHERE UserLoginId = @DummyUserLoginId';\nEND\n\nIF(@Currency IS NOT NULL)\nBEGIN\nSET @QueryString = @QueryString + ' WHERE Currency = @DummyCurrency';\nEND\n\nEXECUTE SP_EXECUTESQL @QueryString\n ,N'@DummyUserPreferencesId int, @DummySpecialOfferMails char(1), @DummyNewsLetters char(1), @DummyUserLoginId int, @DummyCurrency varchar(50)'\n ,@DummyUserPreferencesId=@UserPreferencesId\n ,@DummySpecialOfferMails=@SpecialOfferMails\n ,@DummyNewsLetters=@NewsLetters\n ,@DummyUserLoginId=@UserLoginId\n ,@DummyCurrency=@Currency;\n public DataSet Search(int? AccessRightId, int? RoleId, int? ModuleId, char? CanAdd, char? CanEdit, char? CanDelete, DateTime? CreatedDatetime, DateTime? LastAccessDatetime, char? Deleted)\n {\n dbManager.ConnectionString = ConfigurationManager.ConnectionStrings[\"MSSQL\"].ToString();\n DataSet ds = new DataSet();\n try\n {\n dbManager.Open();\n dbManager.CreateParameters(9);\n dbManager.AddParameters(0, \"@AccessRightId\", AccessRightId, ParameterDirection.Input);\n dbManager.AddParameters(1, \"@RoleId\", RoleId, ParameterDirection.Input);\n dbManager.AddParameters(2, \"@ModuleId\", ModuleId, ParameterDirection.Input);\n dbManager.AddParameters(3, \"@CanAdd\", CanAdd, ParameterDirection.Input);\n dbManager.AddParameters(4, \"@CanEdit\", CanEdit, ParameterDirection.Input);\n dbManager.AddParameters(5, \"@CanDelete\", CanDelete, ParameterDirection.Input);\n dbManager.AddParameters(6, \"@CreatedDatetime\", CreatedDatetime, ParameterDirection.Input);\n dbManager.AddParameters(7, \"@LastAccessDatetime\", LastAccessDatetime, ParameterDirection.Input);\n dbManager.AddParameters(8, \"@Deleted\", Deleted, ParameterDirection.Input);\n ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, \"AccessRight_Search\");\n return ds;\n }\n catch (Exception ex)\n {\n }\n finally\n {\n dbManager.Dispose();\n }\n return ds;\n }\n ALTER PROCEDURE [dbo].[AccessRight_Search]\n @AccessRightId int=null,\n @RoleId int=null,\n @ModuleId int=null,\n @CanAdd char(1)=null,\n @CanEdit char(1)=null,\n @CanDelete char(1)=null,\n @CreatedDatetime datetime=null,\n @LastAccessDatetime datetime=null,\n @Deleted char(1)=null\nAS\nDECLARE @QueryString nvarchar(4000)\nDECLARE @HasWhere bit\nSET @HasWhere=0\n\nSET @QueryString = 'SELECT a.AccessRightId, a.RoleId,a.ModuleId, a.CanAdd, a.CanEdit, a.CanDelete, a.CreatedDatetime, a.LastAccessDatetime, a.Deleted, b.RoleName, c.ModuleName FROM AccessRight a, Role b, Module c WHERE a.RoleId = b.RoleId AND a.ModuleId = c.ModuleId'\n\nSET @HasWhere=1;\n\nIF(@AccessRightId IS NOT NULL)\n BEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.AccessRightId = @DummyAccessRightId';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.AccessRightId = @DummyAccessRightId';\n END\n\nIF(@RoleId IS NOT NULL)\n BEGIN\n IF(@HasWhere=0)\n BEGIN \n SET @QueryString = @QueryString + ' WHERE a.RoleId = @DummyRoleId';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.RoleId = @DummyRoleId';\n END\n\nIF(@ModuleId IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN \n SET @QueryString = @QueryString + ' WHERE a.ModuleId = @DummyModuleId';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.ModuleId = @DummyModuleId';\nEND\n\nIF(@CanAdd IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN \n SET @QueryString = @QueryString + ' WHERE a.CanAdd = @DummyCanAdd';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.CanAdd = @DummyCanAdd';\nEND\n\nIF(@CanEdit IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.CanEdit = @DummyCanEdit';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.CanEdit = @DummyCanEdit';\nEND\n\nIF(@CanDelete IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.CanDelete = @DummyCanDelete';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.CanDelete = @DummyCanDelete';\nEND\n\nIF(@CreatedDatetime IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.CreatedDatetime = @DummyCreatedDatetime';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.CreatedDatetime = @DummyCreatedDatetime';\nEND\n\nIF(@LastAccessDatetime IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.LastAccessDatetime = @DummyLastAccessDatetime';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.LastAccessDatetime = @DummyLastAccessDatetime';\nEND\n\nIF(@Deleted IS NOT NULL)\nBEGIN\n IF(@HasWhere=0) \n BEGIN\n SET @QueryString = @QueryString + ' WHERE a.Deleted = @DummyDeleted';\n SET @HasWhere=1;\n END\n ELSE SET @QueryString = @QueryString + ' AND a.Deleted = @DummyDeleted';\nEND\n\nPRINT @QueryString\n\nEXECUTE SP_EXECUTESQL @QueryString\n ,N'@DummyAccessRightId int, @DummyRoleId int, @DummyModuleId int, @DummyCanAdd char(1), @DummyCanEdit char(1), @DummyCanDelete char(1), @DummyCreatedDatetime datetime, @DummyLastAccessDatetime datetime, @DummyDeleted char(1)'\n ,@DummyAccessRightId=@AccessRightId\n ,@DummyRoleId=@RoleId\n ,@DummyModuleId=@ModuleId\n ,@DummyCanAdd=@CanAdd\n ,@DummyCanEdit=@CanEdit\n ,@DummyCanDelete=@CanDelete\n ,@DummyCreatedDatetime=@CreatedDatetime\n ,@DummyLastAccessDatetime=@LastAccessDatetime\n ,@DummyDeleted=@Deleted;\n @AccessRightId int=null,\n@RoleId int=null,\n@ModuleId int=null,\n@CanAdd char(1)=null,\n@CanEdit char(1)=null,\n@CanDelete char(1)=null,\n@CreatedDatetime datetime=null,\n@LastAccessDatetime datetime=null,\n@Deleted char(1)=null\n"
},
{
"answer_id": 6605436,
"author": "Xcalibur",
"author_id": 317739,
"author_profile": "https://Stackoverflow.com/users/317739",
"pm_score": 5,
"selected": false,
"text": "CREATE PROCEDURE GetEmployeeDetails\n @DateOfBirth DATETIME = NULL,\n @Surname VARCHAR(20),\n @GenderCode INT = NULL,\nAS\n public static SqlParameter AddParameter<T>(this SqlParameterCollection parameters, string parameterName, T value) where T : class\n{\n return value == null ? parameters.AddWithValue(parameterName, DBNull.Value) : parameters.AddWithValue(parameterName, value);\n}\n"
},
{
"answer_id": 7243702,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 4,
"selected": false,
"text": "cmd.Parameters.AddWithValue(\"@Status\", 0);\n cmd.Parameters.Add(new SqlParameter(\"@Status\", 0));\n"
},
{
"answer_id": 10770555,
"author": "Haitian Programmer",
"author_id": 1419594,
"author_profile": "https://Stackoverflow.com/users/1419594",
"pm_score": 0,
"selected": false,
"text": "create procedure up_select_employe_by_ID \n (@ID int) \nas\n select * \n from employe_t \n where employeID = @ID\n cmd.parameter.add(\"@ID\", sqltype,size).value = @ID\n cmd.parameter.add(\"@employeID\", sqltype,size).value = @employeid \n"
},
{
"answer_id": 13612631,
"author": "rafoo",
"author_id": 1244297,
"author_profile": "https://Stackoverflow.com/users/1244297",
"pm_score": 3,
"selected": false,
"text": "DBNULL.Value null null"
},
{
"answer_id": 63834663,
"author": "San",
"author_id": 6824772,
"author_profile": "https://Stackoverflow.com/users/6824772",
"pm_score": 2,
"selected": false,
"text": "sp.Value = Template ?? (object)DBNull.Value;\n"
},
{
"answer_id": 68177555,
"author": "Tarec",
"author_id": 1284902,
"author_profile": "https://Stackoverflow.com/users/1284902",
"pm_score": 2,
"selected": false,
"text": "@someTextParameter NVARCHAR(100) NULL\n NULL @someTextParameter NVARCHAR(100) = NULL\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
368,651 | <p>Using the standard win32 api, what's the best way to detect more than one user is logged on? I have an upgrade to our software product that can't be run when more than one user is logged in. (I know this is something to be avoided because of its annoyance factor, but the product is very complicated. You'll have to trust me when I say there really is no other solution.) Thanks.</p>
| [
{
"answer_id": 368937,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 2,
"selected": false,
"text": "unit main;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\nconst\n WTS_CURRENT_SERVER_HANDLE = 0;\n\ntype\n PTOKEN_USER = ^TOKEN_USER;\n _TOKEN_USER = record\n User: TSidAndAttributes;\n end;\n TOKEN_USER = _TOKEN_USER;\n\n USHORT = word;\n\n _LSA_UNICODE_STRING = record\n Length: USHORT;\n MaximumLength: USHORT;\n Buffer: LPWSTR;\n end;\n LSA_UNICODE_STRING = _LSA_UNICODE_STRING;\n\n PLuid = ^LUID;\n _LUID = record\n LowPart: DWORD;\n HighPart: LongInt;\n end;\n LUID = _LUID;\n\n _SECURITY_LOGON_TYPE = (\n seltFiller0, seltFiller1,\n Interactive,\n Network,\n Batch,\n Service,\n Proxy,\n Unlock,\n NetworkCleartext,\n NewCredentials,\n RemoteInteractive,\n CachedInteractive,\n CachedRemoteInteractive);\n SECURITY_LOGON_TYPE = _SECURITY_LOGON_TYPE;\n\n PSECURITY_LOGON_SESSION_DATA = ^SECURITY_LOGON_SESSION_DATA;\n _SECURITY_LOGON_SESSION_DATA = record\n Size: ULONG;\n LogonId: LUID;\n UserName: LSA_UNICODE_STRING;\n LogonDomain: LSA_UNICODE_STRING;\n AuthenticationPackage: LSA_UNICODE_STRING;\n LogonType: SECURITY_LOGON_TYPE;\n Session: ULONG;\n Sid: PSID;\n LogonTime: LARGE_INTEGER;\n LogonServer: LSA_UNICODE_STRING;\n DnsDomainName: LSA_UNICODE_STRING;\n Upn: LSA_UNICODE_STRING;\n end;\n SECURITY_LOGON_SESSION_DATA = _SECURITY_LOGON_SESSION_DATA;\n\n _WTS_INFO_CLASS = (\n WTSInitialProgram,\n WTSApplicationName,\n WTSWorkingDirectory,\n WTSOEMId,\n WTSSessionId,\n WTSUserName,\n WTSWinStationName,\n WTSDomainName,\n WTSConnectState,\n WTSClientBuildNumber,\n WTSClientName,\n WTSClientDirectory,\n WTSClientProductId,\n WTSClientHardwareId,\n WTSClientAddress,\n WTSClientDisplay,\n WTSClientProtocolType);\n WTS_INFO_CLASS = _WTS_INFO_CLASS;\n\n _WTS_CONNECTSTATE_CLASS = (\n WTSActive, // User logged on to WinStation\n WTSConnected, // WinStation connected to client\n WTSConnectQuery, // In the process of connecting to client\n WTSShadow, // Shadowing another WinStation\n WTSDisconnected, // WinStation logged on without client\n WTSIdle, // Waiting for client to connect\n WTSListen, // WinStation is listening for connection\n WTSReset, // WinStation is being reset\n WTSDown, // WinStation is down due to error\n WTSInit); // WinStation in initialization\n WTS_CONNECTSTATE_CLASS = _WTS_CONNECTSTATE_CLASS;\n\n function LsaFreeReturnBuffer(Buffer: pointer): Integer; stdcall;\n\n function WTSGetActiveConsoleSessionId: DWORD; external 'Kernel32.dll';\n\n function LsaGetLogonSessionData(LogonId: PLUID;\n var ppLogonSessionData: PSECURITY_LOGON_SESSION_DATA): LongInt; stdcall;\n external 'Secur32.dll';\n\n function LsaNtStatusToWinError(Status: cardinal): ULONG; stdcall;\n external 'Advapi32.dll';\n\n function LsaEnumerateLogonSessions(Count: PULONG; List: PLUID): LongInt;\n stdcall; external 'Secur32.dll';\n\n function WTSQuerySessionInformationA(hServer: THandle; SessionId: DWORD;\n WTSInfoClass: WTS_INFO_CLASS; var pBuffer: Pointer;\n var pBytesReturned: DWORD): BOOL; stdcall; external 'Wtsapi32.dll';\n\ntype\n TForm1 = class(TForm)\n Button1: TButton;\n Memo1: TMemo;\n procedure Button1Click(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nfunction LsaFreeReturnBuffer; external 'secur32.dll' name 'LsaFreeReturnBuffer';\n\nprocedure GetActiveUserNames(var slUserList : TStringList);\nvar\n Count: cardinal;\n List: PLUID;\n sessionData: PSECURITY_LOGON_SESSION_DATA;\n i1: integer;\n SizeNeeded, SizeNeeded2: DWORD;\n OwnerName, DomainName: PChar;\n OwnerType: SID_NAME_USE;\n pBuffer: Pointer;\n pBytesreturned: DWord;\n sUser : string;\nbegin\n //result:= '';\n //Listing LogOnSessions\n i1:= lsaNtStatusToWinError(LsaEnumerateLogonSessions(@Count, @List));\n try\n if i1 = 0 then\n begin\n i1:= -1;\n if Count > 0 then\n begin\n repeat\n inc(i1);\n LsaGetLogonSessionData(List, sessionData);\n //Checks if it is an interactive session\n sUser := sessionData.UserName.Buffer;\n if (sessionData.LogonType = Interactive)\n or (sessionData.LogonType = RemoteInteractive)\n or (sessionData.LogonType = CachedInteractive)\n or (sessionData.LogonType = CachedRemoteInteractive) then\n begin\n //\n SizeNeeded := MAX_PATH;\n SizeNeeded2:= MAX_PATH;\n GetMem(OwnerName, MAX_PATH);\n GetMem(DomainName, MAX_PATH);\n try\n if LookupAccountSID(nil, sessionData.SID, OwnerName,\n SizeNeeded, DomainName,SizeNeeded2,\n OwnerType) then\n begin\n if OwnerType = 1 then //This is a USER account SID (SidTypeUser=1)\n begin\n sUser := AnsiUpperCase(sessionData.LogonDomain.Buffer);\n sUser := sUser + '\\';\n sUser := sUser + AnsiUpperCase(sessionData.UserName.Buffer);\n slUserList.Add(sUser);\n// if sessionData.Session = WTSGetActiveConsoleSessionId then\n// begin\n// //Wenn Benutzer aktiv\n// try\n// if WTSQuerySessionInformationA\n// (WTS_CURRENT_SERVER_HANDLE,\n// sessionData.Session, WTSConnectState,\n// pBuffer,\n// pBytesreturned) then\n// begin\n// if WTS_CONNECTSTATE_CLASS(pBuffer^) = WTSActive then\n// begin\n// //result:= sessionData.UserName.Buffer;\n// slUserList.Add(sessionData.UserName.Buffer);\n// end;\n// end;\n// finally\n// LSAFreeReturnBuffer(pBuffer);\n// end;\n //end;\n end;\n end;\n finally\n FreeMem(OwnerName);\n FreeMem(DomainName);\n end;\n end;\n inc(List);\n try\n LSAFreeReturnBuffer(sessionData);\n except\n end;\n until (i1 = Count-1);// or (result <> '');\n end;\n end;\n finally\n LSAFreeReturnBuffer(List);\n end;\nend;\n\nprocedure TForm1.Button1Click(Sender: TObject);\nvar\n slUsers : TStringList;\nbegin\n slUsers := TStringList.Create;\n slUsers.Duplicates := dupIgnore;\n slUsers.Sorted := True;\n\n try\n GetActiveUserNames(slUsers);\n Memo1.Lines.AddStrings(slUsers);\n finally\n FreeAndNil(slUsers)\n end;\nend;\n\nend.\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24898/"
] |
368,653 | <p>In a web-application implemented in java using JSP and Servlets; if I store information in the user session, this information is shared from all the tabs from the same browser. How to differ sessions in the browser-tabs?
In this example: </p>
<pre><code><%@page language="java"%>
<%
String user = request.getParameter("user");
user = (user == null ? (String)session.getAttribute("SESSIONS_USER") : user);
session.setAttribute("SESSIONS_USER",user);
%>
<html><head></head><body>
<%=user %>
<form method="post">
User:<input name="user" value="">
<input type="submit" value="send">
</form>
</body></html>
</code></pre>
<p>Copy this code in a jsp page (<code>testpage.jsp</code>), deploy this file in an existing context of a web application on the server (I use Apache Tomcat), then open a browser (FF, IE7 or Opera) using the correct URL (<code>localhost/context1/testpage.jsp</code>), type your name in the input and submit the form. Then open a new tab in the same browser, and then you can see your name (get from the session) on the new tab. Be careful with the browser-cache, sometimes seems that it doesn't happen, but it's in the cache, refresh the second tab.</p>
<p>Thanks.</p>
| [
{
"answer_id": 19384101,
"author": "Mike A.",
"author_id": 782695,
"author_profile": "https://Stackoverflow.com/users/782695",
"pm_score": 3,
"selected": false,
"text": "//Events \n$(window).ready(function() {generateWindowID()});\n$(window).focus(function() {setAppId()});\n$(window).mouseover(function() {setAppId()});\n\n\nfunction generateWindowID()\n{\n //first see if the name is already set, if not, set it.\n if (se_appframe().name.indexOf(\"SEAppId\") == -1){\n \"window.name = 'SEAppId' + (new Date()).getTime()\n }\n setAppId()\n}\n\nfunction setAppId()\n{\n //generate the cookie\n strCookie = 'seAppId=' + se_appframe().name + ';';\n strCookie += ' path=/';\n\n if (window.location.protocol.toLowerCase() == 'https:'){\n strCookie += ' secure;';\n }\n\n document.cookie = strCookie;\n}\n //variable name \nstring varname = \"\";\nHttpCookie aCookie = Request.Cookies[\"seAppId\"];\nif(aCookie != null) {\n varname = Request.Cookies[\"seAppId\"].Value + \"_\";\n}\nvarname += \"_mySessionVariable\";\n\n//write session data \nSession[varname] = \"ABC123\";\n\n//readsession data \nString myVariable = Session[varname];\n"
},
{
"answer_id": 20140533,
"author": "Kingz",
"author_id": 1642266,
"author_profile": "https://Stackoverflow.com/users/1642266",
"pm_score": 0,
"selected": false,
"text": "How to differ sessions in browser-tabs?\n"
},
{
"answer_id": 23075956,
"author": "user3534653",
"author_id": 3534653,
"author_profile": "https://Stackoverflow.com/users/3534653",
"pm_score": 3,
"selected": false,
"text": "23423.abc.com\n242234.abc.com\n235643.abc.com\n"
},
{
"answer_id": 30711951,
"author": "SilverlightFox",
"author_id": 413180,
"author_profile": "https://Stackoverflow.com/users/413180",
"pm_score": 2,
"selected": false,
"text": "<form method=\"post\" action=\"/handler\">\n\n <input type=\"hidden\" name=\"sessionId\" value=\"123456890123456890ABCDEF01\" />\n <input type=\"hidden\" name=\"action\" value=\"\" />\n\n</form>\n action <input type=\"hidden\" name=\"action\" value=\"completeCheckout\" />\n<input type=\"hidden\" name=\"data\" value='{ \"cardNumber\" : \"4111111111111111\", ... ' />\n"
},
{
"answer_id": 34164406,
"author": "German Sanchez",
"author_id": 1835975,
"author_profile": "https://Stackoverflow.com/users/1835975",
"pm_score": 1,
"selected": false,
"text": "var deferred = $q.defer(),\n self = this,\n onConnect = function(status){\n if (status === Strophe.Status.CONNECTING) {\n deferred.notify({status: 'connecting'});\n } else if (status === Strophe.Status.CONNFAIL) {\n self.connected = false;\n deferred.notify({status: 'fail'});\n } else if (status === Strophe.Status.DISCONNECTING) {\n deferred.notify({status: 'disconnecting'});\n } else if (status === Strophe.Status.DISCONNECTED) {\n self.connected = false;\n deferred.notify({status: 'disconnected'});\n } else if (status === Strophe.Status.CONNECTED) {\n self.connection.send($pres().tree());\n self.connected = true;\n deferred.resolve({status: 'connected'});\n } else if (status === Strophe.Status.ATTACHED) {\n deferred.resolve({status: 'attached'});\n self.connected = true;\n }\n },\n output = function(data){\n if (self.connected){\n var rid = $(data).attr('rid'),\n sid = $(data).attr('sid'),\n storage = {};\n\n if (localStorageService.cookie.get('day_bind')){\n storage = localStorageService.cookie.get('day_bind');\n }else{\n storage = {};\n }\n storage[$window.name] = sid + '-' + rid;\n localStorageService.cookie.set('day_bind', angular.toJson(storage));\n }\n };\n if ($window.name){\n var storage = localStorageService.cookie.get('day_bind'),\n value = storage[$window.name].split('-')\n sid = value[0],\n rid = value[1];\n self.connection = new Strophe.Connection(BoshService);\n self.connection.xmlOutput = output;\n self.connection.attach('bosh@' + BoshDomain + '/' + $window.name, sid, parseInt(rid, 10) + 1, onConnect);\n }else{\n $window.name = 'web_' + (new Date()).getTime();\n self.connection = new Strophe.Connection(BoshService);\n self.connection.xmlOutput = output;\n self.connection.connect('bosh@' + BoshDomain + '/' + $window.name, '123456', onConnect);\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46388/"
] |
368,668 | <p>I'm interested in assigning the tag name of the root element in an xml document to an xslt variable. For instance, if the document looked like (minus the DTD):</p>
<pre><code><foo xmlns="http://.....">
<bar>1</bar>
</foo>
</code></pre>
<p>and I wanted to assign the string 'foo' to an xslt variable. Is there a way to reference that?</p>
<p>Thanks, Matt</p>
| [
{
"answer_id": 368727,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 6,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:variable name=\"outermostElementName\" select=\"name(/*)\" />\n\n <xsl:template match=\"/\">\n <xsl:value-of select=\"$outermostElementName\"/>\n </xsl:template>\n</xsl:stylesheet>\n"
},
{
"answer_id": 369196,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 5,
"selected": false,
"text": "name() name(/*) <bar:foo/> local-name()"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26241/"
] |
368,669 | <p>We have many projects that use a common base of shared components (dlls).
Currently the development build for each project links against dlls built from the trunk of the components. (ie trunk builds use the dlls from other trunk builds)</p>
<p>When we do a release build, we have a script that goes through the project files and replaces the trunk references to specific numbered versions of the components (that are built from a tagged branch) </p>
<p>I think this weakens the testing that we do during development because the project that I am actually working on is using diferent dlls to what the release build will be using. I would like to always develop against the numbered versions of the components and only ever update them when there is a specific need.</p>
<p>However others in the team argue that unless we develop against trunk (and update to the newer versions of the components with each release) we will have the problem that (a) our products will hardly ever update to the newer version of the components then (b) when we do need to update it will be a huge task because the component source/interfaces will have changed so much.</p>
<p>What practices do you follow, and why?</p>
<p>Edit: Sorry all, I have just realised I have confused things by mentioning that there are several main products sharing components - although they share the components they don't run on the same PCs. My concern relates to the fact the because the components are likely to change with each release of a product (even though there was no specific requirement to update the component) that testing would miss some subtle change that was done in a component and not related to the specific work being done on the product. </p>
| [
{
"answer_id": 368753,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": true,
"text": "trunk tags labels branches"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590/"
] |
368,725 | <p>Given the schema</p>
<pre>
PERSON { name, spouse }
</pre>
<p>where PERSON.spouse is a foreign key to PERSON.name, NULLs will be necessary when a person is unmarried or we don't have any info.</p>
<p>Going with the argument against nulls, how do you avoid them in this case?</p>
<p>I have an alternate schema</p>
<pre>
PERSON { name }
SPOUSE { name1, name2 }
</pre>
<p>where SPOUSE.name* are FKs to PERSON. The problem I see here is that there is no way to ensure someone has only one spouse (even with all possible UNIQUE constraints, it would be possible to have two spouses).</p>
<p>What's the best way to factor out nulls in bill-of-materials style relations?</p>
| [
{
"answer_id": 368795,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "PERSON { A, B }\nPERSON { B, C }\nPERSON { C, NULL }\n PERSON { A, FEMALE, B }\nPERSON { B, MALE, NULL }\nPERSON { C, FEMALE, NULL }\n"
},
{
"answer_id": 369057,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE People\n(\n person_name VARCHAR(100),\n CONSTRAINT PK_People PRIMARY KEY (person_name)\n)\nGO\nCREATE TABLE Spouses\n(\n person_name VARCHAR(100),\n spouse_name VARCHAR(100),\n CONSTRAINT PK_Spouses PRIMARY KEY (person_name),\n CONSTRAINT FK_Spouses_People FOREIGN KEY (person_name) REFERENCES People (person_name)\n)\nGO\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21294/"
] |
368,742 | <p>Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example):</p>
<pre><code>void someMethod(SomeClass x)
{
if (x == null){
throw new ArgumentNullException("someMethod received a null argument!");
}
x.doSomething();
}
</code></pre>
<p>Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?</p>
<p>Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?</p>
| [
{
"answer_id": 368759,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": true,
"text": "ArgumentNullException NullReferenceException"
},
{
"answer_id": 368760,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 5,
"selected": false,
"text": "[Pure]\npublic static object Call([NotNull] Type declaringType, \n [NotNull] string methodName, \n [CanBeNull] object instance)\n{\n if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));\n if (methodName == null) throw new ArgumentNullException(nameof(methodName));\n nameof"
},
{
"answer_id": 368778,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 3,
"selected": false,
"text": "void someMethod(SomeClass x, SomeClass y)\n{\n Guard.NotNull(x,\"x\",\"someMethod received a null x argument!\");\n Guard.NotNull(y,\"y\",\"someMethod received a null y argument!\");\n\n\n x.doSomething();\n y.doSomething();\n}\n"
},
{
"answer_id": 368780,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 3,
"selected": false,
"text": " //\n // Summary:\n // Initializes a new instance of the System.ArgumentNullException class with\n // the name of the parameter that causes this exception.\n //\n // Parameters:\n // paramName:\n // The name of the parameter that caused the exception.\n public ArgumentNullException(string paramName);\n"
},
{
"answer_id": 369274,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 4,
"selected": false,
"text": "void someMethod(SomeClass x)\n{ \n x.Property.doSomething();\n}\n NullReferenceException x x.Property"
},
{
"answer_id": 45196191,
"author": "DiskJunky",
"author_id": 1838819,
"author_profile": "https://Stackoverflow.com/users/1838819",
"pm_score": 1,
"selected": false,
"text": "ArgumentNullException void SomeMethod(SomeObject someObject)\n{\n Throw.IfArgNull(() => someObject);\n //... do more stuff\n}\n public static class Throw\n{\n public static void IfArgNull<T>(Expression<Func<T>> arg)\n {\n if (arg == null)\n {\n throw new ArgumentNullException(nameof(arg), \"There is no expression with which to test the object's value.\");\n }\n\n // get the variable name of the argument\n MemberExpression metaData = arg.Body as MemberExpression;\n if (metaData == null)\n {\n throw new ArgumentException(\"Unable to retrieve the name of the object being tested.\", nameof(arg));\n }\n\n // can the data type be null at all\n string argName = metaData.Member.Name;\n Type type = typeof(T);\n if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)\n {\n throw new ArgumentException(\"The expression does not specify a nullible type.\", argName);\n }\n\n // get the value and check for null\n if (arg.Compile()() == null)\n {\n throw new ArgumentNullException(argName);\n }\n }\n}\n"
},
{
"answer_id": 60634447,
"author": "AndyWarby",
"author_id": 3893130,
"author_profile": "https://Stackoverflow.com/users/3893130",
"pm_score": 4,
"selected": false,
"text": "_ = declaringType ?? throw new ArgumentNullException(nameof(declaringType));\n_ = methodname ?? throw new ArgumentNullException(nameof(methodName));\n"
},
{
"answer_id": 68741398,
"author": "Pekka Ylönen",
"author_id": 16391556,
"author_profile": "https://Stackoverflow.com/users/16391556",
"pm_score": 1,
"selected": false,
"text": "== == if (something is null) \n{\n throw new ArgumentNullException(nameof(something), \"Can't be null.\");\n}\n"
},
{
"answer_id": 69596303,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 3,
"selected": false,
"text": "ArgumentNullException ArgumentNullException.ThrowIfNull(object);\n"
},
{
"answer_id": 72458872,
"author": "Tasty213",
"author_id": 10436605,
"author_profile": "https://Stackoverflow.com/users/10436605",
"pm_score": 1,
"selected": false,
"text": "int? foo = null;\nArgumentNullException.ThrowIfNull(foo);\n foo"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
368,744 | <p>Suppose a shell script (/bin/sh or /bin/bash) contained several commands. How can I cleanly make the script terminate if any of the commands has a failing exit status? Obviously, one can use if blocks and/or callbacks, but is there a cleaner, more concise way? Using && is not really an option either, because the commands can be long, or the script could have non-trivial things like loops and conditionals.</p>
| [
{
"answer_id": 368754,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 7,
"selected": true,
"text": "sh bash set -e\n $ help set\n...\n -e Exit immediately if a command exits with a non-zero status.\n zsh csh tcsh #!/bin/csh -e"
},
{
"answer_id": 1222559,
"author": "Barun",
"author_id": 147021,
"author_profile": "https://Stackoverflow.com/users/147021",
"pm_score": 5,
"selected": false,
"text": "$ <any_command> || exit 1\n"
},
{
"answer_id": 9184722,
"author": "f0ster",
"author_id": 157460,
"author_profile": "https://Stackoverflow.com/users/157460",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n# A Tidier approach\n\ncheck_errs()\n{\n # Function. Parameter 1 is the return code\n # Para. 2 is text to display on failure.\n if [ \"${1}\" -ne \"0\" ]; then\n echo \"ERROR # ${1} : ${2}\"\n # as a bonus, make our script exit with the right error code.\n exit ${1}\n fi\n}\n\n### main script starts here ###\n\ngrep \"^${1}:\" /etc/passwd > /dev/null 2>&1\ncheck_errs $? \"User ${1} not found in /etc/passwd\"\nUSERNAME=`grep \"^${1}:\" /etc/passwd|cut -d\":\" -f1`\ncheck_errs $? \"Cut returned an error\"\necho \"USERNAME: $USERNAME\"\ncheck_errs $? \"echo returned an error - very strange!\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28558/"
] |
368,750 | <p>Finally, I have a question to ask on Stack Overflow! :-)</p>
<p>The main target is for Java but I believe it is mostly language agnostic: if you don't have native assert, you can always simulate it.</p>
<p>I work for a company selling a suite of softwares written in Java. The code is old, dating back to Java 1.3 at least, and at some places, it shows... That's a large code base, some 2 millions of lines, so we can't refactor it all at once.<br>
Recently, we switched the latest versions from Java 1.4 syntax and JVM to Java 1.6, making conservative use of some new features like <code>assert</code> (we used to use a DEBUG.ASSERT macro -- I know <code>assert</code> has been introduced in 1.4 but we didn't used it before), generics (only typed collections), foreach loop, enums, etc.</p>
<p>I am still a bit green about the use of assert, although I have read a couple of articles on the topic. Yet, some usages I see leave me perplex, hurting my common sense... ^_^ So I thought I should ask some questions, to see if I am right to want to correct stuff, or if it goes against common practices. I am wordy, so I <strong>bolded</strong> the questions, for those liking to skim stuff.</p>
<p>For reference, I have searched <em>assert java</em> in SO and found some interesting threads, but apparently no exact duplicate.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java" title=" How to avoid “!= null” statements in java? "> How to avoid “!= null” statements in java? </a> and <a href="https://stackoverflow.com/questions/302736/how-much-null-checking-is-enough" title="How much null checking is enough?">How much null checking is enough?</a> are quite relevant, because lot of asserts we have just check if variable is null. At some places in our code, there are usages of the null object (eg. returning <code>new String[0]</code>) but not always. We have to live with that, at least for maintenance of legacy code.</li>
<li>Some good answers also in <a href="https://stackoverflow.com/questions/298909/java-assertions-underused" title="Java assertions underused">Java assertions underused</a>.</li>
<li>Oh, and SO indicates with reason that <a href="https://stackoverflow.com/questions/129120/when-should-i-use-debugassert" title="When should I use Debug.Assert()?">When should I use Debug.Assert()?</a> question is related too (nice feature to reduce duplicates!).</li>
</ul>
<p>First, main issue, which triggered my question today:</p>
<pre><code>SubDocument aSubDoc = documents.GetAt( i );
assert( aSubDoc != null );
if ( aSubDoc.GetType() == GIS_DOC )
{
continue;
}
assert( aSubDoc.GetDoc() != null );
ContentsInfo ci = (ContentsInfo) aSubDoc.GetDoc();
</code></pre>
<p>(<em>Yes, we use MS' C/C++ style/code conventions. And I even like it (coming from same background)! So sue us.</em>)<br>
First, the <code>assert()</code> form comes from conversion of <code>DEBUG.ASSERT()</code> calls. I dislike the extra parentheses, since assert is a language construct, not (no longer, here) a function call. I dislike also <code>return (foo);</code> :-)<br>
Next, the asserts don't test here for invariants, they are rather used as guards against bad values. But as I understand it, they are useless here: the assert will throw an exception, not even documented with a companion string, and only if assertions are enabled. So if we have <code>-ea</code> option, we just have an assertion thrown instead of the regular NullPointerException one. That doesn't look like a paramount advantage, since we catch unchecked exceptions at highest level anyway.<br>
<strong>Am I right supposing we can get rid of them and live with that (ie. let Java raise such unckecked exception)?</strong> (or, of course, test against null value if likely, which is done in other places).</p>
<p>Side note: should I have to assert in the above snippet, I would do that against ci value, not against the getter: even if most getters are optimized/inlined, we cannot be sure, so we should avoid calling it twice.</p>
<p>Somebody told, in the last referenced thread, that public methods should use tests against values of parameters (usage of the public API) and private methods should rely on asserts instead. Good advice.<br>
Now, both kinds of methods must check another source of data: external input. Ie. data coming from user, from a database, from some file or from the network, for example.<br>
In our code, I see asserts against these values. I always change these to real test, so they act even with assertions disabled: these are not invariants and must be properly handled.<br>
I see only one possible exception, where input is supposed constant, for example a database table filled with constants used in relations: program would break if this table is changed but corresponding code wasn't updated.<br>
<strong>Do you see other exceptions?</strong></p>
<p>Another relatively frequent use I see, which seems OK: in the default of a switch, or at the end of a series of <code>else if</code> testing all possible values (these cases date back before our use of enums!), there is often an <code>assert false : "Unexpected value for stuff: " + stuff;</code><br>
<strong>Looks legitimate for me (these cases shouldn't happen in production), what do you think?</strong> (beyond the "no switch, use OO" advices which are irrelevant here).</p>
<p>And finally, <strong>are there any other useful use cases or annoying gotchas</strong> I missed here? (probably!)</p>
| [
{
"answer_id": 368811,
"author": "Stefan Teitge",
"author_id": 12463,
"author_profile": "https://Stackoverflow.com/users/12463",
"pm_score": 2,
"selected": false,
"text": "List returnListOfSize(int size) {\n // complex list creation\n assert list.size == size;\n}\n"
},
{
"answer_id": 368877,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 2,
"selected": false,
"text": "assert throw new AssertionError(\"You dead\");\n assert false:\"I am lucky\";\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15459/"
] |
368,761 | <p>I need to start and stop SQL Server from the command line. I am willing to write a small C# program if necessary, but I suspect that there's something (PowerShell, maybe?) that currently exists that does this gracefully.</p>
<p>Thank you.</p>
| [
{
"answer_id": 368772,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 5,
"selected": true,
"text": "net {start|stop} mssqlserver"
},
{
"answer_id": 73737652,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "net start \"SQL Server (SQLEXPRESS)\"\n net stop \"SQL Server (SQLEXPRESS)\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] |
368,762 | <p>So What I'm essentially trying to do is have something happen 70% of the time, another few things happen 10% of the time each if that makes sense but my app doesn't seem to do any of the actions I'm guessing I'm misunderstanding the loop syntax or something, anyway if anyone could take a look and maybe give me some advice</p>
<pre><code>per1 := 70;
per2 := 77;
per3 := 84;
per4 := 91;
per5 := 100;
per6 := Random(2) + 1;
randomize;
RandPer:= Random(100);
randomize;
RandPer2 := Random(100);
if RandPer2 <= 70 then begin
If RandPer <= per1 then begin
Functiontest(1);
end Else If RandPer <= per2 then begin
Functiontest(3);
end Else begin If RandPer <= per3 then begin
Functiontest(5);
end Else begin If RandPer <= per4 then begin
Functiontest(6);
end Else begin If RandPer <= per5 then begin
Functiontest(9);
end;
end;
end;
end;
</code></pre>
| [
{
"answer_id": 368772,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 5,
"selected": true,
"text": "net {start|stop} mssqlserver"
},
{
"answer_id": 73737652,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "net start \"SQL Server (SQLEXPRESS)\"\n net stop \"SQL Server (SQLEXPRESS)\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,766 | <p>I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.</p>
<p>Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?</p>
<p>Thanks.</p>
| [
{
"answer_id": 368851,
"author": "Abram Simon",
"author_id": 46204,
"author_profile": "https://Stackoverflow.com/users/46204",
"pm_score": 5,
"selected": true,
"text": "LocalReport myReport = new LocalReport();\nmyReport.ReportPath = Server.MapPath(\"~/Path/To/Report.rdlc\");\n\nReportParameter myParam = new ReportParameter(\"ParamName\", \"ParamValue\");\nmyReport.SetParameters(new ReportParameter[] { myParam });\n\n// more code here to render report\n"
},
{
"answer_id": 945717,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Dim MyRS As New ReportingService\n MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3) MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)\n\nDim ReportByteArray As Byte() = Nothing\nDim ReportPath As String = \"/SRSSiteSubFolder/ReportNameWithoutRDLExtension\"\nDim ReportFormat As String = \"PDF\"\nDim HistoryID As String = Nothing\nDim DevInfo As String = \"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>\"\n'Dim x As ReportParameter - not necessary\nDim ReportParams(0) As ParameterValue\nReportParams(0) = New ParameterValue()\nReportParams(0).Name = \"TheParamName\"\nReportParams(0).Value = WhateverValue\n\nDim Credentials As DataSourceCredentials() = Nothing\nDim ShowHideToggle As String = Nothing\nDim Encoding As String\nDim MimeType As String\nDim ReportHistoryParameters As ParameterValue() = Nothing\nDim Warnings As Warning() = Nothing\nDim StreamIDs As String() = Nothing\n'Dim sh As New SessionHeader() - not necessary\n''MyRS.SessionHeaderValue = sh - not necessary\n\nReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _\n ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)\n'(Yay! That line was giving \"HTTP error 401 - Unauthorized\", until I set the credentials\n' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)\n\n'Write the contents of the report to a PDF file:\nDim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)\nfs.Write(ReportByteArray, 0, ReportByteArray.Length)\nfs.Close()\n\nCall EmailTheReport(FullReportPath)\n\nIf IO.File.Exists(FullReportPath) Then\n IO.File.Delete(FullReportPath)\nEnd If\n"
},
{
"answer_id": 6521355,
"author": "girish.M",
"author_id": 821172,
"author_profile": "https://Stackoverflow.com/users/821172",
"pm_score": 1,
"selected": false,
"text": "ReportViewer1.LocalReport.DataSources.Clear();\nReportViewer1.Reset();\nLabel1.Visible = false;\nReportViewer1.Visible = true;\nDataSet dataSet = new DataSet();\ndataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text, \nddlType.SelectedValue, levelcode, fields);\nReportDataSource datasource = new ReportDataSource(\"DataSet_StoreprocedureName\",\ndataSet.Tables[0]);\n\nif (dataSet.Tables[0].Rows.Count == 0)\n{\n ReportViewer1.Visible = false;\n}\n\nReportViewer1.LocalReport.ReportPath = Server.MapPath(\"\") + @\"\\Report.rdlc\";\nReportViewer1.LocalReport.DataSources.Clear();\nReportViewer1.LocalReport.DataSources.Add(datasource);\nstring fields=\"name,girish,Z0117\";\nstring[] filedName = fields.Split(',');\nReportParameter[] param = new ReportParameter[2];\n\n//for (int i = 0; i < filedName.Length; i++)\n//{\n\nparam[0] = new ReportParameter(filedName[0], filedName[0], true);\nparam[1] = new ReportParameter(filedName[3], filedName[3], true);\n\n// }\n\n\nReportViewer1.LocalReport.SetParameters(param);\n\nReportViewer1.ServerReport.Refresh();\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6602/"
] |
368,771 | <p>How do I post a form to an external site using an ASP.NET MVC controller?</p>
<p><strong>EDIT:</strong> Ok... I have a view with some data on it. After the user completes the form I need to do a postback with a specified form format to an external site (like for paypal). After I posted the constructed form I need to redirect the action to a new view</p>
| [
{
"answer_id": 368785,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 0,
"selected": false,
"text": "<% using (Html.Form<Controller>(\"Action\", c => c.Method())) { %>\n <form action=\"http://www.someotherwebsite.com/action\">\n"
},
{
"answer_id": 369050,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": ""
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,786 | <p>Here's an interesting question. I have a system that attempts to run some initialization code. If it fails, we call the deinitializer to clean everything up.</p>
<p>Because we call the deinitializer in exception handling, we run the risk that both initialize and deinitialize will fail, and hypothetically, it now seems that we have to throw <strong>two</strong> exceptions.</p>
<p>It seems pretty unlikely that we will, though. So what happens and what should the code do here?</p>
<pre><code> try { /* init code here */ }
catch (Exception ex)
{
try
{
_DeinitializeEngine();
}
catch (Exception ex2)
{
throw new OCRException("Engine failed to initialize; ALSO failed to deinitialize engine!", ex2);
}
finally
{
throw new OCRException("Engine failed to initialize; failed to initialize license!", ex);
}
}
</code></pre>
| [
{
"answer_id": 368796,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": " static void Main(string[] args)\n {\n try\n {\n principalMethod();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Test : \" + e.Message);\n }\n Console.Read();\n }\n\n public static void principalMethod()\n {\n try\n {\n throw new Exception(\"Primary\");\n }\n catch (Exception ex1)\n {\n try\n {\n methodThatCanCrash();\n }\n catch\n {\n throw new Exception(\"Cannot deinitialize\", ex1);\n }\n }\n }\n\n private static void methodThatCanCrash()\n {\n throw new NotImplementedException();\n }\n"
},
{
"answer_id": 368914,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 1,
"selected": false,
"text": "try { /* init code here */ } \ncatch (Exception ex)\n{\n // Passing original exception as inner exception\n Exception ocrex = new OCRException(\"Engine failed to initialize\", ex);\n\n try\n {\n _DeinitializeEngine();\n }\n catch (Exception ex2)\n {\n // Passing initialization failure as inner exception\n ocrex = new OCRException(\"Failed to deinitialize engine!\", ocrex); \n }\n throw ocrex;\n}\n"
},
{
"answer_id": 369293,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "RelatedException PriorException"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40352/"
] |
368,802 | <p>I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.</p>
<p>I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine <strong>Update: the caller I have in mind is not another JVM; thanks @Dave Ray</strong></p>
<p>My implementation considerations are typical </p>
<ul>
<li>performance</li>
<li>ease of implementation and maintenance (simplicity?)</li>
<li>reliability</li>
<li>flexibility (i.e. can I call from a remote machine, etc.)</li>
</ul>
<p>Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?</p>
<p>(Stuff people have actually done and can provide real-life feedback on would be great!)</p>
| [
{
"answer_id": 1540974,
"author": "Travis Wilson",
"author_id": 8735,
"author_profile": "https://Stackoverflow.com/users/8735",
"pm_score": 1,
"selected": false,
"text": "i = new bsh.Interpreter();\ni.set( \"myapp\", this ); // Provide a reference to your app\ni.eval(\"server(7000)\");\n telnet localhost 7001\nmyapp.someMethod();\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2362/"
] |
368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
| [
{
"answer_id": 368828,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 2,
"selected": false,
"text": ">>> u'add \\x93Monitoring\\x93 to list '.encode('latin-1','ignore')\n'add \\x93Monitoring\\x93 to list '\n"
},
{
"answer_id": 368859,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": -1,
"selected": false,
"text": "'add \\x93Monitoring\\x93 to list '.decode('latin-1').encode('latin-1')\n"
},
{
"answer_id": 370199,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 9,
"selected": true,
"text": "\"add \\x93Monitoring\\x94 to list\".decode(\"cp1252\", \"ignore\")\n .encode"
},
{
"answer_id": 62672428,
"author": "rubmz",
"author_id": 4226806,
"author_profile": "https://Stackoverflow.com/users/4226806",
"pm_score": -1,
"selected": false,
"text": "unicodedata.normalize('NFKD', text).encode('utf-8', 'ignore')\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
368,807 | <p>The following html code works in Firefox, but for some reason fails in IE (Label2 is not shown). Is that a bug or I miss something?</p>
<p>Any help would be appreciated.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
</script>
<script>
jQuery(document).ready(function(){
function setVis(){
var val = $("#check").is(":checked");
if (val)
$("#g_1").show();
else
$("#g_1").hide();
}
setVis();
$("#check").change(setVis);
});
</script>
</head>
<body>
<span>
<input type="checkbox" id="check" />
<label>Label1</label>
</span>
<span id="g_1">
<label>Label2</label>
</span>
</body>
</html>
</code></pre>
| [
{
"answer_id": 368857,
"author": "cLFlaVA",
"author_id": 45109,
"author_profile": "https://Stackoverflow.com/users/45109",
"pm_score": 3,
"selected": false,
"text": "<sidequestion> </sidequestion> jQuery(document).ready(function(){\n $(\"#g_1\").hide();\n $(\"#check\").change(function() { $(\"#g_1\").toggle(); });\n});\n"
},
{
"answer_id": 368893,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "click change $(\"#check\").click(setVis);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42512/"
] |
368,813 | <p>According to HTML specs, the <code>select</code> tag in HTML doesn't have a <code>readonly</code> attribute, only a <code>disabled</code> attribute. So if you want to keep the user from changing the dropdown, you have to use <code>disabled</code>.</p>
<p>The only problem is that disabled HTML form inputs don't get included in the POST / GET data.</p>
<p>What's the best way to emulate the <code>readonly</code> attribute for a <code>select</code> tag, and still get the POST data?</p>
| [
{
"answer_id": 368822,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 7,
"selected": false,
"text": "$('#yourSelect').prop('disabled', true);\n $('#yourForm').on('submit', function() {\n $('#yourSelect').prop('disabled', false);\n});\n $('#yourForm').on('submit', function() {\n $('input, select').prop('disabled', false);\n});\n"
},
{
"answer_id": 368834,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 10,
"selected": true,
"text": "select disabled input $('#mainform').submit(function() {\n $('#formdata_container').show();\n $('#formdata').html($(this).serialize());\n return false;\n});\n\n$('#enableselect').click(function() {\n $('#mainform input[name=animal]')\n .attr(\"disabled\", true);\n \n $('#animal-select')\n .attr('disabled', false)\n .attr('name', 'animal');\n \n $('#enableselect').hide();\n return false;\n}); #formdata_container {\n padding: 10px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div>\n <form id=\"mainform\">\n <select id=\"animal-select\" disabled=\"true\">\n <option value=\"cat\" selected>Cat</option>\n <option value=\"dog\">Dog</option>\n <option value=\"hamster\">Hamster</option>\n </select>\n <input type=\"hidden\" name=\"animal\" value=\"cat\"/>\n <button id=\"enableselect\">Enable</button>\n \n <select name=\"color\">\n <option value=\"blue\" selected>Blue</option>\n <option value=\"green\">Green</option>\n <option value=\"red\">Red</option>\n </select>\n\n <input type=\"submit\"/>\n </form>\n</div>\n\n<div id=\"formdata_container\" style=\"display:none\">\n <div>Submitted data:</div>\n <div id=\"formdata\">\n </div>\n</div>"
},
{
"answer_id": 368842,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 5,
"selected": false,
"text": "<select id=\"countries\" onfocus=\"this.defaultIndex=this.selectedIndex;\" onchange=\"this.selectedIndex=this.defaultIndex;\">\n<option value=\"1\">Country1</option>\n<option value=\"2\">Country2</option>\n<option value=\"3\">Country3</option>\n<option value=\"4\">Country4</option>\n<option value=\"5\">Country5</option>\n<option value=\"6\">Country6</option>\n<option value=\"7\" selected=\"selected\">Country7</option>\n<option value=\"8\">Country8</option>\n<option value=\"9\">Country9</option>\n</select>\n"
},
{
"answer_id": 368847,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 1,
"selected": false,
"text": "<div> <input type=\"text\">"
},
{
"answer_id": 2097881,
"author": "thetoolman",
"author_id": 251185,
"author_profile": "https://Stackoverflow.com/users/251185",
"pm_score": 2,
"selected": false,
"text": "var readonlySelect = function(selector, makeReadonly) {\n\n $(selector).filter(\"select\").each(function(i){\n var select = $(this);\n\n //remove any existing readonly handler\n if(this.readonlyFn) select.unbind(\"change\", this.readonlyFn);\n if(this.readonlyIndex) this.readonlyIndex = null;\n\n if(makeReadonly) {\n this.readonlyIndex = this.selectedIndex;\n this.readonlyFn = function(){\n this.selectedIndex = this.readonlyIndex;\n };\n select.bind(\"change\", this.readonlyFn);\n }\n });\n\n};\n"
},
{
"answer_id": 6106258,
"author": "Craig Ambrose",
"author_id": 767171,
"author_profile": "https://Stackoverflow.com/users/767171",
"pm_score": 3,
"selected": false,
"text": "// global variable to store original event/handler for save button\nvar form_save_button_func = null;\n\n// function to get jQuery object for save button\nfunction get_form_button_by_id(button_id) {\n return jQuery(\"input[type=button]#\"+button_id);\n}\n\n// alter value of disabled element\nfunction set_disabled_elem_value(elem_id, value) {\n jQuery(\"#\"+elem_id).removeAttr(\"disabled\");\n jQuery(\"#\"+elem_id).val(value);\n jQuery(\"#\"+elem_id).attr('disabled','disabled');\n}\n\nfunction set_form_bottom_button_save_custom_code_generic(msg) {\n // save original event/handler that was either declared\n // through javascript or html onclick attribute\n // in a global variable\n form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.6\n //form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.7\n\n // unbind original event/handler (can use any of following statements below)\n get_form_button_by_value('BtnSave').unbind('click');\n get_form_button_by_value('BtnSave').removeAttr('onclick');\n\n // alternate save code which also calls original event/handler stored in global variable\n get_form_button_by_value('BtnSave').click(function(event){\n event.preventDefault();\n var confirm_result = confirm(msg);\n if (confirm_result) {\n if (jQuery(\"form.anyForm\").find('input[type=text], textarea, select').filter(\".disabled-form-elem\").length > 0) {\n jQuery(\"form.anyForm\").find('input[type=text], textarea, select').filter(\".disabled-form-elem\").removeAttr(\"disabled\");\n }\n\n // disallow further editing of fields once save operation is underway\n // by making them readonly\n // you can also disallow form editing by showing a large transparent\n // div over form such as loading animation with \"Saving\" message text\n jQuery(\"form.anyForm\").find('input[type=text], textarea, select').attr('ReadOnly','True');\n\n // now execute original event/handler\n form_save_button_func();\n }\n });\n}\n\n$(document).ready(function() {\n // if you want to define save button code in javascript then define it now\n\n // code below for record update\n set_form_bottom_button_save_custom_code_generic(\"Do you really want to update this record?\");\n // code below for new record\n //set_form_bottom_button_save_custom_code_generic(\"Do you really want to create this new record?\");\n\n // start disabling elements on form load by also adding a class to identify disabled elements\n jQuery(\"input[type=text]#phone\").addClass('disabled-form-elem').attr('disabled','disabled');\n jQuery(\"input[type=text]#fax\").addClass('disabled-form-elem').attr('disabled','disabled');\n jQuery(\"select#country\").addClass('disabled-form-elem').attr('disabled','disabled');\n jQuery(\"textarea#address\").addClass('disabled-form-elem').attr('disabled','disabled');\n\n set_disabled_elem_value('phone', '123121231');\n set_disabled_elem_value('fax', '123123123');\n set_disabled_elem_value('country', 'Pakistan');\n set_disabled_elem_value('address', 'address');\n\n}); // end of $(document).ready function\n"
},
{
"answer_id": 6996975,
"author": "ownking",
"author_id": 275443,
"author_profile": "https://Stackoverflow.com/users/275443",
"pm_score": 1,
"selected": false,
"text": " $(\"select.myselect\").bind(\"focus\", function(){\n if($(this).hasClass('readonly'))\n {\n $(this).blur(); \n return;\n }\n });\n"
},
{
"answer_id": 7881751,
"author": "john",
"author_id": 1011657,
"author_profile": "https://Stackoverflow.com/users/1011657",
"pm_score": 0,
"selected": false,
"text": "$('select[name=country]').attr(\"disabled\", \"disabled\"); \n"
},
{
"answer_id": 8270505,
"author": "Kadmillos",
"author_id": 1065791,
"author_profile": "https://Stackoverflow.com/users/1065791",
"pm_score": 1,
"selected": false,
"text": "<select onfocus=\"this.blur();\"> selectElement.addEventListener(\"focus\", selectElement.blur, true); selectElement.attachEvent(\"focus\", selectElement.blur); //thanks, IE selectElement.removeEventListener(\"focus\", selectElement.blur, true); selectElement.detachEvent(\"focus\", selectElement.blur); //thanks, IE"
},
{
"answer_id": 8415623,
"author": "fiatjaf",
"author_id": 973380,
"author_profile": "https://Stackoverflow.com/users/973380",
"pm_score": 0,
"selected": false,
"text": "span .readonly .toVanish .toShow $( '.readonly' ).live( 'focus', function(e) {\n $( this ).attr( 'readonly', 'readonly' )\n if( $( this ).get(0).tagName == 'SELECT' ) {\n $( this ).before( '<span class=\"toVanish readonly\" style=\"border:1px solid; padding:5px\">' \n + $( this ).find( 'option:selected' ).html() + '</span>' )\n $( this ).addClass( 'toShow' )\n $( this ).hide()\n }\n });\n"
},
{
"answer_id": 8997253,
"author": "Sojourneer",
"author_id": 1168371,
"author_profile": "https://Stackoverflow.com/users/1168371",
"pm_score": 1,
"selected": false,
"text": "<select onfocus=\"this.oldvalue=this.value;this.blur();\" onchange=\"this.value=this.oldvalue;\">\n....\n</select>\n"
},
{
"answer_id": 10559934,
"author": "Black Brick Software",
"author_id": 1390470,
"author_profile": "https://Stackoverflow.com/users/1390470",
"pm_score": 5,
"selected": false,
"text": "readonly jQuery('select.readonly option:not(:selected)').attr('disabled',true);\n readonly=\"readonly\" $('select[readonly=\"readonly\"] option:not(:selected)').attr('disabled',true);\n"
},
{
"answer_id": 13300183,
"author": "tamersalama",
"author_id": 7693,
"author_profile": "https://Stackoverflow.com/users/7693",
"pm_score": 0,
"selected": false,
"text": "$(function(){\n\n $.prototype.toggleDisable = function(flag) {\n // prepare some values\n var selectId = $(this).attr('id');\n var hiddenId = selectId + 'hidden';\n if (flag) {\n // disable the select - however this will not submit the value of the select\n // a new hidden form element will be created below to compensate for the \n // non-submitted select value \n $(this).attr('disabled', true);\n\n // gather attributes\n var selectVal = $(this).val();\n var selectName = $(this).attr('name');\n\n // creates a hidden form element to submit the value of the disabled select\n $(this).parents('form').append($('<input></input>').\n attr('type', 'hidden').\n attr('id', hiddenId).\n attr('name', selectName).\n val(selectVal) );\n } else {\n // remove the newly-created hidden form element\n $(this).parents('form').remove(hiddenId);\n // enable back the element\n $(this).removeAttr('disabled');\n }\n }\n\n // Usage\n // $('#some_select_element').toggleDisable(true);\n // $('#some_select_element').toggleDisable(false);\n\n});\n"
},
{
"answer_id": 14712627,
"author": "Rafael Moni",
"author_id": 1141308,
"author_profile": "https://Stackoverflow.com/users/1141308",
"pm_score": 1,
"selected": false,
"text": "$(function(){\n $('#myform').validate({\n submitHandler:function(form){\n $('select').removeAttr('disabled');\n form.submit();\n }\n });\n});\n"
},
{
"answer_id": 15710655,
"author": "David",
"author_id": 867903,
"author_profile": "https://Stackoverflow.com/users/867903",
"pm_score": 2,
"selected": false,
"text": " $value = $element->getValue();\n $options = $element->getAttrib('options');\n $sole_option = array($value => $options[$value]);\n $element->setAttrib('options', $sole_option);\n"
},
{
"answer_id": 17195507,
"author": "unplugandplay",
"author_id": 2501896,
"author_profile": "https://Stackoverflow.com/users/2501896",
"pm_score": -1,
"selected": false,
"text": "disabled=\"disabled\""
},
{
"answer_id": 17468595,
"author": "cernunnos",
"author_id": 2076150,
"author_profile": "https://Stackoverflow.com/users/2076150",
"pm_score": 3,
"selected": false,
"text": "$(\"select[readonly]\").find(\"option:not(:selected)\").hide().attr(\"disabled\",true);\n $(\"select[readonly] option:not(:selected)\")\n"
},
{
"answer_id": 18603212,
"author": "Wendell Carvalho",
"author_id": 2293214,
"author_profile": "https://Stackoverflow.com/users/2293214",
"pm_score": 0,
"selected": false,
"text": " $('form').submit(function () {\n $(\"#Id_Unidade\").attr(\"disabled\", false);\n });\n"
},
{
"answer_id": 20357432,
"author": "gbear",
"author_id": 3062483,
"author_profile": "https://Stackoverflow.com/users/3062483",
"pm_score": -1,
"selected": false,
"text": "submitdisabledcontrols POST"
},
{
"answer_id": 21185189,
"author": "Joaquim Perez",
"author_id": 2539512,
"author_profile": "https://Stackoverflow.com/users/2539512",
"pm_score": 3,
"selected": false,
"text": "readonly disabled $('select.readonly option:not(:selected)').attr('disabled',true);\n\n$('select:not([readonly]) option').removeAttr('disabled');\n"
},
{
"answer_id": 23428851,
"author": "vimal1083",
"author_id": 2557900,
"author_profile": "https://Stackoverflow.com/users/2557900",
"pm_score": 8,
"selected": false,
"text": "<select>\n <option disabled>1</option>\n <option selected>2</option>\n <option disabled>3</option>\n</select>"
},
{
"answer_id": 25187231,
"author": "d.raev",
"author_id": 1621821,
"author_profile": "https://Stackoverflow.com/users/1621821",
"pm_score": 5,
"selected": false,
"text": "select[readonly]{\n background: #eee;\n cursor:no-drop;\n}\n\nselect[readonly] option{\n display:none;\n}\n"
},
{
"answer_id": 25321681,
"author": "Yaje",
"author_id": 3706101,
"author_profile": "https://Stackoverflow.com/users/3706101",
"pm_score": 6,
"selected": false,
"text": "readOnly select css $('#selection').css('pointer-events','none');\n"
},
{
"answer_id": 25537719,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 4,
"selected": false,
"text": "$(\"#YourSELECTIdHere option:not(:selected)\").prop(\"disabled\", true);\n"
},
{
"answer_id": 25750518,
"author": "gordon",
"author_id": 778294,
"author_profile": "https://Stackoverflow.com/users/778294",
"pm_score": 0,
"selected": false,
"text": "var thisId=\"\";\nvar thisVal=\"\";\nfunction selectAll(){\n $(\"#\"+thisId+\" option\").each(function(){\n if(!$(this).prop(\"disabled\"))$(this).prop(\"selected\",true);\n });\n $(\"#\"+thisId).prop(\"disabled\",false);\n}\n$(document).ready(function(){\n $(\"select option:not(:selected)\").attr('disabled',true);\n $(\"select[multiple]\").focus(function(){\n thisId=$(this).prop(\"id\");\n thisVal=$(this).val();\n $(this).prop(\"disabled\",true).blur();\n setTimeout(\"selectAll();\",200);\n });\n});\n"
},
{
"answer_id": 26916519,
"author": "Guilherme Ferreira",
"author_id": 835753,
"author_profile": "https://Stackoverflow.com/users/835753",
"pm_score": 3,
"selected": false,
"text": "$(\"select[readonly]\").live(\"focus mousedown mouseup click\",function(e){\n e.preventDefault();\n e.stopPropagation();\n});\n"
},
{
"answer_id": 27478905,
"author": "ramesh shinde",
"author_id": 4361353,
"author_profile": "https://Stackoverflow.com/users/4361353",
"pm_score": 0,
"selected": false,
"text": "$(\"document\").ready(function(){ \n var mapping=$(\"select[name=mapping]\").val();\n $(\"select[name=mapping]\").change(function(){\n $(\"select[name=mapping]\").val(mapping);\n });\n});\n"
},
{
"answer_id": 33518475,
"author": "Afwan Zikri",
"author_id": 5110131,
"author_profile": "https://Stackoverflow.com/users/5110131",
"pm_score": 1,
"selected": false,
"text": "<select id=\"case_reason\" name=\"case_reason\" disabled=\"disabled\">\n disabled=\"disabled\" -> readonly=\"readonly\" ->"
},
{
"answer_id": 39351277,
"author": "nrofis",
"author_id": 1725836,
"author_profile": "https://Stackoverflow.com/users/1725836",
"pm_score": 5,
"selected": false,
"text": "select[readonly] option, select[readonly] optgroup {\n display: none;\n}\n readonly"
},
{
"answer_id": 41129909,
"author": "Syd",
"author_id": 4297315,
"author_profile": "https://Stackoverflow.com/users/4297315",
"pm_score": 2,
"selected": false,
"text": "<select> <select name='day' id='day'>\n <option>SUN</option>\n <option>MON</option>\n <option>TUE</option>\n <option>WED</option>\n <option>THU</option>\n <option>FRI</option>\n <option>SAT</option>\n</select>\n document.getElementById('day').innerHTML = '<option>FRI</option>';\n <select name='day' id='day'>\n <option>FRI</option>\n</select>\n <FORM>"
},
{
"answer_id": 42267236,
"author": "mainak chakraborty",
"author_id": 4542480,
"author_profile": "https://Stackoverflow.com/users/4542480",
"pm_score": 4,
"selected": false,
"text": "style=\"pointer-events: none;\"\n"
},
{
"answer_id": 49904151,
"author": "jBelanger",
"author_id": 3616841,
"author_profile": "https://Stackoverflow.com/users/3616841",
"pm_score": 3,
"selected": false,
"text": ".disabled {\n pointer-events:none; /* No cursor */\n background-color: #eee; /* Gray background */\n}\n $(\".disabled\").attr(\"tabindex\", \"-1\");\n <select class=\"disabled\">\n <option value=\"0\">0</option>\n</select>\n\n<input type=\"text\" class=\"disabled\" />\n $(document).on(\"mousedown\", \".disabled\", function (e) {\n e.preventDefault();\n});\n"
},
{
"answer_id": 52375366,
"author": "Sam",
"author_id": 1460758,
"author_profile": "https://Stackoverflow.com/users/1460758",
"pm_score": 0,
"selected": false,
"text": " #region Prepare Action Priviledges\n editAuditVM.ExtAuditEditRoleMatrixVM = new ExtAuditEditRoleMatrixVM\n {\n CanEditAcn = _extAuditEditRoleMatrixHelper.CanEditAcn(user, audit),\n CanEditSensitiveDesignation = _extAuditEditRoleMatrixHelper.CanEditSensitiveDesignation(user, audit),\n CanEditTitle = _extAuditEditRoleMatrixHelper.CanEditTitle(),\n CanEditAuditScope = _extAuditEditRoleMatrixHelper.CanEditAuditScope(user, audit)\n };\n #endregion\n\n\n #region Prepare SelectLists for Drop Downs\n #region AuditScope List\n IQueryable<SelectListItem> auditScopes = _auditTypesRepo.AuditTypes\n .Where(at => at.AuditTypeClassCode.ToLower() == \"e\")\n .Select(at => new SelectListItem\n { Text = at.AuditTypeText, Value = at.AuditTypeID.ToString() });\n // Cannot make a select readonly on client side.\n // So only return currently selected option.\n if (!editAuditVM.ExtAuditEditRoleMatrixVM.CanEditAuditScope)\n {\n auditScopes = auditScopes\n .Where(ascopeId => ascopeId.Value == editAuditVM.ExternalAudit.AuditTypeID.ToString());\n }\n #endregion\n #endregion\n"
},
{
"answer_id": 59789947,
"author": "Alex Begun",
"author_id": 6029751,
"author_profile": "https://Stackoverflow.com/users/6029751",
"pm_score": 0,
"selected": false,
"text": "setDropdownReadOnly('yourIdGoesHere',true/false)\n function setDropdownReadOnly(controlName, state) {\n var ddl = document.getElementById(controlName);\n\n for (i = 0; i < ddl.length; i++) {\n if (i == ddl.selectedIndex)\n ddl[i].disabled = false;\n else\n ddl[i].disabled = state;\n }\n }\n"
},
{
"answer_id": 63112507,
"author": "Joost00719",
"author_id": 7081176,
"author_profile": "https://Stackoverflow.com/users/7081176",
"pm_score": 3,
"selected": false,
"text": "select[readonly] {\n pointer-events:none;\n}\n"
},
{
"answer_id": 63948980,
"author": "R.P. Pedraza",
"author_id": 10580490,
"author_profile": "https://Stackoverflow.com/users/10580490",
"pm_score": 0,
"selected": false,
"text": "select[readonly] { pointer-events: none; } $(document).on('keydown', 'select[readonly]', function(e) {\n if (e.keyCode != 9) {\n if (e.preventDefault) {\n e.preventDefault();\n }\n\n e.returnValue = false;\n e.cancel = true;\n }\n});\n"
},
{
"answer_id": 65255358,
"author": "vinyll",
"author_id": 328117,
"author_profile": "https://Stackoverflow.com/users/328117",
"pm_score": 2,
"selected": false,
"text": "input <select> input.querySelectorAll(':not([selected])').forEach(option => {\n option.disabled = true\n})\n option"
},
{
"answer_id": 71119201,
"author": "vincent salomon",
"author_id": 18183749,
"author_profile": "https://Stackoverflow.com/users/18183749",
"pm_score": 0,
"selected": false,
"text": "addReadOnlyToFormElements = function (idElement) {\n \n // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items\n $('#' + idElement + ' select>option:not([selected])').prop('disabled',true);\n \n // and, on the selected ones, to mimic readOnly appearance\n $('#' + idElement + ' select').css('background-color','#eee');\n }\n removeReadOnlyFromFormElements = function (idElement) {\n\n // Remove the disabled attribut on non-selected \n $('#' + idElement + ' select>option:not([selected])').prop('disabled',false);\n\n // Remove readOnly appearance on selected ones\n $('#' + idElement + ' select').css('background-color','');\n}\n"
},
{
"answer_id": 71611573,
"author": "Jacobski",
"author_id": 6550194,
"author_profile": "https://Stackoverflow.com/users/6550194",
"pm_score": 0,
"selected": false,
"text": "$(\"select[id='country']\").val('PH').attr(\"disabled\", true);\n$(\"select[id='country']\").parent().append(\"<input type='hidden' id='country' value='PH'>\");\n $(\"select[id='country']\").attr(\"disabled\", false);\n$(\"input[id='country']\").remove();\n"
},
{
"answer_id": 72059014,
"author": "Wagner Pereira",
"author_id": 3954704,
"author_profile": "https://Stackoverflow.com/users/3954704",
"pm_score": 0,
"selected": false,
"text": "document.querySelectorAll(\"select[readonly] > option:not([selected])\").forEach( (el) => el.setAttribute(\"disabled\", \"disabled\") ); without readonly: <select>\n <option>1</option>\n <option selected>2</option>\n <option>3</option>\n</select>\n\n<br>\nwith readonly: <select readonly=\"readonly\">\n <option>1</option>\n <option selected>2</option>\n <option>3</option>\n</select>"
},
{
"answer_id": 72241445,
"author": "Nick Asher",
"author_id": 6198751,
"author_profile": "https://Stackoverflow.com/users/6198751",
"pm_score": 3,
"selected": false,
"text": "<select style=\"pointer-events: none;\" onclick=\"return false;\" onkeydown=\"return false;\" ></select>\n let isReadOnly = true ;\n\nselectElement.onclick = function () {\n return !isReadOnly ;\n};\nselectElement.onkeydown =function(){\n return !isReadOnly ;\n} ;\nselectElement.style.pointerEvents = isReadOnly ? \"none\" : \"all\" ;"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
] |
368,830 | <p>I currently have some code that pulls down a list of users in a group and then iterates through that group to determine if a given account exists, but it seems like there ought to be a more concise (and perhaps faster) way to accomplish this.</p>
<p>This code (VB.NET) attempts to use the member property of the group object, but it is returning false even when the user is a member of that group. Can anyone see what I am doing wrong here?</p>
<pre><code>Dim group As DirectoryEntry = GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)
Dim user As DirectoryEntry =GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)
Return group.Properties("member").Contains(user.Path)
</code></pre>
<p>FYI: The GetNetworkObject calls just return a directoryEntry object, I have confirmed that the correct object is being returned for both the group and user object.</p>
| [
{
"answer_id": 368890,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 5,
"selected": true,
"text": "static bool IsUserMemberOf(string userName, string groupName)\n{\n using (var ctx = new PrincipalContext(ContextType.Domain))\n using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))\n using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))\n {\n return userPrincipal.IsMemberOf(groupPrincipal);\n }\n}\n\n// Usage:\nbool result = IsUserMemberOf(\"CONTOSO\\\\john.doe\", \"CONTOSO\\\\Administrators\");\n"
},
{
"answer_id": 368971,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": 2,
"selected": false,
"text": "Set wshNet = CreateObject(\"WScript.Network\") 'Setup connection to the Network\nSet fso = CreateObject(\"Scripting.FileSystemObject\") 'Create File System Object for any file manipulations\n\nSet ADSysInfo = CreateObject(\"ADSystemInfo\") 'Setup connection to Active Directory\nSet CurrentUser = GetObject(\"LDAP://\" & ADSysInfo.UserName) 'Setup current user to look for in Active Directory\nstrGroups = LCase(Join(CurrentUser.MemberOf)) 'Grabs all the groups the current user is a member of\n If InStr(strGroups, \"MyGroup\") Then MyGroupSub\n"
},
{
"answer_id": 369000,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 1,
"selected": false,
"text": "Dim DSearcher As New DirectorySearcher(group, \"(&(objectClass=user)(cn=\" + Login + \"))\", New String() {\"member;Range=0-5000\"}, SearchScope.OneLevel) \ngroup = GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)\nuser = GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)\nDSearcher.AttributeScopeQuery = \"member\"\nReturn (DSearcher.FindOne() IsNot Nothing)\n"
},
{
"answer_id": 369650,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 1,
"selected": false,
"text": "dSearch.Filter = String.Format(\"(&(memberOf={0})(objectSid={1}))\", groupDN, WindowsIdentity.GetCurrent.User)\n\nReturn dSearch.FindOne() IsNot Nothing\n searchName = searchName.Replace(\"\\\", \"\\5c\"). _\n Replace(\"/\", \"\\2f\"). _\n Replace(\"*\", \"\\2a\"). _\n Replace(\"(\", \"\\28\"). _\n Replace(\")\", \"\\29\")\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30018/"
] |
368,831 | <p>i would to know how to write a profiler? What books and / or articles recommended? Can anyone help me please?</p>
<p>Someone has already done something like this?</p>
| [
{
"answer_id": 738647,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 3,
"selected": false,
"text": "I I I I I1 I2 I2 I1 I2 I1"
},
{
"answer_id": 874632,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 0,
"selected": false,
"text": "strlen strlen(s) s[i] for MyFile.cpp:502 HisFile.cpp:113 strlen"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24639/"
] |
368,832 | <p>I have a PHP script (running on a Linux server) that ouputs the names of some files on the server. It outputs these file names in a simple text-only format.</p>
<p>This output is read from a VB.NET program by using HttpWebRequest, HttpWebResponse, and a StreamReader.</p>
<p>The problem is that some of the file names being output contain... unusual characters. Specifically, the "section" symbol (§). </p>
<p>If I view the output of the PHP script in a web browser, the symbol appears fine.</p>
<p>But when I read the output of the PHP script into my .NET program, the symbol doesn't appear correctly (it appears as a generic "block" symbol). </p>
<p>I've tried all the different character encoding options that you can use when reading the response stream (from the HttpWebResponse). I've tried outputting the stream directly to a text file (no good), displaying it in a TextBox (no good), and even when viewing the results directly in the Visual Studio debugger, the character appears as a block instead of as the "section" symbol. </p>
<p>I've examined the output in a hex editor (as suggested by a related question, "<a href="https://stackoverflow.com/questions/29499/how-do-you-troubleshoot-character-encoding-problems">how do you troubleshoot character encoding problems</a>." </p>
<p>When I write out the section symbol (§) from .NET itself, the hex bytes I see representing it are "c2 a7" (makes sense if it's unicode, right? requires two bytes?). When I write out the output from the PHP script directly to a file and examine that with a hex editor, the symbol shows up as "ef bf bd" - three bytes instead of two?</p>
<p>I'm at a loss as to what to do - if I need to specify some other character encoding, or if I'm missing something obvious about this. </p>
<p>Here's the code that's used to get the output of the PHP script (VB-style comments modified so they appear correctly on this site):</p>
<pre><code>
Dim myRequest As HttpWebRequest = WebRequest.Create("http://www.example.com/sample.php")
Dim myResponse As HttpWebResponse = myRequest.GetResponse()
// read the response stream
Dim myReader As New StreamReader(myResponse.GetResponseStream())
// read the entire output in one block (just as an example)
Dim theOutput as String = myReader.ReadToEnd()
</code></pre>
<p>Any ideas? </p>
<ul>
<li>Am I using the wrong kind of StreamReader? (I've tried passing the character encoding in the call to create the new StreamReader - I've tried all the ones that are in System.Text.Encoding - UTF-8, UTF-7, ASCII, UTF-32, Unicode, etc.)</li>
<li>Should I be using a different method for reading the output of the PHP script? </li>
<li>Is there something I should be doing different on the PHP-side when outputting the text?</li>
</ul>
<p><strong>UPDATED INFO:</strong></p>
<ul>
<li>The output from PHP is specifically encoded UTF-8 by calling: <code>utf8_encode($file);</code></li>
<li>When I wrote out the symbol from .NET, I copied and pasted the symbol from the Character Map app in Windows. I also copied & pasted it directly from the file's name (in Windows) and from this web page itself - all gave the same hex value when written out (c2 a7).</li>
<li>Yes, the "section symbol" I'm talking about is U+00A7 (ALT+0167 on Windows, according to Character Map).</li>
<li>The content-type is set explicitly via <code>header('Content-Type: text/html; charset=utf-8');</code> right at the beginning of the PHP script.</li>
</ul>
<p><strong>UPDATE:</strong></p>
<p>Figured it out myself, but I couldn't have done it without the help from the people who answered. Thank you!</p>
| [
{
"answer_id": 368848,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "utf8_encode($file)"
},
{
"answer_id": 368939,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 1,
"selected": false,
"text": "utf8_encode($file) Content-Type charset Content-Type: text/html; charset=utf-8\n"
},
{
"answer_id": 369117,
"author": "Keithius",
"author_id": 5956,
"author_profile": "https://Stackoverflow.com/users/5956",
"pm_score": 3,
"selected": true,
"text": "utf8_encode()"
},
{
"answer_id": 9162210,
"author": "AdrenalineJunky",
"author_id": 374572,
"author_profile": "https://Stackoverflow.com/users/374572",
"pm_score": 0,
"selected": false,
"text": "$feed = header(\"Content-Type: text/html; charset=utf-8\");\n$feed.=utf8_encode(readfile(rawurldecode($_GET[\"url\"])));\n$feed = fread(rawurldecode($_GET[\"url\"]));\ndie($feed);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5956/"
] |
368,858 | <p>I've been working with <a href="http://www.microsoft.com/Sqlserver/" rel="nofollow noreferrer">Microsoft SQL Server</a> with many years now but have only just recently started to use <a href="http://www.mysql.com/" rel="nofollow noreferrer">MySQL</a> with my web applications, and I'm hungry for knowledge.</p>
<p>To continue with the long line of <a href="https://stackoverflow.com/questions/tagged/hidden-features">"hidden feature" questions</a>, I would like to know any hidden or handy features of MySQL which will hopefully improve my knowledge of this open source database.</p>
| [
{
"answer_id": 368894,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": false,
"text": "mysql> show processlist;\nshow processlist;\n+----+-------------+-----------------+------+---------+------+----------------------------------+------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+----+-------------+-----------------+------+---------+------+----------------------------------+------------------+\n| 1 | root | localhost:32893 | NULL | Sleep | 0 | | NULL |\n| 5 | system user | | NULL | Connect | 98 | Waiting for master to send event | NULL |\n| 6 | system user | | NULL | Connect | 5018 | Reading event from the relay log | NULL |\n+-----+------+-----------+---------+---------+-------+-------+------------------+\n3 rows in set (0.00 sec) \n mysql>kill 5 \n"
},
{
"answer_id": 368920,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 4,
"selected": false,
"text": "mysql> SHOW open TABLES FROM test;\n+----------+-------+--------+-------------+\n| DATABASE | TABLE | In_use | Name_locked |\n+----------+-------+--------+-------------+\n| test | a | 3 | 0 |\n+----------+-------+--------+-------------+\n1 row IN SET (0.00 sec)\n"
},
{
"answer_id": 385935,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": false,
"text": "inet_ntoa() inet_aton()"
},
{
"answer_id": 596646,
"author": "SorinV",
"author_id": 69524,
"author_profile": "https://Stackoverflow.com/users/69524",
"pm_score": 3,
"selected": false,
"text": "<query>\\G -- \\G in the CLI instead of the ; will show one column per row\nexplain <query>; -- this will show the execution plan for the query\n"
},
{
"answer_id": 600830,
"author": "Mike Trader",
"author_id": 18749,
"author_profile": "https://Stackoverflow.com/users/18749",
"pm_score": 8,
"selected": true,
"text": "max_connections ALTER TABLE mytable AUTO_INCREMENT = value; \n UNIX_TIMESTAMP() \n FROM_UNIXTIME() \n UTC_DATE()\n UTC_TIME()\n UTC_TIMESTAMP()\n #Master Binary Logging Config STATEMENT causes replication \n to be statement-based - default\n\nlog-bin=Mike\nbinlog-format=STATEMENT\nserver-id=1 \nmax_binlog_size = 10M\nexpire_logs_days = 120 \n\n\n#Slave Config\nmaster-host=master-hostname\nmaster-user=slave-user\nmaster-password=slave-password\nserver-id=2\n SET AUTOCOMMIT = 0;\nSET FOREIGN_KEY_CHECKS=0;\n\n.. your dump file ..\n\nSET FOREIGN_KEY_CHECKS = 1;\nCOMMIT;\nSET AUTOCOMMIT = 1;\n mytable virtualcolumn Unknown column ‘the first bit of data what you want to put into the table‘ in ‘field list’\n INSERT INTO table (this, that) VALUES ($this, $that)\n INSERT INTO table (this, that) VALUES ('$this', '$that') \n"
},
{
"answer_id": 954777,
"author": "serbaut",
"author_id": 84760,
"author_profile": "https://Stackoverflow.com/users/84760",
"pm_score": 1,
"selected": false,
"text": "innodb_file_per_table"
},
{
"answer_id": 1021604,
"author": "DBMarcos99",
"author_id": 123595,
"author_profile": "https://Stackoverflow.com/users/123595",
"pm_score": 2,
"selected": false,
"text": "\\! cat file1.sql\n \\T filename\n mysql -u root -p < case1.sql\n"
},
{
"answer_id": 1024698,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "on duplicate key insert into occurances(word,count) values('foo',1),('bar',1) \n on duplicate key cnt=cnt+1\n"
},
{
"answer_id": 1025682,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 3,
"selected": false,
"text": "pager less\nselect lots_of_stuff FROM tbl WHERE clause_which_matches_10k_rows;\n pager tee myfile.txt\nselect a_few_things FROM tbl WHERE i_want_to_save_output_to_a_file;\n"
},
{
"answer_id": 1026664,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "SHOW CREATE TABLE CountryLanguage CountryLanguage | CREATE TABLE countrylanguage (\n CountryCode char(3) NOT NULL DEFAULT '',\n Language char(30) NOT NULL DEFAULT '',\n IsOfficial enum('T','F') NOT NULL DEFAULT 'F',\n Percentage float(4,1) NOT NULL DEFAULT '0.0',\n PRIMARY KEY (CountryCode,Language)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1\n SELECT CountryCode\n, GROUP_CONCAT(Language) AS List\nFROM CountryLanguage\nGROUP BY CountryCode \n +-------------+------------------------------------+\n| CountryCode | List |\n+-------------+------------------------------------+\n| ABW | Dutch,English,Papiamento,Spanish |\n. ... . ... .\n| ZWE | English,Ndebele,Nyanja,Shona |\n+-------------+------------------------------------+\n SELECT CountryCode\n, GROUP_CONCAT(\n Language\n, IF(IsOfficial='T', ' (Official)', '')\n ) AS List\nFROM CountryLanguage\nGROUP BY CountryCode\n +-------------+---------------------------------------------+\n| CountryCode | List |\n+-------------+---------------------------------------------+\n| ABW | Dutch (Official),English,Papiamento,Spanish |\n. ... . ... .\n| ZWE | English (Official),Ndebele,Nyanja,Shona |\n+-------------+---------------------------------------------+\n SELECT CountryCode\n, GROUP_CONCAT(Language SEPARATOR ' and ') AS List\nFROM CountryLanguage\nGROUP BY CountryCode\n +-------------+----------------------------------------------+\n| CountryCode | List |\n+-------------+----------------------------------------------+\n| ABW | Dutch and English and Papiamento and Spanish |\n. ... . ... .\n| ZWE | English and Ndebele and Nyanja and Shona |\n+-------------+----------------------------------------------+\n SELECT CountryCode\n, GROUP_CONCAT(\n Language\n ORDER BY CASE IsOfficial WHEN 'T' THEN 1 ELSE 2 END DESC\n , Language\n ) AS List\nFROM CountryLanguage\nGROUP BY CountryCode\n +-------------+------------------------------------+\n| CountryCode | List |\n+-------------+------------------------------------+\n| ABW | English,Papiamento,Spanish,Dutch, |\n. ... . ... .\n| ZWE | Ndebele,Nyanja,Shona,English |\n+-------------+------------------------------------+\n SELECT COUNT(DISTINCT CountryCode, Language) FROM CountryLanguage SELECT Country.Code, Country.Continent, COUNT(CountryLanguage.Language)\nFROM CountryLanguage \nINNER JOIN Country \nON CountryLanguage.CountryCode = Country.Code\nGROUP BY Country.Code\n GROUP BY Country.Code, Country.Continent\n SELECT Country.Code, MAX(Country.Continent), COUNT(CountryLanguage.Language)\n SELECT Country.Code, COUNT(CountryLanguage.Language), CountryLanguage.Percentage\nFROM CountryLanguage \nINNER JOIN Country \nON CountryLanguage.CountryCode = Country.Code\nGROUP BY Country.Code\n"
},
{
"answer_id": 1115937,
"author": "Arjan",
"author_id": 84237,
"author_profile": "https://Stackoverflow.com/users/84237",
"pm_score": 2,
"selected": false,
"text": "0000-00-00"
},
{
"answer_id": 7499572,
"author": "Johan",
"author_id": 650492,
"author_profile": "https://Stackoverflow.com/users/650492",
"pm_score": 2,
"selected": false,
"text": "WHERE (x.id > y.id) OR (x.id = y.id AND x.f2 > y.f2) \n WHERE (x.id, x.f2) > (y.id, y.f2)\n"
},
{
"answer_id": 7698468,
"author": "Osvaldo Mercado",
"author_id": 550178,
"author_profile": "https://Stackoverflow.com/users/550178",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM mytable\nWHERE date(date_colum) BETWEEN '2011-01-01' AND ''2011-03-03';\n SELECT * FROM mytable\nWHERE date_column BETWEEN '2011-01-01 00:00:00' AND '2011-03-03 23:59:59'\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
368,879 | <p>I have an application which tries to load some expected registry settings within its constructor.</p>
<p>What is the most appropriate .NET Exception from the BCL to throw if these (essential, non-defaultable) registry settings cannot be loaded?</p>
<p>For example:</p>
<pre><code> RegistryKey registryKey = Registry.LocalMachine.OpenSubkey("HKLM\Foo\Bar\Baz");
// registryKey might be null!
if (registryKey == null)
{
// What exception to throw?
throw new ???Exception("Could not load settings from HKLM\foo\bar\baz.");
}
</code></pre>
| [
{
"answer_id": 368891,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 4,
"selected": true,
"text": "throw new ArgumentException(\"Could not find registry key: \" + theKey);\n"
},
{
"answer_id": 368898,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 4,
"selected": false,
"text": "public class KeyNotFoundException : RegistryException\n{\n public KeyNotFoundException(string message)\n : base(message) { }\n}\npublic class RegistryException : Exception\n{\n public RegistryException(string message)\n : base(message) { }\n}\n\n....\n\nif (registryKey == null)\n{\n throw new KeyNotFoundException(\"Could not load settings from HKLM\\foo\\bar\\baz.\");\n}\n Exception ApplicationException"
},
{
"answer_id": 368903,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "System.UnauthorizedAccess FileNotFound"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5975/"
] |
368,904 | <p>I have a classic 3-tier ASP.Net 3.5 web application with forms that display business objects and allow them to be edited. Controls on the form correspond to a property of the underlying business object. The user will have read/write, readonly, or no access to the various controls depending on his/her role. Very conventional stuff.</p>
<p>My question is: what is the object-oriented best practice for coding this? Is there anything more elegant than wrapping each control in a test for the user's role and setting its Visible and Enabled properties?</p>
<p>Thanks</p>
| [
{
"answer_id": 1743719,
"author": "Julian Bromwich",
"author_id": 212262,
"author_profile": "https://Stackoverflow.com/users/212262",
"pm_score": 3,
"selected": true,
"text": "/** NO permissions.\n * Presentation: \"hidden\"\n * Database: \"no access\"\n */\nNONE(0),\n\n/** VIEW permissions.\n * Presentation: \"read-only\"\n * Database: \"read access\"\n */\nVIEW(1),\n\n/** VIEW and POPULATE permissions.\n * Presentation: \"required/highlighted\"\n * Database: \"non-null\"\n */\nREQUIRED(2),\n\n/** VIEW, POPULATE, and DEPOPULATE permissions.\n * Presentation: \"editable\"\n * Database: \"nullable\"\n */\nEDIT(3);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44394/"
] |
368,913 | <p>What's a good way to serialize a Delphi object tree to XML--using RTTI and not custom code?</p>
<p>I would have loved to find that this feature is already built into Delphi, but it doesn't seem to be.</p>
<p>I've found a few components (posted, below) that seem like they might perform this function. Have you used any of them or some other offering? Have you built your own? Am I missing something obvious, in Delphi?</p>
| [
{
"answer_id": 368972,
"author": "Andreas Hausladen",
"author_id": 44005,
"author_profile": "https://Stackoverflow.com/users/44005",
"pm_score": 5,
"selected": true,
"text": "uses\n JvAppXMLStorage;\n\nvar\n Storage: TJvAppXMLFileStorage;\nbegin\n Storage := TJvAppXMLFileStorage.Create(nil);\n try\n Storage.WritePersistent('', MyObject);\n Storage.Xml.SaveToFile('S:\\TestFiles\\Test.xml');\n\n Storage.Xml.LoadFromFile('S:\\TestFiles\\Test.xml');\n Storage.ReadPersistent('', MyObject);\n finally\n Storage.Free;\n end;\nend;\n"
},
{
"answer_id": 370799,
"author": "Marek Jedliński",
"author_id": 9226,
"author_profile": "https://Stackoverflow.com/users/9226",
"pm_score": 4,
"selected": false,
"text": "// saving:\npers : TPersistent;\n// SaveToFile is a class method, so no need to instantiate the object:\nTOmniXMLWriter.SaveToFile( pers, 'd:\\path\\file.xml', pfAttributes, ofIndent );\n // loading:\nTOmniXMLWriter.LoadFromFile( pers, 'd:\\path\\file.xml' ); \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32841/"
] |
368,924 | <p>Is there any simple way to access the <code>DataContext</code> in a linq2sql entity class.</p>
<p>I'm trying to create something like <code>EntitySet</code> but I cannot figure out how the <code>EntitySet</code> has access to the context that created the entity object in the first place.</p>
<p>I want to have a regular linq2sql entity class with a way for the class to access the <code>DataContext</code> that created it. I know it's possible because when you have an entity class with a primary key linq2sql gives you the option to load all children without creating a new <code>DataContext</code>.</p>
| [
{
"answer_id": 369618,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "EntitySet<T> Source"
},
{
"answer_id": 818987,
"author": "Monty",
"author_id": 83791,
"author_profile": "https://Stackoverflow.com/users/83791",
"pm_score": 0,
"selected": false,
"text": "Partial Class SalesOrder\n Private moContext As L2S_SalesOrdersDataContext\n\n Friend Property Context() As L2S_SalesOrdersDataContext\n Get\n Return moContext\n End Get\n Set(ByVal value As L2S_SalesOrdersDataContext)\n moContext = value\n End Set\n End Property\n...\n"
},
{
"answer_id": 2434487,
"author": "Dan",
"author_id": 76086,
"author_profile": "https://Stackoverflow.com/users/76086",
"pm_score": 3,
"selected": false,
"text": "public interface ISandboxObject : INotifyPropertyChanging\n{\n // This is just a marker interface for Extension Methods\n}\n /// <summary>\n /// Obtain the DataContext providing this entity\n /// </summary>\n /// <param name=\"obj\"></param>\n /// <returns></returns>\n public static DataContext GetContext(this ISandboxObject obj)\n {\n FieldInfo fEvent = obj.GetType().GetField(\"PropertyChanging\", BindingFlags.NonPublic | BindingFlags.Instance);\n MulticastDelegate dEvent = (MulticastDelegate)fEvent.GetValue(obj);\n Delegate[] onChangingHandlers = dEvent.GetInvocationList();\n\n // Obtain the ChangeTracker\n foreach (Delegate handler in onChangingHandlers)\n {\n if (handler.Target.GetType().Name == \"StandardChangeTracker\")\n {\n // Obtain the 'services' private field of the 'tracker'\n object tracker = handler.Target;\n object services = tracker.GetType().GetField(\"services\", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(tracker);\n\n // Get the Context\n DataContext context = services.GetType().GetProperty(\"Context\").GetValue(services, null) as DataContext;\n return context;\n }\n }\n\n // Not found\n throw new Exception(\"Error reflecting object\");\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35371/"
] |
368,926 | <p>What's the easiest way to figure out if a window is opened modally or not?</p>
<p><strong>CLARIFICATION:</strong></p>
<p>I open a window calling </p>
<pre><code>myWindow.ShowDialog();
</code></pre>
<p>I have a footer with an "OK" & "Cancel" button that I only want to show if the window is opened modally. Now I realize I can set a property by doing this:</p>
<pre><code>myWindow.IsModal = true;
myWindow.ShowDialog();
</code></pre>
<p>But I want the window itself to make that determination. I want to check in the <code>Loaded</code> event of the window whether or not it is modal.</p>
<p><strong>UPDATE</strong></p>
<p>The <code>IsModal</code> property doesn't <em>actually</em> exist in a WPF window. It's a property that I have created. <code>ShowDialog()</code> blocks the current thread. </p>
<p>I'm guessing I can determine if the Window is opened via <code>ShowDialog()</code> by checking if the current thread is blocked. How would I go about doing that?</p>
| [
{
"answer_id": 368969,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "dim f as myWindow\nf.show\nsomeOtherMethod()\n dim f as myWindow\nf.showDialog\nsomeOtherMethod()\n dim f as MyWindow\nf.ShowDialog(true)\n Public Function Shadows ShowDialog(myVar as boolean) As Boolean\n if myVar then ShowButtons()\n return mybase.ShowDialog()\nEnd Function \n"
},
{
"answer_id": 369021,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 3,
"selected": false,
"text": "Dim frm As New Window2\nfrm.ShowDialog()\n Private _IsModal As Boolean = False 'This will be changed in the IsModal method\n\nPublic Property IsModal() As Boolean\n Get\n Return _IsModal\n End Get\n Set(ByVal value As Boolean)\n _IsModal = value\n End Set\nEnd Property\n\nPublic Shadows Sub ShowDialog()\n IsModal = True\n MyBase.ShowDialog()\nEnd Sub\n"
},
{
"answer_id": 369077,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 0,
"selected": false,
"text": "void Window2_Loaded(object sender, RoutedEventArgs e)\n{\n var hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;\n var el = AutomationElement.FromHandle(hwnd);\n\n Object oPattern = null;\n\n if (el.TryGetCurrentPattern(WindowPattern.Pattern, out oPattern))\n {\n var pattern = oPattern as WindowPattern;\n\n this.Title = pattern.Current.IsModal.ToString();\n }\n}\n"
},
{
"answer_id": 1266900,
"author": "CMerat",
"author_id": 95032,
"author_profile": "https://Stackoverflow.com/users/95032",
"pm_score": 5,
"selected": false,
"text": "_showingAsDialog public static bool IsModal(this Window window)\n{\n return (bool)typeof(Window).GetField(\"_showingAsDialog\", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window);\n}\n"
},
{
"answer_id": 8916285,
"author": "Pluck",
"author_id": 1157031,
"author_profile": "https://Stackoverflow.com/users/1157031",
"pm_score": 2,
"selected": false,
"text": " public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n Window window = value as Window;\n if (window != null)\n { \n var showingAsDialogFieldInfo = typeof(System.Windows.Window).GetField(\"_showingAsDialog\",\n BindingFlags.NonPublic | BindingFlags.Instance);\n if ((bool) showingAsDialogFieldInfo.GetValue(window) == false)\n {\n return Visibility.Visible;\n }\n }\n return Visibility.Hidden;\n }\n"
},
{
"answer_id": 56769264,
"author": "Stefan Ott",
"author_id": 10866650,
"author_profile": "https://Stackoverflow.com/users/10866650",
"pm_score": 0,
"selected": false,
"text": "public class Dialog : Window\n{\n private bool IsDialog;\n\n new public bool? ShowDialog()\n {\n IsDialog = true;\n return base.ShowDialog();\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
368,927 | <p>I am working in the Linux environment, and I have a C++ program, what I want is when I cancel the program with ctrl+c I would like that the program executes a function, to close some files and print some sutff, is there any way to do this?. Thank you. </p>
| [
{
"answer_id": 368949,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 2,
"selected": false,
"text": "void sigint_handler(int sig)\n{\n [do some cleanup]\n signal(SIGINT, SIG_DFL);\n kill(getpid(), SIGINT);\n}\n"
},
{
"answer_id": 369080,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": false,
"text": "#include <signal.h>\n#include <stdio.h>\n#include <stdbool.h>\n\nvolatile bool STOP = false;\nvoid sigint_handler(int sig);\n\nint main() {\n signal(SIGINT, sigint_handler);\n while(true) {\n if (STOP) {\n break;\n }\n }\n return 0;\n}\n\nvoid sigint_handler(int sig) {\n printf(\"\\nCTRL-C detected\\n\");\n STOP = true;\n}\n [user@host]$ ./a.out \n^C\nCTRL-C detected\n"
},
{
"answer_id": 369138,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 0,
"selected": false,
"text": "SetConsoleCtrlHandler CTRL_C_EVENT CTRL_BREAK_EVENT CTRL_CLOSE_EVENT"
},
{
"answer_id": 376059,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 4,
"selected": true,
"text": "signal() sigaction() #include<stdio.h>\n#include<unistd.h>\n#include<signal.h>\n#include<string.h>\n\nstruct sigaction old_action;\n\nvoid sigint_handler(int sig_no)\n{\n printf(\"CTRL-C pressed\\n\");\n sigaction(SIGINT, &old_action, NULL);\n kill(0, SIGINT);\n}\n\nint main()\n{\n\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = &sigint_handler;\n sigaction(SIGINT, &action, &old_action);\n\n pause();\n\n return 0;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39160/"
] |
368,929 | <p>Say I want to design a database for a community site with blogs, photos, forums etc., one way to do this is to single out the concept of a "post", as a blog entry, a blog comment, a photo, a photo comment, a forum post all can be thought as a post. So, I could potentially have one table named Post [PostID, PostType, Title, Body .... ], the PostType will tell what type of post it is.</p>
<p>Or I could design this whole thing with more tables, BlogPost, PhotoPost, ForumPost, and I'll leave Comment just it's own table with a CommentType column.</p>
<p>Or have a Post table for all types of post, but have a separate Comment table.</p>
<p>To be complete I'm using ADO.NET Entity Framework to implement my DAL. </p>
<p>Now the question what are some of the implications if I go with any route described above that will influence on my DB performance and manageability, middle tier design and code cleaness, EF performance etc.?</p>
<p>Thank you very much!</p>
<p>Ray.</p>
| [
{
"answer_id": 369019,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 2,
"selected": false,
"text": "Post BlogPost ForumPost Comment Post"
},
{
"answer_id": 369223,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "create table posts (post_id number primary key, \n post_date date,\n post_title ...); /* All the common attributes */\n\ncreate table photo_post (post_id references posts, photograph ...);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32240/"
] |
368,943 | <p>How do I get the div from within this (the last) list item?</p>
<p>Currently I have this, which is just plain ugly...any suggestions on a cleaner selector/ solution?</p>
<pre><code>var div = ul.append("<li><div></div></li>").contents("li:last-child")[0].children[0];
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 368955,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 0,
"selected": false,
"text": "var div = ul.append(\"<li><div></div></li>\").contents(\"li:last-child > div\")[0];\n"
},
{
"answer_id": 368960,
"author": "Chatu",
"author_id": 39203,
"author_profile": "https://Stackoverflow.com/users/39203",
"pm_score": 0,
"selected": false,
"text": "ul.append(\"<li><div></div></li>\").contents(\"li:last-child > div\").get(0);\n"
},
{
"answer_id": 368979,
"author": "Lindsay",
"author_id": 23520,
"author_profile": "https://Stackoverflow.com/users/23520",
"pm_score": 2,
"selected": false,
"text": "var div = $('<div/>'); \n// do whatever you need to do with the div\n$('<li/>').appendTo(ul).append(div);\n"
},
{
"answer_id": 368993,
"author": "Mark Bell",
"author_id": 43140,
"author_profile": "https://Stackoverflow.com/users/43140",
"pm_score": 0,
"selected": false,
"text": "var div = ul.append('<li><div></div></li>').find(\"li:last div\");\n"
},
{
"answer_id": 368994,
"author": "brad",
"author_id": 208,
"author_profile": "https://Stackoverflow.com/users/208",
"pm_score": 0,
"selected": false,
"text": " var div = $('<li><div/></li>').appendTo(ul).find('div');\n"
},
{
"answer_id": 369004,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "var div = $('<div></div>').appendTo($(\"<li></li>\").appendTo(ul));\n"
},
{
"answer_id": 369031,
"author": "Manik",
"author_id": 41381,
"author_profile": "https://Stackoverflow.com/users/41381",
"pm_score": 0,
"selected": false,
"text": "var div = ul.append(\"<li><div></div></li>\").find('div').get(0);\n"
},
{
"answer_id": 369062,
"author": "Ben Blank",
"author_id": 46387,
"author_profile": "https://Stackoverflow.com/users/46387",
"pm_score": 2,
"selected": true,
"text": "var div = $(\"<div/>\").appendTo($(\"<li/>\").appendTo(ul));\n var div = $(\"<div/>\").appendTo($(\"<li/>\").appendTo(ul))[0];\n"
},
{
"answer_id": 369318,
"author": "Ata",
"author_id": 46110,
"author_profile": "https://Stackoverflow.com/users/46110",
"pm_score": 0,
"selected": false,
"text": "var div = ul.append(\"<li><div></div></li>\").find(\"div:last\");\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5791/"
] |
368,954 | <p>Probably not much more to elaborate on here - I'm using a NumericStepper control and I want the user to use the buttons only to change the value in the NS, not by typing into the control - I couldn't find a property to disable the text - does it exist? </p>
<p>If it doesn't, how would I subclass this thing to disable the text?</p>
| [
{
"answer_id": 369039,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 1,
"selected": false,
"text": "mx_internal::inputField.enabled = false;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
368,956 | <p>I have forms in my page a get and a post and i want add pager on my get form .. so i cant page through the results.. </p>
<p>The problem that i am having is when i move to the second page it does not display anything..</p>
<p>I am using this library for paging ..
<a href="http://stephenwalther.com/Blog/archive/2008/09/18/asp-net-mvc-tip-44-create-a-pager-html-helper.aspx" rel="nofollow noreferrer">http://stephenwalther.com/Blog/archive/2008/09/18/asp-net-mvc-tip-44-create-a-pager-html-helper.aspx</a></p>
<p>this my actions code.</p>
<pre><code> [AcceptVerbs("GET")]
public ActionResult SearchByAttraction()
{
return View();
}
[AcceptVerbs("POST")]
public ActionResult SearchByAttraction(int? id, FormCollection form)
{....
}
</code></pre>
<p>and this is what i am using on my get form to page through</p>
<p><%= Html.Pager(ViewData.Model)%> //but when i do this it goes to
this method
[AcceptVerbs("GET")]
public ActionResult SearchByAttraction()</p>
<p>instead of going to this this</p>
<p>[AcceptVerbs("POST")] public ActionResult SearchByAttraction(int? id, FormCollection form)</p>
<p>which sort of makes sence .. but i cant really think of any other way of doing this</p>
<p>Any help would be very appreciated.. </p>
<p>Thanx</p>
| [
{
"answer_id": 369049,
"author": "maxnk",
"author_id": 45862,
"author_profile": "https://Stackoverflow.com/users/45862",
"pm_score": 1,
"selected": false,
"text": "1. make form on the page:\n <form id=\"myForm\" action=\"your/url\" method=\"post\">\n <input type=\"hidden\" name=\"page\" />\n\n <input type=\"hidden\" name=\"your_param1\" />\n <input type=\"hidden\" name=\"your_param2\" />\n <input type=\"hidden\" name=\"your_paramN\" />\n </form>\n\n2. make changes to pager - it should produce something like that:\n\n <ul id=\"pager\">\n <li><a href=\"url/as/was/created/by/pager\" onclick=\"return submitMyForm(1);\">1</a></li>\n <li><a href=\"url/as/was/created/by/pager\" onclick=\"return submitMyForm(2);\">2</a></li>\n <li><a href=\"url/as/was/created/by/pager\" onclick=\"return submitMyForm(3);\">3</a></li>\n </ul>\n\n3. add simple javascript function on the page:\n\n <script language=\"javascript\" type=\"text/javascript\">\n function submitMyForm(page) {\n var form = document.forms[\"myForm\"];\n form.elements[\"page\"].value = page;\n form.submit();\n return false;\n }\n </script>\n"
},
{
"answer_id": 369218,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 1,
"selected": false,
"text": "[AcceptVerbs(\"GET\")]\npublic ActionResult SearchByAttraction(int? id)\n{\n return View();\n} \n"
},
{
"answer_id": 369298,
"author": "devforall",
"author_id": 43838,
"author_profile": "https://Stackoverflow.com/users/43838",
"pm_score": 1,
"selected": false,
"text": " [AcceptVerbs(\"GET\")]\n public ActionResult SearchByAttraction()\n {\n return View();\n }\n\n public ActionResult Search(FormCollection form,int? id)\n {\n var info = _repository.ListByLocation(city, postal, pageIndex, 2);\n return View(\"SearchByAttraction\", info); \n }\n <% using (Html.BeginForm(\"Search\", \"Home\", FormMethod.Get))\n{ %>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43838/"
] |
368,963 | <p>I wish to store a single variable in my application that will be saved between runs. This will be a version number that will be used to trigger an update option and so will change only rarely.</p>
<p>Does anyone have suggestions on the best way of implementing this? Considering it's such a simple requirement I am interested in the simplest solution.</p>
<p>Thanks!</p>
| [
{
"answer_id": 377065,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 0,
"selected": false,
"text": "c:\\System\\Apps\\${AppName}\\${filename}"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
368,966 | <p>I'm trying to do query result pagination with hibernate and displaytag, and Hibernate <code>DetachedCriteria</code> objects are doing their best to stand in the way. Let me explain...</p>
<p>The easiest way to do pagination with displaytag seems to be implementing the <code>PaginatedList</code> interface that has, among others, the following methods:</p>
<pre><code>/* Gets the total number of results. */
int getFullListSize();
/* Gets the current page of results. */
List getList();
/* Gets the page size. */
int getObjectsPerPage();
/* Gets the current page number. */
int getPageNumber();
/* Get the sorting column and direction */
String getSortCriterion();
SortOrderEnum getSortDirection();
</code></pre>
<p>I'm thinking of throwing my PaginatedList implementation a Criteria object and let it work along theese lines...</p>
<pre><code>getFullListSize() {
criteria.setProjection(Projections.rowCount());
return ((Long) criteria.uniqueResult()).intValue();
}
getList() {
if (getSortDirection() == SortOrderEnum.ASCENDING) {
criteria.addOrder(Order.asc(getSortCriterion());
} else if (getSortDirection() == SortOrderEnum.DECENDING) {
criteria.addOrder(Order.desc(getSortCriterion());
}
return criteria.list((getPageNumber() - 1) * getObjectsPerPage(),
getObjectsPerPage());
}
</code></pre>
<p>But this doesn't work, because the <code>addOrder()</code> or the <code>setProjection()</code> calls modify the criteria object rendering it in-usable for the successive calls. I'm not entirely sure of the order of the calls, but the db throws an error on <code>getFullListSize()</code> trying to do a "<code>select count(*) ... order by ...</code>" which is obviously wrong.</p>
<p>I think I could fix this by creating an object of my own to keep track of query conditions and rebuilding the Criteria object for each call, but that feels like reinventing yet another wheel. Is there a smarter way, possibly copying the Criteria initially passed in and working on that copy?</p>
<p><strong><em>Update</em></strong>:
It looks like <code>getList</code> is called first, and <code>getFullListSize</code> is called multiple times after, so, as soon as there's an ordering passed in, <code>getFullListSize</code> will fail. It would make sense to hit the db only once (in <code>getList</code> I'd say) and cache the results, with no need to copy/reset the <code>Criteria</code> object, but still...</p>
<p><strong><em>Update (again)</em></strong>:
Forget about that, once I've done the <code>count</code> I can't do the <code>select</code>, and vice versa. I really need two distinct <code>Criteria</code> objects.</p>
| [
{
"answer_id": 374333,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 1,
"selected": false,
"text": "DetachedCriteria PaginatedList"
},
{
"answer_id": 805842,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 0,
"selected": false,
"text": "Criteria.forClass(myDAO.getPersistentClass())\n .add(myRestrictions)\n .addOrder(<someOrder>)\n Criteria.forClass(myDAO.getPersistentClass())\n .add(myRestrictions)\n .setProjection(Projections.rowCount());\n"
},
{
"answer_id": 1472958,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "Criteria.setProjection(null);\nCriteria.setResultTransformer(Criteria.ROOT_ENTITY);\n"
},
{
"answer_id": 3271148,
"author": "bobac",
"author_id": 385764,
"author_profile": "https://Stackoverflow.com/users/385764",
"pm_score": -1,
"selected": false,
"text": "public static DetachedCriteria Clone(this DetachedCriteria criteria)\n{\n var dummy = criteria.ToByteArray();\n return dummy.FromByteArray<DetachedCriteria>();\n}\n"
},
{
"answer_id": 61224468,
"author": "Marcin",
"author_id": 8537786,
"author_profile": "https://Stackoverflow.com/users/8537786",
"pm_score": 0,
"selected": false,
"text": "ICriteria criteria = ...(your original criteria init here)...;\n\nvar criteriaClone = (ICriteria)criteria.Clone();\n ICriteria criteria = ...(your original criteria init here)...; \nvar countCrit = (ICriteria)criteria.Clone();\ncountCrit.ClearOrders(); // avoid missing group by exceptions\n\nvar rowCount = countCrit\n .SetProjection(Projections.RowCount()).FutureValue<Int32>();\n\nvar results = criteria\n .SetFirstResult(pageIndex * pageSize)\n .SetMaxResults(pageSize)\n .Future<T>();\n\nvar resultsArray = results.GetEnumerable();\n\nvar totalCount = rowCount.Value;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6069/"
] |
368,967 | <p>There example on the net and code given in Learn OpenCv,Orielly.</p>
<p>After many attempts the out.avi file is written with 0 bytes.
I wonder where i went wrong.</p>
<p>The following are the code i used...</p>
<pre><code>int main(int argc, char* argv[]) {
CvCapture* input = cvCaptureFromFile(argv[1]);
IplImage* image = cvRetrieveFrame(input);
if (!image) {
printf("Unable to read input");
return 0;
}
CvSize imgSize;
imgSize.width = image->width;
imgSize.height = image->height;
double fps = cvGetCaptureProperty(
input,
CV_CAP_PROP_FPS
);
CvVideoWriter *writer = cvCreateVideoWriter(
"out.avi",
CV_FOURCC('M', 'J', 'P', 'G'),
fps,
imgSize
);
IplImage* colourImage;
//Keep processing frames...
for (;;) {
//Get a frame from the input video.
colourImage = cvQueryFrame(input);
cvWriteFrame(writer, colourImage);
}
cvReleaseVideoWriter(&writer);
cvReleaseCapture(&input);
}
</code></pre>
| [
{
"answer_id": 397703,
"author": "sgielen",
"author_id": 13104,
"author_profile": "https://Stackoverflow.com/users/13104",
"pm_score": 0,
"selected": false,
"text": "if(colourImage == NULL) {\n printf(\"Warning - got NULL colourImage\\n\");\n continue;\n}\ncvNamedWindow( \"test\", 1);\ncvShowImage( \"test\", colourImage );\ncvWaitKey( 0 );\ncvDestroyWindow( \"test\" );\n"
},
{
"answer_id": 901657,
"author": "Rick2047",
"author_id": 110426,
"author_profile": "https://Stackoverflow.com/users/110426",
"pm_score": 1,
"selected": false,
"text": " #include<cv.h>\n #include<highgui.h>\n #include<cvaux.h>\n #include<cvcam.h>\n #include<cxcore.h>\n\n int main()\n {\n CvVideoWriter *writer = 0;\n int isColor = 1;\n int fps = 5; // or 30\n int frameW = 1600; //640; // 744 for firewire cameras\n int frameH = 1200; //480; // 480 for firewire cameras\n //writer=cvCreateVideoWriter(\"out.avi\",CV_FOURCC('P','I','M','1'),\n // fps,cvSize(frameW,frameH),isColor);\n writer=cvCreateVideoWriter(\"out.avi\",-1,\n fps,cvSize(frameW,frameH),isColor);\n IplImage* img = 0; \n\n img=cvLoadImage(\"CapturedFrame_0.jpg\");\n cvWriteFrame(writer,img); // add the frame to the file\n img=cvLoadImage(\"CapturedFrame_1.jpg\");\n cvWriteFrame(writer,img);\n img=cvLoadImage(\"CapturedFrame_2.jpg\");\n cvWriteFrame(writer,img);\n img=cvLoadImage(\"CapturedFrame_3.jpg\");\n cvWriteFrame(writer,img);\n img=cvLoadImage(\"CapturedFrame_4.jpg\");\n cvWriteFrame(writer,img);\n img=cvLoadImage(\"CapturedFrame_5.jpg\");\n cvWriteFrame(writer,img);\n\n cvReleaseVideoWriter(&writer);\n return 0;\n }\n"
},
{
"answer_id": 1186868,
"author": "Rick2047",
"author_id": 110426,
"author_profile": "https://Stackoverflow.com/users/110426",
"pm_score": 0,
"selected": false,
"text": " cv.h \n highgui.h \n cvaux.h \n cvcam.h \n cxcore.h \n\nint main(){\n\n CvVideoWriter *writer = 0;\n int isColor = 1;\n int fps = 5; // or 30\n IplImage* img = 0; \n img=cvLoadImage(\"animTest_1.bmp\");\n int frameW = img->width; //640; // 744 for firewire cameras\n int frameH = img->height; //480; // 480 for firewire cameras\n\n writer=cvCreateVideoWriter(\"out.avi\",-1,\n fps,cvSize(frameW,frameH),1);\n\n cvWriteFrame(writer, img); // add the frame to the file\n\n char *FirstFile,fF[20]=\"\",*fileNoStr,fns[4]=\"\";\n fileNoStr=fns;\n for(int fileNo;fileNo<100;fileNo++){\n FirstFile=fF; \n itoa(fileNo,fileNoStr,10);\n FirstFile=strcat ( FirstFile,\"animTest_\");\n FirstFile=strcat ( FirstFile,fileNoStr);\n FirstFile=strcat ( FirstFile,\".bmp\");\n\n printf(\" \\n%s .\",FirstFile);\n img=cvLoadImage(FirstFile);\n\n cvWriteFrame(writer, img);\n\n }\n cvReleaseVideoWriter(&writer);\n\n return 0;\n}\n"
},
{
"answer_id": 3071265,
"author": "user370469",
"author_id": 370469,
"author_profile": "https://Stackoverflow.com/users/370469",
"pm_score": 0,
"selected": false,
"text": "cvReleaseVideoWriter(&writer); cvReleaseCapture(&input); for(int i=0; i<200; i++)"
},
{
"answer_id": 9118442,
"author": "ewleina",
"author_id": 1185941,
"author_profile": "https://Stackoverflow.com/users/1185941",
"pm_score": 1,
"selected": false,
"text": "-1 cvCreateVideo 1"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43076/"
] |
368,976 | <p>I have an abstract class defining a pure virtual method in c++:</p>
<pre><code>class Base
{
Base();
~Base();
virtual bool Test() = 0;
};
</code></pre>
<p>I have subclassed this with a number of other classes (which provide an implementation for Test()), which I'll refer to as A, B, C, etc. I now want to create an array of any of these types using this base class:</p>
<pre><code>int main(int argc, char* argv[])
{
int size = 0;
Base* bases = new Base[10];
bases[size++] = new A();
bases[size++] = new B();
for (int i = 0; i < size; i++)
{
Base* base = bases[i];
base->Test();
}
}
</code></pre>
<p>(Excuse any errors I might have made, I'm writing this on the fly to provide a simple example).</p>
<p>The problem is I can't instantiate the array as it would require creating an instance of the Base class (which it can't do as it's abstract). However, without doing this, it hasn't allocated the memory needed to assign to the indices of the array, and thus provides a segmentation fault when trying to access that memory. I am under the impression that it's not good practice to mix new and delete with malloc and free.</p>
<p>It may be that I have confused the way this should be used and I should be attempting to use templates or some other mechanism to do this, but hopefully I've provided enough information to illustrate what I'm attempting to do.</p>
<p>So what is the best way of doing this and how would I get around this problem of allocating memory to an abstract class?</p>
<p>Thanks,
Dan</p>
| [
{
"answer_id": 368984,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "int main(int argc, char* argv[])\n{\n int size = 0;\n Base** bases = new Base*[10];\n\n bases[size++] = new A();\n bases[size++] = new B();\n\n for (int i = 0; i < size; i++)\n {\n Base* base = bases[i];\n base->Test();\n }\n}\n"
},
{
"answer_id": 368991,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "virtual ~Base();\n Base** bases = new Base *[10];\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
368,981 | <p>I have a full path which I would like to remove certain levels of it. So for instance,</p>
<pre><code>/home/john/smith/web/test/testing/nothing/
</code></pre>
<p>I would like to get rid of 4 levels, so I get</p>
<pre><code>/test/testing/nothing/
</code></pre>
<p>What would be a good of doing this?</p>
<p>Thanks</p>
| [
{
"answer_id": 368989,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": true,
"text": "join(\"/\", array_slice(explode(\"/\", $path), 5));\n preg_replace('~^/home/john/smith/web/~', '', $path);\n"
},
{
"answer_id": 371208,
"author": "Jay",
"author_id": 41690,
"author_profile": "https://Stackoverflow.com/users/41690",
"pm_score": -1,
"selected": false,
"text": "$s_path = '/home/john/smith/web/test/testing/nothing/';\n$s_path = str_replace('john/smith/web/test/', '', $s_path);\n realpath() '../../' dirname(__FILE__) rtrim()"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
368,997 | <p>I have a column that contains dates, when I click the column header the column is sorted numerically and not by date. How would I sort this by date? The date is in the format dd/mm/yy.</p>
<p>Example (sorted oldest first):</p>
<p>10/12/08 <--December
10/09/08 <--September
12/12/08 <--December</p>
<p>Many thanks</p>
| [
{
"answer_id": 369014,
"author": "Gunny",
"author_id": 12830,
"author_profile": "https://Stackoverflow.com/users/12830",
"pm_score": 3,
"selected": false,
"text": "myDataTable.Columns[\"ColumnName\"].DataType = System.Type.GetType(\"System.Date\");\n"
},
{
"answer_id": 3324967,
"author": "stepd",
"author_id": 401030,
"author_profile": "https://Stackoverflow.com/users/401030",
"pm_score": 1,
"selected": false,
"text": "dgv.Rows[rowId].Cells[\"colCreated\"].Style.Format = \"HH:mm :: dd/MM/yyyy\";\n"
},
{
"answer_id": 13428566,
"author": "Endkill",
"author_id": 1831461,
"author_profile": "https://Stackoverflow.com/users/1831461",
"pm_score": 1,
"selected": false,
"text": "dataGridView1.Columns[colNum].DefaultCellStyle.Format = \"d\";\n colNum d HH:mm:ss"
},
{
"answer_id": 58836102,
"author": "peregrinus",
"author_id": 2067788,
"author_profile": "https://Stackoverflow.com/users/2067788",
"pm_score": 0,
"selected": false,
"text": "//Init \ndataGridView_records.Columns[0].DefaultCellStyle.Format = \"dd/MM/yy HH:mm:ss\";\n DateTime date = DateTime.ParseExact((String)drs[\"data\"], \"dd/MM/yy HH:mm:ss\", CultureInfo.InvariantCulture);\nobject[] gdr = new object[1] { date };//add the other columns data here\ndataGridView_records.Rows.Add(gdr); \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.