qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
45,908
<p>After answering on <a href="https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664">this question</a> I thought it would be nice to collect some tips &amp; tricks for working with MSVS solutions and projects. </p> <p>Here is my list: </p> <ul> <li><p>How to avoid saving new projects automatically to reduce garbage in file system.</p> <p>Uncheck <strong>Tools->Options->Projects and Solutions->Save new projects when created</strong></p></li> <li><p>How to add common file to multiple projects without copying it to project’s directory.</p> <p>Right click on a project, select <strong>Add->Existing Item->Add as link</strong> (press on small arrow on Add button)</p></li> <li><p>How to add project to solution without including it in the build process</p> <p>Right click on solution, select <strong>Add->New solution folder</strong>.<br> Right click on created folder, <strong>select Add->Add existing project</strong></p></li> <li><p>How to edit project file from Visual Studio?</p> <p>Right click on project and select <strong>Unload Project</strong>, right click on unloaded project and select <strong>Edit</strong>. Or install <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow noreferrer">Power Commands</a> and select <strong>Edit Project File</strong></p></li> <li><p>How to group files in the project tree (like auto-generated files for WinForms controls)</p> <p>Open project file for editing. </p></li> </ul> <pre> Change</pre> <pre><code>&lt;Compile Include="MainFile.cs" /&gt; &lt;Compile Include="SecondaryFile.cs" /&gt; To &lt;Compile Include="SecondaryFile.cs "&gt; &lt;DependentUpon&gt; MainFile.cs &lt;/DependentUpon&gt; &lt;/Compile&gt; </code></pre> <p>Do you have anything else to add?</p>
[ { "answer_id": 156311, "author": "Mario", "author_id": 472, "author_profile": "https://Stackoverflow.com/users/472", "pm_score": 2, "selected": false, "text": "open <filename> open alias o open o <filename> login.aspx .cs" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
45,924
<p>My users are having an intermittent error when using a Windows Forms application built in VB.NET 3.5. Apparently when they click on the form and the form re-paints, a red 'X' will be painted over the MenuStrip control and the app will crash with the following error. </p> <p>Has anyone seen this before? Can someone point me in the right direction? </p> <pre><code> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index) at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs) at System.Windows.Forms.Control.WmPaint(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ScrollableControl.WndProc(Message&amp; m) at System.Windows.Forms.ToolStrip.WndProc(Message&amp; m) at System.Windows.Forms.MenuStrip.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre>
[ { "answer_id": 156311, "author": "Mario", "author_id": 472, "author_profile": "https://Stackoverflow.com/users/472", "pm_score": 2, "selected": false, "text": "open <filename> open alias o open o <filename> login.aspx .cs" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
45,941
<p>I've used subversion for a while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.</p> <p>So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?</p>
[ { "answer_id": 45978, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 3, "selected": true, "text": "svn merge trunkURL\n" }, { "answer_id": 46154, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 1, "selected": false, "text": "svnadmin upgrade REPOS_PATH\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
45,953
<p>I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.</p> <p>Any suggestions would be much appreciated.</p>
[ { "answer_id": 45966, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 10, "selected": true, "text": "exec(sprintf(\"%s > %s 2>&1 & echo $! >> %s\", $cmd, $outputfile, $pidfile));\n $cmd $outputfile $pidfile function isRunning($pid){\n try{\n $result = shell_exec(sprintf(\"ps %d\", $pid));\n if( count(preg_split(\"/\\n/\", $result)) > 2){\n return true;\n }\n }catch(Exception $e){}\n\n return false;\n}\n" }, { "answer_id": 46008, "author": "Eric Goodwin", "author_id": 1430, "author_profile": "https://Stackoverflow.com/users/1430", "pm_score": 5, "selected": false, "text": "proc_close( proc_open( \"./command --foo=1 &\", array(), $foo ) );\n" }, { "answer_id": 2254982, "author": "Captain Obvious", "author_id": 172166, "author_profile": "https://Stackoverflow.com/users/172166", "pm_score": 4, "selected": false, "text": "<?php\n\nini_set(\"display_errors\",1);\nerror_reporting(E_ALL);\n\necho \"<pre>loading page</pre>\";\n\nfunction run_background_process()\n{\n file_put_contents(\"testprocesses.php\",\"foreground start time = \" . time() . \"\\n\");\n echo \"<pre> foreground start time = \" . time() . \"</pre>\";\n\n // output from the command must be redirected to a file or another output stream \n // http://ca.php.net/manual/en/function.exec.php\n\n exec(\"php background.php > testoutput.php 2>&1 & echo $!\", $output);\n\n echo \"<pre> foreground end time = \" . time() . \"</pre>\";\n file_put_contents(\"testprocesses.php\",\"foreground end time = \" . time() . \"\\n\", FILE_APPEND);\n return $output;\n}\n\necho \"<pre>calling run_background_process</pre>\";\n\n$output = run_background_process();\n\necho \"<pre>output = \"; print_r($output); echo \"</pre>\";\necho \"<pre>end of page</pre>\";\n?>\n <?\nfile_put_contents(\"testprocesses.php\",\"background start time = \" . time() . \"\\n\", FILE_APPEND);\nsleep(10);\nfile_put_contents(\"testprocesses.php\",\"background end time = \" . time() . \"\\n\", FILE_APPEND);\n?>\n loading page\ncalling run_background_process\n foreground start time = 1266003600\n foreground end time = 1266003600\noutput = Array\n(\n [0] => 15010\n)\nend of page\n foreground start time = 1266003600\nforeground end time = 1266003600\nbackground start time = 1266003600\nbackground end time = 1266003610\n" }, { "answer_id": 4832703, "author": "Neven Boyanov", "author_id": 594345, "author_profile": "https://Stackoverflow.com/users/594345", "pm_score": 3, "selected": false, "text": "sleep(5); // some delay\nfile_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file\n $proc_command = \"wget.exe http://localhost/test-proc-bg.php -q -O - -b\";\n$proc = popen($proc_command, \"r\");\npclose($proc);\n -q keeps wget quiet.\n-O - outputs to stdout.\n-b works on background\n" }, { "answer_id": 7035131, "author": "Alex", "author_id": 891051, "author_profile": "https://Stackoverflow.com/users/891051", "pm_score": -1, "selected": false, "text": "<img src=\"run-in-background.php\" border=\"0\" alt=\"\" width=\"1\" height=\"1\" />" }, { "answer_id": 11954827, "author": "wlf", "author_id": 1595154, "author_profile": "https://Stackoverflow.com/users/1595154", "pm_score": 5, "selected": false, "text": ">/dev/null 2>/dev/null &\n shell_exec('service named reload >/dev/null 2>/dev/null &');\n" }, { "answer_id": 24025322, "author": "Morfidon", "author_id": 2393593, "author_profile": "https://Stackoverflow.com/users/2393593", "pm_score": 3, "selected": false, "text": "shell_exec('screen -dmS $name_of_screen $command'); \n" }, { "answer_id": 26170949, "author": "sgotre", "author_id": 2859620, "author_profile": "https://Stackoverflow.com/users/2859620", "pm_score": 1, "selected": false, "text": "fast_cgi_finish_request() $message ='job executed';\n$backgroundJob = function() use ($message) {\n //do some work here\n echo $message;\n}\n register_shutdown_function($backgroundJob);\n fast_cgi_finish_request();\n" }, { "answer_id": 30672118, "author": "Jimmy Ilenloa", "author_id": 2259400, "author_profile": "https://Stackoverflow.com/users/2259400", "pm_score": 0, "selected": false, "text": "<?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"notepad.exe\", 7, false); \n?> \n <?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"cmd /C dir /S %windir%\", 0, false); \n?> \n <?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"mspaint.exe\", 3, true); \n?> \n" }, { "answer_id": 34612967, "author": "Slava", "author_id": 1709903, "author_profile": "https://Stackoverflow.com/users/1709903", "pm_score": 3, "selected": false, "text": "function LaunchBackgroundProcess($command){\n // Run command Asynchroniously (in a separate thread)\n if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){\n // Windows\n $command = 'start \"\" '. $command;\n } else {\n // Linux/UNIX\n $command = $command .' /dev/null &';\n }\n $handle = popen($command, 'r');\n if($handle!==false){\n pclose($handle);\n return true;\n } else {\n return false;\n }\n}\n /B start /B start \"\" start" }, { "answer_id": 38179655, "author": "Pascal9x", "author_id": 2782340, "author_profile": "https://Stackoverflow.com/users/2782340", "pm_score": 2, "selected": false, "text": "<?php\nfunction startBackgroundProcess(\n $command,\n $stdin = null,\n $redirectStdout = null,\n $redirectStderr = null,\n $cwd = null,\n $env = null,\n $other_options = null\n) {\n $descriptorspec = array(\n 1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),\n 2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),\n );\n if (is_string($stdin)) {\n $descriptorspec[0] = array('pipe', 'r');\n }\n $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);\n if (!is_resource($proc)) {\n throw new \\Exception(\"Failed to start background process by command: $command\");\n }\n if (is_string($stdin)) {\n fwrite($pipes[0], $stdin);\n fclose($pipes[0]);\n }\n if (!is_string($redirectStdout)) {\n fclose($pipes[1]);\n }\n if (!is_string($redirectStderr)) {\n fclose($pipes[2]);\n }\n return $proc;\n}\n nul startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');\n startBackgroundProcess('ping yandex.com >nul 2>&1');\n $proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');\nprint_r(proc_get_status($proc));\n startBackgroundProcess('cat > input.txt', \"Hello world!\\n\");\n" }, { "answer_id": 46617107, "author": "Joshy Francis", "author_id": 6417678, "author_profile": "https://Stackoverflow.com/users/6417678", "pm_score": 2, "selected": false, "text": "function run_process($cmd,$outputFile = '/dev/null', $append = false){\n $pid=0;\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n $cmd = 'wmic process call create \"'.$cmd.'\" | find \"ProcessId\"';\n $handle = popen(\"start /B \". $cmd, \"r\");\n $read = fread($handle, 200); //Read the output \n $pid=substr($read,strpos($read,'=')+1);\n $pid=substr($pid,0,strpos($pid,';') );\n $pid = (int)$pid;\n pclose($handle); //Close\n }else{\n $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));\n }\n return $pid;\n }\n function is_process_running($pid){\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n //tasklist /FI \"PID eq 6480\"\n $result = shell_exec('tasklist /FI \"PID eq '.$pid.'\"' );\n if (count(preg_split(\"/\\n/\", $result)) > 0 && !preg_match('/No tasks/', $result)) {\n return true;\n }\n }else{\n $result = shell_exec(sprintf('ps %d 2>&1', $pid));\n if (count(preg_split(\"/\\n/\", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {\n return true;\n }\n }\n return false;\n }\n function stop_process($pid){\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n $result = shell_exec('taskkill /PID '.$pid );\n if (count(preg_split(\"/\\n/\", $result)) > 0 && !preg_match('/No tasks/', $result)) {\n return true;\n }\n }else{\n $result = shell_exec(sprintf('kill %d 2>&1', $pid));\n if (!preg_match('/No such process/', $result)) {\n return true;\n }\n }\n }\n" }, { "answer_id": 54409868, "author": "MAChitgarha", "author_id": 4215651, "author_profile": "https://Stackoverflow.com/users/4215651", "pm_score": 2, "selected": false, "text": "proc_*" }, { "answer_id": 64778230, "author": "TheKarateKid", "author_id": 1692693, "author_profile": "https://Stackoverflow.com/users/1692693", "pm_score": 1, "selected": false, "text": "/dev/null & exec(\"bg_process > /dev/null &\");\n $output exec()" }, { "answer_id": 71655444, "author": "Justin Jack", "author_id": 1678210, "author_profile": "https://Stackoverflow.com/users/1678210", "pm_score": 0, "selected": false, "text": " function threadproc($thread, $param) {\n \n echo \"\\tI'm a PHPThread. In this example, I was given only one parameter: \\\"\". print_r($param, true) .\"\\\" to work with, but I can accept as many as you'd like!\\n\";\n \n for ($i = 0; $i < 10; $i++) {\n usleep(1000000);\n echo \"\\tPHPThread working, very busy...\\n\";\n }\n \n return \"I'm a return value!\";\n}\n \n\n$thread_id = phpthread_create($thread, array(), \"threadproc\", null, array(\"123456\"));\n \necho \"I'm the main thread doing very important work!\\n\";\n \nfor ($n = 0; $n < 5; $n++) {\n usleep(1000000);\n echo \"Main thread...working!\\n\";\n}\n \necho \"\\nMain thread done working. Waiting on our PHPThread...\\n\";\n \nphpthread_join($thread_id, $retval);\n \necho \"\\n\\nOur PHPThread returned: \" . print_r($retval, true) . \"!\\n\";\n" }, { "answer_id": 73118719, "author": "Dev Matee", "author_id": 3743412, "author_profile": "https://Stackoverflow.com/users/3743412", "pm_score": 0, "selected": false, "text": "<?php\nfunction execInBackground($cmd) {\n if (substr(php_uname(), 0, 7) == \"Windows\"){\n pclose(popen(\"start /B \". $cmd, \"r\")); \n }\n else {\n exec($cmd . \" > /dev/null &\"); \n }\n}\n?>\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1071/" ]
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
[ { "answer_id": 3647010, "author": "emilmont", "author_id": 318098, "author_profile": "https://Stackoverflow.com/users/318098", "pm_score": 3, "selected": false, "text": ">>> from bintools.dwarf import DWARF\n>>> dwarf = DWARF('test/test')\n>>> dwarf.get_loc_by_addr(0x8048475)\n('/home/emilmont/Workspace/dbg/test/main.c', 36, 0)\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
45,964
<p>How do I multiply 10 to an <code>Integer</code> object and get back the <code>Integer</code> object?</p> <p>I am looking for the neatest way of doing this.</p> <p>I would probably do it this way: Get int from <code>Integer</code> object, multiply it with the other int and create another Integer object with this int value.</p> <p>Code will be something like ... </p> <pre><code>integerObj = new Integer(integerObj.intValue() * 10); </code></pre> <p>But, I saw a code where the author is doing it this way: Get the <code>String</code> from the <code>Integer</code> object, concatenate "0" at the end and then get <code>Integer</code> object back by using <code>Integer.parseInt</code></p> <p>The code is something like this:</p> <pre><code>String s = integerObj + "0"; integerObj = Integer.parseInt(s); </code></pre> <p>Is there any merit in doing it either way?</p> <p>And what would be the most efficient/neatest way in general and in this case?</p>
[ { "answer_id": 45975, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 6, "selected": true, "text": "Integer a = new Integer(2); // or even just Integer a = 2;\na *= 10;\nSystem.out.println(a);\n" }, { "answer_id": 46424, "author": "ckpwong", "author_id": 2551, "author_profile": "https://Stackoverflow.com/users/2551", "pm_score": 2, "selected": false, "text": "\"0\" s javac String s = new StringBuilder().append(integerObj.toString()).append(\"0\").toString() integerObj String s1 = integerObj + \"0\";\n String s2 = integerObj + \"0\"; (s1 == s2) false s1.equals(s2) true Integer.parseInt new Integer() Integer" }, { "answer_id": 24281194, "author": "Chris", "author_id": 1460848, "author_profile": "https://Stackoverflow.com/users/1460848", "pm_score": 0, "selected": false, "text": "Integer a = new Integer(2); // or even just Integer a = 2;\na *= 10;\nSystem.out.println(a); // will output 20\n Integer a = new Integer(2); // or even just Integer a = 2;\na = a.intValue() * 10;\nSystem.out.println(a.intValue()); // will output 20\n static void test() {\n Integer i = new Integer(10);\n System.out.println(\"StartingMemory: \" + System.identityHashCode(i));\n changeInteger(i);\n System.out.println(\"Step1: \" + i);\n changeInteger(++i);\n System.out.println(\"Step2: \" + i.intValue());\n System.out.println(\"MiddleMemory: \" + System.identityHashCode(i));\n}\n\nstatic void changeInteger(Integer i) {\n System.out.println(\"ChangeStartMemory: \" + System.identityHashCode(i));\n System.out.println(\"ChangeStartValue: \" + i);\n i++;\n System.out.println(\"ChangeEnd: \" + i);\n System.out.println(\"ChangeEndMemory: \" + System.identityHashCode(i));\n}\n StartingMemory: 1373539035\nChangeStartMemory: 1373539035\nChangeStartValue: 10\nChangeEnd: 11\nChangeEndMemory: 190331520\nStep1: 10\nChangeStartMemory: 190331520\nChangeStartValue: 11\nChangeEnd: 12\nChangeEndMemory: 1298706257\nStep2: 11\nMiddleMemory: 190331520\n System.out.println(\"MiddleMemory: \" + System.identityHashCode(i));\ntry {\n final Field f = i.getClass().getDeclaredField(\"value\");\n f.setAccessible(true);\n f.setInt(i, 15);\n System.out.println(\"Step3: \" + i.intValue());\n System.out.println(\"EndingMemory: \" + System.identityHashCode(i));\n} catch (final Exception e) {\n e.printStackTrace();\n}\n MiddleMemory: 190331520\nStep2: 15\nMiddleMemory: 190331520\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
45,972
<p>I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets scanned many times.</p> <p>Is there a rule of thumb for using <code>mmap()</code> versus reading in blocks via C++'s <code>fstream</code> library? What I'd like to do is read large blocks from disk into a buffer, process complete records from the buffer, and then read more.</p> <p>The <code>mmap()</code> code could potentially get very messy since <code>mmap</code>'d blocks need to lie on page sized boundaries (my understanding) and records could potentially lie across page boundaries. With <code>fstream</code>s, I can just seek to the start of a record and begin reading again, since we're not limited to reading blocks that lie on page sized boundaries.</p> <p>How can I decide between these two options without actually writing up a complete implementation first? Any rules of thumb (e.g., <code>mmap()</code> is 2x faster) or simple tests?</p>
[ { "answer_id": 46005, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 5, "selected": false, "text": "char data[0x1000];\nstd::ifstream in(\"file.bin\");\n\nwhile (in)\n{\n in.read(data, 0x1000);\n // do something with data\n}\n const int file_size=something;\nconst int page_size=0x1000;\nint off=0;\nvoid *data;\n\nint fd = open(\"filename.bin\", O_RDONLY);\n\nwhile (off < file_size)\n{\n data = mmap(NULL, page_size, PROT_READ, 0, fd, off);\n // do stuff with data\n munmap(data, page_size);\n off += page_size;\n}\n page_size mmap read read mmap read std::fstream Boost::Iostreams mmap .pack Boost::Iostreams std::streambuf std::istream std::filebuf mapped_filebuf std::fstream a mapped_fstream Boost::Iostreams" }, { "answer_id": 151865, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": false, "text": "char data[0x1000];\nstd::ifstream in(\"file.bin\");\n\nwhile (in)\n{\n in.read(data, 0x1000);\n // do something with data \n}\n char data[0x1000];\nstd::ifstream iifle( \"file.bin\");\nstd::istream in( ifile.rdbuf() );\n\nwhile( in )\n{\n in.read( data, 0x1000);\n // do something with data\n}\n" }, { "answer_id": 1897055, "author": "ony", "author_id": 230744, "author_profile": "https://Stackoverflow.com/users/230744", "pm_score": 1, "selected": false, "text": " addr1 = NULL;\n while( size_left > 0 ) {\n r = min(MMAP_SIZE, size_left);\n addr2 = mmap(NULL, r,\n PROT_READ, MAP_FLAGS,\n 0, pos);\n if (addr1 != NULL)\n {\n /* process mmap from prev cycle */\n feed_data(ctx, addr1, MMAP_SIZE);\n munmap(addr1, MMAP_SIZE);\n }\n addr1 = addr2;\n size_left -= r;\n pos += r;\n }\n feed_data(ctx, addr1, r);\n munmap(addr1, r);" }, { "answer_id": 6383253, "author": "Dietrich Epp", "author_id": 82294, "author_profile": "https://Stackoverflow.com/users/82294", "pm_score": 9, "selected": true, "text": "mmap read mmap read epoll poll read read mlock epoll poll epoll MAP_SHARED" }, { "answer_id": 41419353, "author": "BeeOnRope", "author_id": 149138, "author_profile": "https://Stackoverflow.com/users/149138", "pm_score": 6, "selected": false, "text": "mmap mmap mmap mmap mmap read(2) mmap mmap MAP_POPULATE mmap mmap mmap mmap read() read() malloc read mmap read() mmap MAP_POPULATE read() read() copy_to_user mmap MAP_POPULATE copy_to_user arch/x86/lib/copy_user_64.S REP MOVQ read() read() mmap read() mmap MAP_POPULATE mmap read madvise fadvise mmap MAP_POPULATE" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2353001/" ]
45,988
<p>In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using <code>System.Windows.Forms.FolderBrowserDialog</code> but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).</p> <p>I'd like something more like the <code>System.Windows.Forms.OpenFileDialog</code>, but for folders instead of files. </p> <p>What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.</p>
[ { "answer_id": 625057, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 6, "selected": true, "text": "var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();\ndlg1.Description = \"Select a folder to extract to:\";\ndlg1.ShowNewFolderButton = true;\ndlg1.ShowEditBox = true;\n//dlg1.NewStyle = false;\ndlg1.SelectedPath = txtExtractDirectory.Text;\ndlg1.ShowFullPathInEditBox = true;\ndlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;\n\n// Show the FolderBrowserDialog.\nDialogResult result = dlg1.ShowDialog();\nif (result == DialogResult.OK)\n{\n txtExtractDirectory.Text = dlg1.SelectedPath;\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367/" ]
45,991
<p>I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.</p> <p>What is the best way to convert <code>==Heading==</code> to <code>&lt;h2&gt;Heading&lt;/h2&gt;</code>, or <code>--bold--</code> to <code>&lt;b&gt;bold&lt;/b&gt;</code>? Can this be done simply with Regex, or does somebody have a simple function?</p> <p>I'm writing this in C#, but examples from other languages would probably work.</p>
[ { "answer_id": 45998, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 3, "selected": true, "text": "replace the pattern ==([^=]*)== with <h2>\\1</h2>\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/45991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
46,003
<p>How can I change default <a href="http://msdn.microsoft.com/en-us/library/3a7hkh29.aspx" rel="nofollow noreferrer">Generate Method Stub</a> behavior in Visaul Studio to generate method with body</p> <pre><code>throw new NotImplementedException(); </code></pre> <p>instead of </p> <pre><code>throw new Exception("The method or operation is not implemented."); </code></pre>
[ { "answer_id": 46016, "author": "Sam Wessel", "author_id": 4734, "author_profile": "https://Stackoverflow.com/users/4734", "pm_score": 4, "selected": true, "text": " <Declarations>\n <Literal Editable=\"true\">\n <ID>signature</ID>\n <Default>signature</Default>\n </Literal>\n <Literal>\n <ID>Exception</ID>\n <Function>SimpleTypeName(global::System.NotImplementedException)</Function>\n </Literal>\n </Declarations>\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
46,004
<p>We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data:</p> <pre><code>GET /restapi/myobject?param=object-id-maybe </code></pre> <p>...and an XML document representing some data structure is returned. Fine.</p> <p>But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back. </p> <p>But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this?</p> <p>(Additional consideration: The UI would be primarily done with AJAX)</p> <p>-- Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes?</p>
[ { "answer_id": 176639, "author": "Alexandros Marinos", "author_id": 24461, "author_profile": "https://Stackoverflow.com/users/24461", "pm_score": 4, "selected": false, "text": " Operate on a Record\n\nGET /people/1\n return the first record \nDELETE /people/1\n destroy the first record \nPOST /people/1?_method=DELETE\n alias for DELETE, to compensate for browser limitations \n\nGET /people/1/edit\n return a form to edit the first record \nPUT /people/1\n submit fields for updating the first record \nPOST /people/1?_method=PUT\n alias for PUT, to compensate for browser limitations \n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
46,029
<p>If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into?</p> <p>Specifically, I would like to avoid code similar to:</p> <pre><code>void Main() { ValidateTable1(); ValidateTable2(); ValidateTable3(); } private void ValidateTable1() { //Table1 validation code goes here } private void ValidateTable2() { //Table2 validation code goes here } private void ValidateTable3() { //Table3 validation code goes here } </code></pre> <p>Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared <code>void</code> and doesn't need to return anything. Is this a good idea or would it be better to create some sort of <code>ValidationException</code> that catches all exceptions and stores them in a <code>List&lt;ValidationException&gt;</code> before printing them all out at the end?</p> <p>I did find <a href="http://www.hickorysystems.com/sw_validation.html" rel="noreferrer">this</a>, which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past?</p> <p>For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE.</p>
[ { "answer_id": 46035, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": false, "text": "using(var validation = new ValidationScope())\n{\n ValidateTable1();\n ValidateTable2();\n ValidateTable3();\n\n if(validation.Haserrors)\n {\n MessageBox.Show(validation.ValidationSummary);\n return;\n }\n\n DoSomethingElse();\n}\n ValidationScope.Current.AddError(\"col1\", \"Col1 should not be NULL\");\n" }, { "answer_id": 72421, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 5, "selected": true, "text": "IValidateableTable validate() implement IValidateableTable IValidateableTable table1 = new GenericTable(myDataSet);\ntable1 = new NonNullNonEmptyColumnValidator(table1, \"ColumnA\");\ntable1 = new ColumnValueValidator(table1, \"ColumnB\", \"ExpectedValue\");\n table1.Validate()" }, { "answer_id": 44581032, "author": "Andres A.", "author_id": 170945, "author_profile": "https://Stackoverflow.com/users/170945", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace Example2\n{\n interface IVisitor\n {\n void Visit(Table1 table1);\n void Visit(Table2 table2);\n }\n\n interface IVisitable\n {\n void Accept(IVisitor visitor);\n }\n\n interface ILog\n {\n void Verbose(string message);\n void Debug(string messsage);\n void Info(string message);\n void Error(string message);\n void Fatal(string message);\n }\n\n class Error\n {\n public string Message { get; set; }\n }\n\n class Table1 : IVisitable\n {\n public int Id { get; set; }\n public string Data { get; set; }\n private IList<Table2> InnerElements { get; } = new List<Table2>();\n\n public void Accept(IVisitor visitor)\n {\n visitor.Visit(this);\n\n foreach(var innerElement in InnerElements)\n visitor.Visit(innerElement);\n }\n }\n\n class Table2 : IVisitable\n {\n public int Id { get; set; }\n public int Data { get; set; }\n\n public void Accept(IVisitor visitor)\n {\n visitor.Visit(this);\n }\n }\n\n class Validator : IVisitor\n {\n private readonly ILog log;\n private readonly IRuleSet<Table1> table1Rules;\n private readonly IRuleSet<Table2> table2Rules;\n\n public Validator(ILog log, IRuleSet<Table1> table1Rules, IRuleSet<Table2> table2Rules)\n {\n this.log = log;\n this.table1Rules = table1Rules;\n this.table2Rules = table2Rules;\n }\n\n public void Visit(Table1 table1)\n {\n IEnumerable<Error> errors = table1Rules.EnforceOn(table1);\n\n foreach (var error in errors)\n log.Error(error.Message);\n }\n\n public void Visit(Table2 table2)\n {\n IEnumerable<Error> errors = table2Rules.EnforceOn(table2);\n\n foreach (var error in errors)\n log.Error(error.Message);\n }\n }\n\n class RuleSets\n {\n private readonly IRuleSetFactory factory;\n\n public RuleSets(IRuleSetFactory factory)\n {\n this.factory = factory;\n }\n\n public IRuleSet<Table1> RulesForTable1 =>\n factory.For<Table1>()\n .AddRule(o => string.IsNullOrEmpty(o.Data), \"Data1 is null or empty\")\n .AddRule(o => o.Data.Length < 10, \"Data1 is too short\")\n .AddRule(o => o.Data.Length > 26, \"Data1 is too long\");\n\n public IRuleSet<Table2> RulesForTable2 =>\n factory.For<Table2>()\n .AddRule(o => o.Data < 0, \"Data2 is negative\")\n .AddRule(o => o.Data > 10, \"Data2 is too big\");\n }\n\n interface IRuleSetFactory\n {\n IRuleSet<T> For<T>();\n }\n\n interface IRuleSet<T>\n {\n IEnumerable<Error> EnforceOn(T obj);\n IRuleSet<T> AddRule(Func<T, bool> rule, string description);\n }\n\n class Program\n {\n void Run()\n {\n var log = new ConsoleLogger();\n var factory = new SimpleRules();\n var rules = new RuleSets(factory);\n var validator = new Validator(log, rules.RulesForTable1, rules.RulesForTable2);\n\n var toValidate = new List<IVisitable>();\n toValidate.Add(new Table1());\n toValidate.Add(new Table2());\n\n foreach (var validatable in toValidate)\n validatable.Accept(validator);\n }\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
46,030
<p>So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.</p> <pre><code>CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } </code></pre> <p>As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? </p> <hr> <p>@Joel, thanks for the info. Here is what I tried based on your suggestion:</p> <pre><code>msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); </code></pre> <p>The form still comes up <em>under</em> the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.</p> <p>Thnks for all the ideas so far folks.</p> <hr> <p>Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.</p>
[ { "answer_id": 46092, "author": "Dean Hill", "author_id": 3106, "author_profile": "https://Stackoverflow.com/users/3106", "pm_score": 5, "selected": true, "text": "using System.Diagnostics;\nusing System.Runtime.InteropServices;\n\n// Sets the window to be foreground\n[DllImport(\"User32\")]\nprivate static extern int SetForegroundWindow(IntPtr hwnd);\n\n// Activate or minimize a window\n[DllImportAttribute(\"User32.DLL\")]\nprivate static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\nprivate const int SW_SHOW = 5;\nprivate const int SW_MINIMIZE = 6;\nprivate const int SW_RESTORE = 9;\n\nprivate void ActivateApplication(string briefAppName)\n{\n Process[] procList = Process.GetProcessesByName(briefAppName);\n\n if (procList.Length > 0)\n {\n ShowWindow(procList[0].MainWindowHandle, SW_RESTORE);\n SetForegroundWindow(procList[0].MainWindowHandle);\n }\n}\n" }, { "answer_id": 46467, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 2, "selected": false, "text": "msgFrm.Show();\nmsgFrm.BringToFront();\nmsgFrm.Focus();\n" }, { "answer_id": 94642, "author": "Kevin Gale", "author_id": 7176, "author_profile": "https://Stackoverflow.com/users/7176", "pm_score": 4, "selected": false, "text": " if (IsIconic(hWnd))\n ShowWindowAsync(hWnd, SW_RESTORE);\n\n ShowWindowAsync(hWnd, SW_SHOW);\n\n SetForegroundWindow(hWnd);\n\n // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm\n // Converted to Delphi by Ray Lischner\n // Published in The Delphi Magazine 55, page 16\n // Converted to C# by Kevin Gale\n IntPtr foregroundWindow = GetForegroundWindow();\n IntPtr Dummy = IntPtr.Zero;\n\n uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, Dummy);\n uint thisThreadId = GetWindowThreadProcessId(hWnd, Dummy);\n\n if (AttachThreadInput(thisThreadId, foregroundThreadId, true))\n {\n BringWindowToTop(hWnd); // IE 5.5 related hack\n SetForegroundWindow(hWnd);\n AttachThreadInput(thisThreadId, foregroundThreadId, false);\n }\n\n if (GetForegroundWindow() != hWnd)\n {\n // Code by Daniel P. Stasinski\n // Converted to C# by Kevin Gale\n IntPtr Timeout = IntPtr.Zero;\n SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, Timeout, 0);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Dummy, SPIF_SENDCHANGE);\n BringWindowToTop(hWnd); // IE 5.5 related hack\n SetForegroundWindow(hWnd);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Timeout, SPIF_SENDCHANGE);\n }\n //Win32 API calls necesary to raise an unowned processs main window\n\n[DllImport(\"user32.dll\")]\n\nprivate static extern bool SetForegroundWindow(IntPtr hWnd);\n[DllImport(\"user32.dll\")]\nprivate static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);\n[DllImport(\"user32.dll\")]\nprivate static extern bool IsIconic(IntPtr hWnd);\n[DllImport(\"user32.dll\", SetLastError = true)]\nprivate static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);\n[DllImport(\"user32.dll\", SetLastError = true)]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr lpdwProcessId);\n[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n[DllImport(\"user32.dll\")]\nprivate static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);\n[DllImport(\"user32.dll\")]\nstatic extern bool BringWindowToTop(IntPtr hWnd);\n\n[DllImport(\"user32.dll\")] \nprivate static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, Int32 nMaxCount);\n[DllImport(\"user32.dll\")]\nprivate static extern int GetWindowThreadProcessId(IntPtr hWnd, ref Int32 lpdwProcessId);\n[DllImport(\"User32.dll\")]\npublic static extern IntPtr GetParent(IntPtr hWnd); \n\nprivate const int SW_HIDE = 0;\nprivate const int SW_SHOWNORMAL = 1;\nprivate const int SW_NORMAL = 1;\nprivate const int SW_SHOWMINIMIZED = 2;\nprivate const int SW_SHOWMAXIMIZED = 3;\nprivate const int SW_MAXIMIZE = 3;\nprivate const int SW_SHOWNOACTIVATE = 4;\nprivate const int SW_SHOW = 5;\nprivate const int SW_MINIMIZE = 6;\nprivate const int SW_SHOWMINNOACTIVE = 7;\nprivate const int SW_SHOWNA = 8;\nprivate const int SW_RESTORE = 9;\nprivate const int SW_SHOWDEFAULT = 10;\nprivate const int SW_MAX = 10;\n\nprivate const uint SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000;\nprivate const uint SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001;\nprivate const int SPIF_SENDCHANGE = 0x2;\n" }, { "answer_id": 438971, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 2, "selected": false, "text": "(powershell.exe)\nmkdir C:\\TEMP\\PshWindow\ncd C:\\TEMP\\PshWindow\n // file 'InfoProvider.cs' in C:\\TEMP\\PshWindow\nusing System;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace PshWindow\n{\n public sealed class InfoProvider : IDisposable\n {\n public void Dispose()\n {\n GC.SuppressFinalize(this);\n lock (this._sync)\n {\n if (!this._disposed)\n {\n this._disposed = true;\n if (null != this._worker)\n {\n if (null != this._form)\n {\n this._form.Invoke(new Action(() => this._form.Close()));\n }\n this._worker.Join();\n this._form = null;\n this._worker = null;\n }\n }\n }\n }\n\n public void ShowMessage(string msg)\n {\n lock (this._sync)\n {\n // make sure worker is up and running\n if (this._disposed) { throw new ObjectDisposedException(\"InfoProvider\"); }\n if (null == this._worker)\n {\n this._worker = new Thread(() => (this._form = new MyForm(this._sync)).ShowDialog()) { IsBackground = true };\n this._worker.Start();\n while (this._form == null || !this._form.Created)\n {\n Monitor.Wait(this._sync);\n }\n }\n\n // update the text\n this._form.Invoke(new Action(delegate\n {\n this._form.Text = msg;\n this._form.Activate();\n }));\n }\n }\n\n private bool _disposed;\n private Form _form;\n private Thread _worker;\n private readonly object _sync = new object();\n }\n}\n // file 'MyForm.cs' in C:\\TEMP\\PshWindow\nusing System;\nusing System.Drawing;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace PshWindow\n{\n internal sealed class MyForm : Form\n {\n public MyForm(object sync)\n {\n this._sync = sync;\n this.BackColor = Color.LightGreen;\n this.Width = 200;\n this.Height = 80;\n this.FormBorderStyle = FormBorderStyle.SizableToolWindow;\n }\n\n protected override void OnShown(EventArgs e)\n {\n base.OnShown(e);\n this.TopMost = true;\n\n lock (this._sync)\n {\n Monitor.PulseAll(this._sync);\n }\n }\n\n private readonly object _sync;\n }\n}\n (powershell.exe)\ncsc /out:PshWindow.dll /target:library InfoProvider.cs MyForm.cs\n (powershell.exe)\n[System.Reflection.Assembly]::LoadFile('C:\\TEMP\\PshWindow\\PshWindow.dll')\n$a = New-Object PshWindow.InfoProvider\n$a.ShowMessage('Hello, world')\n $a.ShowMessage('Stack overflow')\n $a.Dispose()\n" }, { "answer_id": 717431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "private static void StatusChecking()\n{\n IntPtr iActiveForm = IntPtr.Zero, iCurrentACtiveApp = IntPtr.Zero;\n Int32 iMyProcID = Process.GetCurrentProcess().Id, iCurrentProcID = 0;\n IntPtr iTmp = (IntPtr)1;\n\n while (bIsRunning)\n {\n try\n {\n Thread.Sleep(45);\n if (Form.ActiveForm != null)\n {\n iActiveForm = Form.ActiveForm.Handle;\n }\n iTmp = GetForegroundWindow();\n if (iTmp == IntPtr.Zero) continue;\n GetWindowThreadProcessId(iTmp, ref iCurrentProcID);\n if (iCurrentProcID == 0)\n {\n iCurrentProcID = 1;\n continue;\n }\n if (iCurrentProcID != iMyProcID)\n {\n SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, 0);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, SPIF_SENDCHANGE);\n BringWindowToTop(iActiveForm);\n SetForegroundWindow(iActiveForm);\n }\n else iActiveForm = iTmp;\n }\n catch (Exception ex)\n {\n Definitions.UnhandledExceptionHandler(ex, 103106);\n }\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
46,034
<p>My work has a financial application, written in <code>VB.NET</code> with <code>SQL</code>, that several users can be working on at the same time.</p> <p>At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.</p> <p>Obviously, I no longer want any other users to <strong>add</strong>, <strong>edit</strong>, or <strong>delete</strong> entries in that batch <strong>after</strong> the <strong>Post process</strong> has been initiated.</p> <p>I have already seen that I can lock <strong>all</strong> data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.</p> <p>Is there a way to lock just the records that I know need to be operated on from VB.NET code?</p>
[ { "answer_id": 46054, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "with (rowlock)\n" }, { "answer_id": 46089, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 2, "selected": false, "text": "SELECT address1 , city, country\nFROM location\nFOR UPDATE;\n" }, { "answer_id": 52304, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "begin tran\nselect * from\nSomeTable (holdlock,updlock)\nwhere ....\n\n\nprocessing here\n\ncommit\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,074
<p>I have a php server that is running my domain name. For testing purposes I am running an asp.net on a dotted quad IP. I am hoping to link them together via either PHP or some kind of DNS/<code>.htaccess</code> voodoo.</p> <p>So if I go to <code>www.mydomain.com/test</code> it redirects (but keeps the url of (<code>www.mydomain.com/test</code>) in the browser's address bar and the pages are served by the dotted quad IP asp.net box.</p>
[ { "answer_id": 46143, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 4, "selected": true, "text": "www.yourdomain.com/test test.yourdomain.com yourdomain.com test.yourdomain.com" }, { "answer_id": 46162, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "www.mydomain.com/test target=_top href www.mydomain.com /test" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3135/" ]
46,079
<p>Details:</p> <ul> <li>Only disable after user clicks the submit button, but before the posting back to the server</li> <li>ASP.NET Webforms (.NET 1.1)</li> <li>Prefer jQuery (if any library at all)</li> <li>Must be enabled if form reloads (i.e. credit card failed)</li> </ul> <p>This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)</p>
[ { "answer_id": 46082, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 1, "selected": false, "text": "$('#SubmitButtonID').click(function() { this.disabled = true; });\n" }, { "answer_id": 46138, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 5, "selected": true, "text": "$('input[type=submit]').click(function() { this.disabled = true; });\n $('form').submit(function() {\n $('input[type=submit]', this).attr(\"disabled\",\"disabled\");\n});\n" }, { "answer_id": 46139, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 0, "selected": false, "text": "OnSubmit=\"return false\"" }, { "answer_id": 46148, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"include/js/prototype.js\"></script>\n\n <script type=\"text/javascript\">\n function handleSubmit()\n {\n $('submit').hide();\n $('progressWheel').show();\n return true;\n }\n </script>\n </head>\n <body>\n <img src=\"include/images/progress-wheel_lg.gif\" id=\"progressWheel\" style=\"display:none;\"/>\n <input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" onclick=\"handleSubmit();\"/>\n </body>\n</html>\n" }, { "answer_id": 249428, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 0, "selected": false, "text": "function disableSubmit() {\n document.getElementById('btnContinue3').onclick = function() { \n alert('Please only click once on the submit button!'); return false;\n };\n}\n" }, { "answer_id": 249530, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "$('form').submit(function() {\n $(this)\n .find(\":submit,:image\") // get all the submit buttons\n .attr({ disabled : 'disabled' }) // disable them\n .end() // go back to this form\n .submit(function() { // change the onsubmit to always reject.\n return false;\n })\n ;\n});\n form.submit() <input type=\"submit\"/> <button type=\"submit\"></button> <input type=\"image\" />" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446/" ]
46,080
<p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p> <p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p>
[ { "answer_id": 46083, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 8, "selected": true, "text": "svn move SOURCE DESTINATION\n" }, { "answer_id": 25660319, "author": "BornToCode", "author_id": 1057791, "author_profile": "https://Stackoverflow.com/users/1057791", "pm_score": 3, "selected": false, "text": "TortoiseSVN -> Paste" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
46,096
<p>I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"?</p> <pre><code>var selectVar = arrayVar.Select( (a,i) =&gt; new { Line = a }); var selectVar = from s in arrayVar select new { Line = s }; </code></pre>
[ { "answer_id": 46108, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "(a) => new { blah = b}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
46,124
<p>I've seen people doing things like this in their HTML:</p> <pre><code>&lt;!--[if IE]&gt; &lt;link rel="stylesheet" href="ie.css" type="text/css" /&gt; &lt;![endif]--&gt; </code></pre> <p>Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?</p> <p><strong>Edit</strong></p> <p>Thanks <a href="https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126">Ross</a>. Interesting to find out about <strong>gt, lt, gte, &amp; lte</strong>.</p>
[ { "answer_id": 46126, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<!--IGNORED COMMENT--> <!--[if IE 8]>\n<link rel=\"stylesheet type=\"text/css\" href=\"ie8.css\" />\n<![endif]-->\n" }, { "answer_id": 46244, "author": "sock", "author_id": 4028, "author_profile": "https://Stackoverflow.com/users/4028", "pm_score": 2, "selected": false, "text": "navigator.appName\nnavigator.appVersion \n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
46,125
<p>I want to do this: </p> <blockquote> <p>//*fu</p> </blockquote> <p>which returns all nodes whose name ends in <strong>fu</strong>, such as <code>&lt;tarfu /&gt;</code> and <code>&lt;snafu /&gt;</code>, but not <code>&lt;fubar /&gt;</code></p>
[ { "answer_id": 46141, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "//*[ends-with(name(), 'fu')]\n" }, { "answer_id": 288865, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 6, "selected": false, "text": "//*[substring(name(),string-length(name())-1) = 'fu']\n" }, { "answer_id": 44435539, "author": "Identity1", "author_id": 3741717, "author_profile": "https://Stackoverflow.com/users/3741717", "pm_score": 2, "selected": false, "text": "//*[substring(name(), string-length(name()) - string-length('fu') +1) = 'fu'] //*[substring(name(), string-length(name()) - string-length('Position') +1) = 'Position']" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,130
<p>I have a list of <code>Foo</code>. Foo has properties <code>Bar</code> and <code>Lum</code>. Some <code>Foo</code>s have identical values for <code>Bar</code>. How can I use lambda/linq to group my <code>Foo</code>s by <code>Bar</code> so I can iterate over each grouping's <code>Lum</code>s?</p>
[ { "answer_id": 46142, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "var q = from x in list\n group x by x.Bar into g\n select g;\n\nforeach (var group in q)\n{\n Console.WriteLine(\"Group \" + group.Key);\n foreach (var item in group)\n {\n Console.WriteLine(item.Bar);\n }\n}\n" }, { "answer_id": 47308, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": true, "text": "var foos = new List<Foo> {\n new Foo{Bar = 1,Lum = 1},\n new Foo{Bar = 1,Lum = 2},\n new Foo{Bar = 2,Lum = 3},\n};\n\n// Using language integrated queries:\n\nvar q = from foo in foos\n group foo by foo.Bar into groupedFoos\n let lums = from fooGroup in groupedFoos\n select fooGroup.Lum\n select new { Bar = groupedFoos.Key, Lums = lums };\n\n// Using lambdas\n\nvar q = foos.GroupBy(x => x.Bar).\n Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});\n\n\nforeach (var group in q)\n{\n Console.WriteLine(\"Lums for Bar#\" + group.Bar);\n foreach (var lum in group.Lums)\n {\n Console.WriteLine(lum);\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
46,136
<p>I have a large codebase that targetted Flash 7, with a <em>lot</em> of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.</p> <p>The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.</p> <p>Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project?</p>
[ { "answer_id": 46184, "author": "lilserf", "author_id": 4545, "author_profile": "https://Stackoverflow.com/users/4545", "pm_score": 4, "selected": true, "text": "class your.package.YourClass\n{\n}\n package your.package\n{\n class YourClass\n {\n }\n}\n" }, { "answer_id": 50840, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 1, "selected": false, "text": "eval()" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
46,146
<p>Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.</p>
[ { "answer_id": 46168, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 4, "selected": false, "text": "public static final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_HEX4DECCOMPRESSED_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_6HEX4DEC_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_HEXCOMPRESSED_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\\\z\";\npublic static final String IPV6_REGEX = \"\\\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\\\z\";\n" }, { "answer_id": 46171, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n \"\\\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\b\"\n" }, { "answer_id": 1573032, "author": "Aeron", "author_id": 190680, "author_profile": "https://Stackoverflow.com/users/190680", "pm_score": 0, "selected": false, "text": "25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d" }, { "answer_id": 42605542, "author": "Sean F", "author_id": 6801443, "author_profile": "https://Stackoverflow.com/users/6801443", "pm_score": 0, "selected": false, "text": "try {\n IPAddressString str = new IPAddressString(\"::1\");\n IPAddress addr = str.toAddress();\n} catch(AddressStringException e) {\n //e.getMessage has validation error\n}\n" }, { "answer_id": 60502882, "author": "Bodhiswatta Mukherjee", "author_id": 12998124, "author_profile": "https://Stackoverflow.com/users/12998124", "pm_score": 1, "selected": false, "text": "package com.capgemini.basics;\n\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\npublic class Main {\n private static Pattern VALID_IPV4_PATTERN = null;\n private static Pattern VALID_IPV6_PATTERN1 = null;\n private static Pattern VALID_IPV6_PATTERN2 = null;\n private static final String ipv4Pattern = \"(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\";\n private static final String ipv6Pattern1 = \"([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}\";\n private static final String ipv6Pattern2 = \"^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$\";\n\n\n static {\n try {\n VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);\n VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);\n VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);\n } catch (PatternSyntaxException e) {\n System.out.println(\"Neither\");\n }\n }\n\n public static List<String> validateAddresses(List<String> ipAddress) {\n final List<String> validity= new ArrayList<String>();\n int len = ipAddress.size();\n for(int i=0; i<len; i++){\n Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));\n Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));\n Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));\n if (m1.matches()) {\n validity.add(\"IPv4\");\n }\n else if(m12.matches() || m22.matches()){\n validity.add(\"IPv6\");\n }\n else{\n validity.add(\"Neither\");\n }\n }\n return validity;\n\n }\n\n public static void main(String[] args)\n {\n final List<String> IPAddress = new ArrayList<String>();\n //Test Case 0\n /*IPAddress.add(\"121.18.19.20\");\n IPAddress.add(\"0.12.12.34\");\n IPAddress.add(\"121.234.12.12\");\n IPAddress.add(\"23.45.12.56\");\n IPAddress.add(\"0.1.2.3\");*/\n\n //Test Case 1\n /*IPAddress.add(\"2001:0db8:0000:0000:0000:ff00:0042:8329\");\n IPAddress.add(\"2001:0db8:0:0:0:ff00:42:8329\");\n IPAddress.add(\"::1\");\n IPAddress.add(\"2001:0db8::ff00:42:8329\");\n IPAddress.add(\"0000:0000:0000:0000:0000:0000:0000:0001\");*/\n\n //Test Case 2\n /*IPAddress.add(\"000.012.234.23\");\n IPAddress.add(\"666.666.23.23\");\n IPAddress.add(\".213.123.23.32\");\n IPAddress.add(\"23.45.22.32.\");\n IPAddress.add(\"272:2624:235e:3bc2:c46d:682:5d46:638g\");\n IPAddress.add(\"1:22:333:4444\");*/\n\n final List<String> result = validateAddresses(IPAddress);\n\n for (int i=0; i<result.size(); i++)\n System.out.println(result.get(i)+\" \");\n\n }\n\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
46,147
<p>Have just started using <code>Google Chrome</code>, and noticed in parts of our site, e.g. all the links on the page, are bright red. They should be black with a dotted underline.</p> <p>Is there some gotcha in <code>WebKit</code> rendering that turns all links red regardless of the style?</p>
[ { "answer_id": 46151, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": ":visited" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
46,155
<p>I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?</p>
[ { "answer_id": 46170, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 7, "selected": false, "text": "emailAddress.match( / some_regex /);\n ^((?>[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+\\x20*|\"((?=[\\x01-\\x7f])[^\"\\\\]|\\\\[\\x01-\\x7f])*\n\"\\x20*)*(?<angle><))?((?!\\.)(?>\\.?[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+)+|\"((?=[\\x01-\\x\n7f])[^\"\\\\]|\\\\[\\x01-\\x7f])*\")@(((?!-)[a-zA-Z\\d\\-]+(?<!-)\\.)+[a-zA-Z]{2,}|\\[(((?(?<\n!\\[)\\.)(25[0-5]|2[0-4]\\d|[01]?\\d?\\d)){4}|[a-zA-Z\\d\\-]*[a-zA-Z\\d]:((?=[\\x01-\\x7f])\n[^\\\\\\[\\]]|\\\\[\\x01-\\x7f])+)\\])(?(angle)>)$\n" }, { "answer_id": 46181, "author": "John Rutherford", "author_id": 3880, "author_profile": "https://Stackoverflow.com/users/3880", "pm_score": 14, "selected": true, "text": "const validateEmail = (email) => {\n return String(email)\n .toLowerCase()\n .match(\n /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n );\n};\n const re =\n /^(([^<>()[\\]\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^<>()[\\]\\.,;:\\s@\\\"]+\\.)+[^<>()[\\]\\.,;:\\s@\\\"]{2,})$/i;\n const validateEmail = (email) => {\n return email.match(\n /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n );\n};\n\nconst validate = () => {\n const $result = $('#result');\n const email = $('#email').val();\n $result.text('');\n\n if (validateEmail(email)) {\n $result.text(email + ' is valid :)');\n $result.css('color', 'green');\n } else {\n $result.text(email + ' is not valid :(');\n $result.css('color', 'red');\n }\n return false;\n}\n\n$('#email').on('input', validate); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<label for=\"email\">Enter an email address: </label>\n<input id=\"email\" />\n<h2 id=\"result\"></h2>" }, { "answer_id": 48800, "author": "Jaymon", "author_id": 5006, "author_profile": "https://Stackoverflow.com/users/5006", "pm_score": 9, "selected": false, "text": "^\\S+@\\S+$\n /^\\S+@\\S+\\.\\S+$/\n" }, { "answer_id": 815235, "author": "Adam McKee", "author_id": 98601, "author_profile": "https://Stackoverflow.com/users/98601", "pm_score": 6, "selected": false, "text": "email = $('email');\nfilter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\nif (filter.test(email.value)) {\n // Yay! valid\n return true;\n}\nelse\n {return false;}\n" }, { "answer_id": 815242, "author": "jacobangel", "author_id": 31318, "author_profile": "https://Stackoverflow.com/users/31318", "pm_score": 5, "selected": false, "text": "RegExp regexp if (reg.test(/@/))\n @ @" }, { "answer_id": 1373724, "author": "Esteban Küber", "author_id": 34813, "author_profile": "https://Stackoverflow.com/users/34813", "pm_score": 10, "selected": false, "text": "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\]) [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? [email protected] [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\\b" }, { "answer_id": 2932827, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "/^[-a-z0-9~!$%^&*_=+}{\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?$/i\n" }, { "answer_id": 3838001, "author": "Félix Saparelli", "author_id": 231788, "author_profile": "https://Stackoverflow.com/users/231788", "pm_score": 4, "selected": false, "text": "/^([\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+\\.)*[\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+@((((([a-z0-9]{1}[a-z0-9\\-]{0,62}[a-z0-9]{1})|[a-z])\\.)+[a-z]{2,6})|(\\d{1,3}\\.){3}\\d{1,3}(\\:\\d{1,5})?)$/i\n" }, { "answer_id": 5166806, "author": "Miloš Rašić", "author_id": 590569, "author_profile": "https://Stackoverflow.com/users/590569", "pm_score": 6, "selected": false, "text": "function looksLikeMail(str) {\n var lastAtPos = str.lastIndexOf('@');\n var lastDotPos = str.lastIndexOf('.');\n return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);\n}\n lastAtPos < lastDotPos @ . @ lastAtPos > 0 @ str.indexOf('@@') == -1 @@ @ \" @ @ lastDotPos > 2 [email protected] (str.length - lastDotPos) > 2" }, { "answer_id": 7791100, "author": "Anoop", "author_id": 460942, "author_profile": "https://Stackoverflow.com/users/460942", "pm_score": 8, "selected": false, "text": "<form>\n <label>Email Address\n <input type=\"email\" placeholder=\"[email protected]\" required>\n </label>\n <input type=\"submit\">\n</form>\n email email = 1*( atext / \".\" ) \"@\" label *( \".\" label )\nlabel = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5\natext = < as defined in RFC 5322 section 3.2.3 >\nlet-dig = < as defined in RFC 1034 section 3.5 >\nldh-str = < as defined in RFC 1034 section 3.5 >\n /^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n" }, { "answer_id": 8565823, "author": "Zo72", "author_id": 246394, "author_profile": "https://Stackoverflow.com/users/246394", "pm_score": 5, "selected": false, "text": "function isPossiblyValidEmail(txt) {\n return txt.length > 5 && txt.indexOf('@')>0;\n}\n" }, { "answer_id": 9204568, "author": "C. Lee", "author_id": 270821, "author_profile": "https://Stackoverflow.com/users/270821", "pm_score": 10, "selected": false, "text": "[email protected]\n /^\\S+@\\S+\\.\\S+$/\n /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n ^ $ trim() function validateEmail(email) {\n var re = /\\S+@\\S+\\.\\S+/;\n return re.test(email);\n}\n \nconsole.log(validateEmail('my email is [email protected]')); // true\n \nconsole.log(validateEmail('my email is anystring@anystring .any')); // false" }, { "answer_id": 10906478, "author": "Steve C", "author_id": 587543, "author_profile": "https://Stackoverflow.com/users/587543", "pm_score": 4, "selected": false, "text": "function isEmail(email) { \n return /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i.test(email);\n} \n if (isEmail('[email protected]')){ console.log('This is email is valid'); }\n" }, { "answer_id": 12199843, "author": "Darren Cato", "author_id": 111291, "author_profile": "https://Stackoverflow.com/users/111291", "pm_score": 3, "selected": false, "text": "function validateEmail(email){ \n var re = /^(([^<>()[]\\\\.,;:\\s@\\\"]+(\\.[^<>()[]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([[0-9]{1,3}\\‌​.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; \n return re.test(email); \n}\n" }, { "answer_id": 13178771, "author": "Ryan Taylor", "author_id": 845413, "author_profile": "https://Stackoverflow.com/users/845413", "pm_score": 6, "selected": false, "text": "^([a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$\n [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\n i var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;\nconsole.log( emailCheck.test('[email protected]') );\n @ @ \"...\"" }, { "answer_id": 13975255, "author": "Boldewyn", "author_id": 113195, "author_profile": "https://Stackoverflow.com/users/113195", "pm_score": 7, "selected": false, "text": "function validateEmail(value) {\n var input = document.createElement('input');\n\n input.type = 'email';\n input.required = true;\n input.value = value;\n\n return typeof input.checkValidity === 'function' ? input.checkValidity() : /\\S+@\\S+\\.\\S+/.test(value);\n}\n" }, { "answer_id": 14622590, "author": "Tugrul", "author_id": 1172945, "author_profile": "https://Stackoverflow.com/users/1172945", "pm_score": 4, "selected": false, "text": "var testresults\n\nfunction checkemail() {\n var str = document.validation.emailcheck.value\n var filter = /^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/i\n if (filter.test(str))\n testresults = true\n else {\n alert(\"Please input a valid email address!\")\n testresults = false\n }\n return (testresults)\n}\n\nfunction checkbae() {\n if (document.layers || document.getElementById || document.all)\n return checkemail()\n else\n return true\n} <form name=\"validation\" onSubmit=\"return checkbae()\">\n Please input a valid email address:<br />\n\n <input type=\"text\" size=18 name=\"emailcheck\">\n <input type=\"submit\" value=\"Submit\">\n</form>" }, { "answer_id": 16014483, "author": "Linkmichiel", "author_id": 738331, "author_profile": "https://Stackoverflow.com/users/738331", "pm_score": 4, "selected": false, "text": "function check_email(val){\n if(!val.match(/\\S+@\\S+\\.\\S+/)){ // Jaymon's / Squirtle's solution\n // Do something\n return false;\n }\n if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){\n // Do something\n return false;\n }\n return true;\n}\n\ncheck_email('check@thiscom'); // Returns false\ncheck_email('[email protected]'); // Returns false\ncheck_email(' [email protected]'); // Returns false\ncheck_email('[email protected]'); // Returns true\n" }, { "answer_id": 16016476, "author": "Bob van Luijt", "author_id": 1501285, "author_profile": "https://Stackoverflow.com/users/1501285", "pm_score": 6, "selected": false, "text": "function checkEmail(emailAddress) {\n var sQtext = '[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]';\n var sDtext = '[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]';\n var sAtom = '[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40\\\\x5b-\\\\x5d\\\\x7f-\\\\xff]+';\n var sQuotedPair = '\\\\x5c[\\\\x00-\\\\x7f]';\n var sDomainLiteral = '\\\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\\\x5d';\n var sQuotedString = '\\\\x22(' + sQtext + '|' + sQuotedPair + ')*\\\\x22';\n var sDomain_ref = sAtom;\n var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';\n var sWord = '(' + sAtom + '|' + sQuotedString + ')';\n var sDomain = sSubDomain + '(\\\\x2e' + sSubDomain + ')*';\n var sLocalPart = sWord + '(\\\\x2e' + sWord + ')*';\n var sAddrSpec = sLocalPart + '\\\\x40' + sDomain; // complete RFC822 email address spec\n var sValidEmail = '^' + sAddrSpec + '$'; // as whole string\n\n var reValidEmail = new RegExp(sValidEmail);\n\n return reValidEmail.test(emailAddress);\n}\n" }, { "answer_id": 17290569, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<input type=\"email\"/>\n" }, { "answer_id": 17642237, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 6, "selected": false, "text": "email.includes('@')\n email.indexOf('@') > 0\n" }, { "answer_id": 18719180, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 2, "selected": false, "text": "goog.format.EmailAddress goog.format.EmailAddress.isValidAddrSpec(\"[email protected]\")\n // This is a fairly naive implementation, but it covers 99% of use cases.\n// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax\n// TODO(mariakhomenko): we should also be handling i18n domain names as per\n// http://en.wikipedia.org/wiki/Internationalized_domain_name\n" }, { "answer_id": 18731676, "author": "pera", "author_id": 79497, "author_profile": "https://Stackoverflow.com/users/79497", "pm_score": 4, "selected": false, "text": "/^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$/\n" }, { "answer_id": 20285787, "author": "Orchid", "author_id": 2845463, "author_profile": "https://Stackoverflow.com/users/2845463", "pm_score": 4, "selected": false, "text": "var emailID = document.forms[\"formName\"][\"form element id\"].value;\natpos = emailID.indexOf(\"@\");\ndotpos = emailID.lastIndexOf(\".\");\nif (atpos < 1 || ( dotpos - atpos < 2 ))\n{\n alert(\"Please enter correct email ID\")\n return false;\n}\n eMailId: {\n required: true,\n email: true\n}\n" }, { "answer_id": 20373180, "author": "Neil Thompson", "author_id": 932833, "author_profile": "https://Stackoverflow.com/users/932833", "pm_score": 3, "selected": false, "text": "/^[\\w-]+(\\.[\\w-]+)*@([a-z0-9-]+(\\.[a-z0-9-]+)*?\\.[a-z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?$/\n" }, { "answer_id": 21397719, "author": "Ferrakkem Bhuiyan", "author_id": 3231139, "author_profile": "https://Stackoverflow.com/users/3231139", "pm_score": 2, "selected": false, "text": "<pre>\n**The personal_info part contains the following ASCII characters.\n1.Uppercase (A-Z) and lowercase (a-z) English letters.\n2.Digits (0-9).\n3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~\n4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**\n</pre>\n*Example of valid email id*\n<pre>\[email protected]\[email protected]\[email protected]\[email protected]\[email protected]\n</pre>\n<pre>\nxxxx.ourearth.com [@ is not present] \[email protected] [ tld (Top Level domain) can not start with dot \".\" ]\[email protected] [ No character before @ ]\[email protected] [ \".b\" is not a valid tld ]\[email protected] [ tld can not start with dot \".\" ]\[email protected] [ an email should not be start with \".\" ]\nxxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]\[email protected] [double dots are not allowed\n</pre>\n**javascript mail code**\n\n function ValidateEmail(inputText)\n {\n var mailformat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if(inputText.value.match(mailformat))\n {\n document.form1.text1.focus();\n return true;\n }\n else\n {\n alert(\"You have entered an invalid email address!\");\n document.form1.text1.focus();\n return false;\n }\n }\n" }, { "answer_id": 24704328, "author": "Yogesh Jindal", "author_id": 197586, "author_profile": "https://Stackoverflow.com/users/197586", "pm_score": 0, "selected": false, "text": "function isValidEmailAddress (email) {\n var validEmail = false;\n if (email) {\n email = email.trim().toLowerCase();\n var pattern = /^[\\w-']+(\\.[\\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*?\\.[a-zA-Z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?$/;\n validEmail = pattern.exec(email);\n }\n\n return validEmail;\n}\n\nif (typeof String.prototype.trim !== 'function') {\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n };\n}\n" }, { "answer_id": 25125279, "author": "zeros-and-ones", "author_id": 2094495, "author_profile": "https://Stackoverflow.com/users/2094495", "pm_score": 3, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>Our Company</title>\n <style>\n .form-style {\n color: #ccc;\n }\n </style>\n</head>\n<body>\n <h1>Email Validation Form Example</h1>\n <input type=\"text\" name=\"email\" id=\"emailInput\" class=\"form-style\">\n <script>\n function validateEmail(emailAddress) {\n var regularExpression = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))){2,6}$/i;\n return regularExpression.test(emailAddress);\n }\n\n function showEmailValidationState(event) {\n if (validateEmail(event.target.value)) {\n document.getElementById(\"emailInput\").style.color = 'black';\n }\n }\n document.getElementById(\"emailInput\").addEventListener(\"keyup\", showEmailValidationState);\n </script>\n</body>\n</html>\n" }, { "answer_id": 27476145, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 1, "selected": false, "text": "type=\"email\" var isEmail = $compile('<input ng-model=\"m\" type=\"email\">')($rootScope.$new()).\n controller('ngModel').$validators[\"email\"];\n\nif (isEmail('[email protected]')) {\n console.log('valid');\n} \n" }, { "answer_id": 28579110, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "function doesEmailExist(email) {\n var emailExistence = require('email-existence');\n return emailExistence.check(email,function (err,status) {\n if (status) {\n return status;\n }\n else {\n throw new Error('Email does not exist');\n }\n });\n}\n" }, { "answer_id": 28804496, "author": "Code Spy", "author_id": 1045296, "author_profile": "https://Stackoverflow.com/users/1045296", "pm_score": 2, "selected": false, "text": "function validateEmail(email) {\nvar chrbeforAt = email.substr(0, email.indexOf('@'));\nif (!($.trim(email).length > 127)) {\n if (chrbeforAt.length >= 2) {\n var re = /^(([^<>()[\\]{}'^?\\\\.,!|//#%*-+=&;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n //var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n return re.test(email);\n } else {\n return false;\n }\n} else {\n return false;\n}\n}\n" }, { "answer_id": 28804516, "author": "Code Spy", "author_id": 1045296, "author_profile": "https://Stackoverflow.com/users/1045296", "pm_score": 2, "selected": false, "text": "function validateEmail(email) {\n var chrbeforAt = email.substr(0, email.indexOf('@'));\n if (!($.trim(email).length > 127)) {\n if (chrbeforAt.length >= 2) {\n var re = /^(([^<>()[\\]{}'^?\\\\.,!|//#%*-+=&;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n return re.test(email);\n } else {\n return false;\n }\n } else {\n return false;\n }\n}\n" }, { "answer_id": 31311899, "author": "jaydev thakkar", "author_id": 5003158, "author_profile": "https://Stackoverflow.com/users/5003158", "pm_score": 0, "selected": false, "text": "\\b[a-z][\\w\\d_\\.]+@\\w+\\.[a-z]{2}[a-z]?\\.?[a-z]{,2}\\s\n [email protected] \[email protected] \[email protected] \[email protected]\n" }, { "answer_id": 31971270, "author": "DestyNova", "author_id": 1528682, "author_profile": "https://Stackoverflow.com/users/1528682", "pm_score": 2, "selected": false, "text": "function isMail(mail)\n{\n pattuser = /^([A-Z0-9_%+\\-!#$&'*\\/=?^`{|}~]+\\.?)*[A-Z0-9_%+\\-!#$&'*\\/=?^`{|}~]+$/i;\n pattdomain = /^([A-Z0-9-]+\\.?)*[A-Z0-9-]+(\\.[A-Z]{2,9})+$/i;\n\n tab = mail.split(\"@\");\n if (tab.length != 2)\n return false;\n return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));\n}\n" }, { "answer_id": 32206684, "author": "Dinesh Devkota", "author_id": 2008447, "author_profile": "https://Stackoverflow.com/users/2008447", "pm_score": 1, "selected": false, "text": " <input id=\"date\" type=\"text\" placeholder=\"YYYY-MM-DD\"/>\n $(\"#date\").mask(\"9999-99-99\",{placeholder:\"YYYY-MM-DD\"});\n" }, { "answer_id": 32420732, "author": "cyberrspiritt", "author_id": 2303664, "author_profile": "https://Stackoverflow.com/users/2303664", "pm_score": 3, "selected": false, "text": "<input type=\"email\" name=\"email\">\n ^[a-zA-Z0-9_\\-.]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-.]+$\n" }, { "answer_id": 32686261, "author": "Andrew", "author_id": 1200649, "author_profile": "https://Stackoverflow.com/users/1200649", "pm_score": 8, "selected": false, "text": "/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n" }, { "answer_id": 37540637, "author": "Priya", "author_id": 4424022, "author_profile": "https://Stackoverflow.com/users/4424022", "pm_score": 2, "selected": false, "text": " /^[a-z][a-zA-Z0-9_.]*(\\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\\.[a-z]+(\\.[a-z]+)?$/\n function validateEmail(email) {\n var re = /^[a-z][a-zA-Z0-9_.]*(\\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\\.[a-z]+(\\.[a-z]+)?$/;\n return re.test(email);\n}\n" }, { "answer_id": 38137215, "author": "CVE-RICK", "author_id": 2381320, "author_profile": "https://Stackoverflow.com/users/2381320", "pm_score": 6, "selected": false, "text": "/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/ /^(([^<>()\\[\\]\\.,;:\\s@\\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^<>()\\.,;\\s@\\\"]+\\.{0,1})+[^<>()\\.,;:\\s@\\\"]{2,})$/" }, { "answer_id": 38544440, "author": "Kentonbmax", "author_id": 5414462, "author_profile": "https://Stackoverflow.com/users/5414462", "pm_score": 2, "selected": false, "text": "vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';\n" }, { "answer_id": 40474862, "author": "chemic", "author_id": 2903210, "author_profile": "https://Stackoverflow.com/users/2903210", "pm_score": 2, "selected": false, "text": "validateEmail(email) {\n let sQtext = '[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]';\n let sDtext = '[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]';\n let sAtom = '[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40\\\\x5b-\\\\x5d\\\\x7f-\\\\xff]+';\n let sQuotedPair = '\\\\x5c[\\\\x00-\\\\x7f]';\n let sDomainLiteral = `\\\\x5b(${sDtext}|${sQuotedPair})*\\\\x5d`;\n let sQuotedString = `\\\\x22(${sQtext}|${sQuotedPair})*\\\\x22`;\n let sDomainRef = sAtom;\n let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`;\n let sWord = `(${sAtom}|${sQuotedString})`;\n let sDomain = `${sSubDomain}(\\\\x2e${sSubDomain})*`;\n let sLocalPart = `${sWord}(\\\\x2e${sWord})*`;\n let sAddrSpec = `${sLocalPart}\\\\x40${sDomain}`; // complete RFC822 email address spec\n let sValidEmail = `^${sAddrSpec}$`; // as whole string\n\n let reValidEmail = new RegExp(sValidEmail);\n\n return reValidEmail.test(email);\n}\n" }, { "answer_id": 41278091, "author": "Prabhat Kasera", "author_id": 1167772, "author_profile": "https://Stackoverflow.com/users/1167772", "pm_score": 4, "selected": false, "text": "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+\n" }, { "answer_id": 41354731, "author": "bman", "author_id": 177006, "author_profile": "https://Stackoverflow.com/users/177006", "pm_score": 4, "selected": false, "text": "[email protected] ccc" }, { "answer_id": 41437076, "author": "Negin", "author_id": 5611484, "author_profile": "https://Stackoverflow.com/users/5611484", "pm_score": 4, "selected": false, "text": "[email protected] [email protected] [email protected] [email protected] [email protected] email@[192.0.2.123] “email”@example.com [email protected] [email protected] [email protected] [email protected] .name [email protected] co.jp [email protected] Regex = /(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/\n" }, { "answer_id": 42197579, "author": "Himanshu Teotia", "author_id": 5031009, "author_profile": "https://Stackoverflow.com/users/5031009", "pm_score": 2, "selected": false, "text": "var validator = require('validator');\n\nvalidator.isEmail('[email protected]'); //=> true \n" }, { "answer_id": 42871920, "author": "Jangli Coder", "author_id": 4247829, "author_profile": "https://Stackoverflow.com/users/4247829", "pm_score": 0, "selected": false, "text": "var pattern = /^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$/; \n" }, { "answer_id": 43245721, "author": "Abhay Shiro", "author_id": 6775407, "author_profile": "https://Stackoverflow.com/users/6775407", "pm_score": 2, "selected": false, "text": "[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}\n" }, { "answer_id": 44323593, "author": "takatan", "author_id": 4228476, "author_profile": "https://Stackoverflow.com/users/4228476", "pm_score": 1, "selected": false, "text": "true Ё console.log (/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test ('Ё@example.org')) /^(([^\\u0080-\\uffff<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^\\u0080-\\uffff<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/" }, { "answer_id": 44601723, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": ".co.uk .com.au var isEmail = function(str) {\n return typeof str==='string' && /^[\\w+\\d+._]+\\@[\\w+\\d+_+]+\\.[\\w+\\d+._]{2,8}$/.test(str);\n}\n isEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]#sswzazaaaa'); //false\nisEmail('[email protected]'); //false\n" }, { "answer_id": 44671643, "author": "Liberateur", "author_id": 3933634, "author_profile": "https://Stackoverflow.com/users/3933634", "pm_score": 5, "selected": false, "text": "function validMail(mail)\n{\n return /^(([^<>()\\[\\]\\.,;:\\s@\\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^<>()\\.,;\\s@\\\"]+\\.{0,1})+([^<>()\\.,;:\\s@\\\"]{2,}|[\\d\\.]+))$/.test(mail);\n}\n validMail('[email protected]') // Return true\nvalidMail('[email protected].') // Return true\nvalidMail('[email protected]') // Return true\nvalidMail('user@localserver') // Return true\nvalidMail('[email protected]') // Return true\nvalidMail('user+mailbox/[email protected]') // Return true\nvalidMail('\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com') // Return true\nvalidMail('!#$%&\\'*+-/=?^_`.{|}[email protected]') // Return true\nvalidMail('\"()<>[]:,;@\\\\\\\"!#$%&\\'-/=?^_`{}| ~.a\"@example.org') // Return true\nvalidMail('\"Abc@def\"@example.com') // Return true\nvalidMail('\"Fred Bloggs\"@example.com') // Return true\nvalidMail('\"Joe.\\\\Blow\"@example.com') // Return true\nvalidMail('Loïc.Accentué@voilà.fr') // Return true\nvalidMail('\" \"@example.org') // Return true\nvalidMail('user@[IPv6:2001:DB8::1]') // Return true\n validMail('Abc.example.com') // Return false\nvalidMail('A@b@[email protected]') // Return false\nvalidMail('a\"b(c)d,e:f;g<h>i[j\\k][email protected]') // Return false\nvalidMail('just\"not\"[email protected]') // Return false\nvalidMail('this is\"not\\[email protected]') // Return false\nvalidMail('this\\ still\\\"not\\\\[email protected]') // Return false\nvalidMail('[email protected]') // Return false\nvalidMail('[email protected]') // Return false\n" }, { "answer_id": 44996725, "author": "Behnam", "author_id": 3243488, "author_profile": "https://Stackoverflow.com/users/3243488", "pm_score": 2, "selected": false, "text": "const validateEmail=(email)=> /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(email);\n" }, { "answer_id": 45250371, "author": "hmharsh3", "author_id": 3386952, "author_profile": "https://Stackoverflow.com/users/3386952", "pm_score": 2, "selected": false, "text": "var string = \"[email protected]\"\nvar exp = /(\\w(=?@)\\w+\\.{1}[a-zA-Z]{2,})/i\nalert(exp.test(string))\n" }, { "answer_id": 48651640, "author": "Juan Pablo", "author_id": 4187847, "author_profile": "https://Stackoverflow.com/users/4187847", "pm_score": 5, "selected": false, "text": "let val = '[email protected]';\nif(/^[a-z0-9][a-z0-9-_\\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\\.[a-z0-9]{2,10}(?:\\.[a-z]{2,10})?$/.test(val)) {\n console.log('passed');\n}\n //\nexport const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\\.[a-z0-9]{2,10}(?:\\.[a-z]{2,10})?$/.test(val);\n" }, { "answer_id": 49005817, "author": "Mizanur Rahaman", "author_id": 8522458, "author_profile": "https://Stackoverflow.com/users/8522458", "pm_score": 1, "selected": false, "text": " <input type=\"email\" class=\"form-control\" required=\"required\" placeholder=\"Email Address\" name=\"Email\" id=\"Email\" autocomplete=\"Email\">\n <button class=\"btn-1 shadow-0 full-width\" type=\"button\" id=\"register\">Register account</button>\n $(\"#register\").click(function(){ \n var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n var Email = $(\"#Email\").val();\n var x = rea.test(Email);\n if (!x) {\n alert('Type Your valid Email');\n return false;\n } \n </script>\n" }, { "answer_id": 49020064, "author": "Menelaos Kotsollaris", "author_id": 1373465, "author_profile": "https://Stackoverflow.com/users/1373465", "pm_score": 2, "selected": false, "text": "[email protected] \\S+@\\S+\\.\\S+" }, { "answer_id": 50570037, "author": "JoelBonetR", "author_id": 6479108, "author_profile": "https://Stackoverflow.com/users/6479108", "pm_score": 2, "selected": false, "text": "The local-part of the email address may use any of these ASCII characters:\n\n- uppercase and lowercase Latin letters A to Z and a to z;\n- digits 0 to 9;\n- special characters !#$%&'*+-/=?^_`{|}~;\n- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but \"John..Doe\"@example.com is allowed);[6]\nNote that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.\n- space and \"(),:;<>@[\\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);\n- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected].\n A__z/J0hn.sm{it!}[email protected]\n \"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com\n" }, { "answer_id": 50968324, "author": "Sbbs", "author_id": 1851294, "author_profile": "https://Stackoverflow.com/users/1851294", "pm_score": 3, "selected": false, "text": "/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i\n const emailRegex = /^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i;\n\nemailRegex.test('[email protected]'); // true\n\n// Multi-word domains\nemailRegex.test('[email protected]'); // true\nemailRegex.test('[email protected]'); // true\n\n// Valid special characters\nemailRegex.test('unusual+but+valid+email1900=/!#$%&\\'*+-/=?^_`.{|}[email protected]') // true\n\n// Trailing dots\nemailRegex.test('[email protected].'); // false\n\n// No domain\nemailRegex.test('email@example'); // false\n\n// Leading space\nemailRegex.test(' [email protected]'); // false\n\n// Trailing space\nemailRegex.test('[email protected] '); // false\n\n// Incorrect domains\nemailRegex.test('email@example,com '); // false\n\n// Other invalid emails\nemailRegex.test('invalid.email.com') // false\nemailRegex.test('invalid@[email protected]') // false\nemailRegex.test('[email protected]') // false\n" }, { "answer_id": 51399417, "author": "aabiro", "author_id": 7848529, "author_profile": "https://Stackoverflow.com/users/7848529", "pm_score": 1, "selected": false, "text": "(function() {\n 'use strict';\n\n window.addEventListener('load', function() {\n var form = document.getElementById('needs-validation');\n form.addEventListener('submit', function(event) {\n if (form.checkValidity() === false) {\n event.preventDefault();\n }\n form.classList.add('was-validated');\n event.preventDefault(); \n }, false);\n }, false);\n})();\n <p class='title'>\n <b>Email validation</b>\n <hr size=\"30px;\">\n</p>\n<br>\n\n<form id=\"needs-validation\" novalidate>\n <p class='form_text'>Try it out!</p>\n <div class=\"form-row\">\n <div class=\"col-12\">\n <input type=\"email\" class=\"form-control\" placeholder=\"Email Address\" required>\n <div class=\"invalid-feedback\">\n Please enter a valid email address.\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <button type=\"submit\" \n class=\"btn btn-default btn-block\">Sign up now\n </button>\n </div>\n </div>\n</form>\n" }, { "answer_id": 51464343, "author": "mpyw", "author_id": 1846562, "author_profile": "https://Stackoverflow.com/users/1846562", "pm_score": 1, "selected": false, "text": "filter_var($value, FILTER_VALIDATE_EMAIL) import validateEmail from 'filter-validate-email'\n\nconst value = '...'\nconst result = validateEmail(value)\n <?php\n\n$value = '...';\n$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);\n" }, { "answer_id": 54153341, "author": "isapir", "author_id": 968244, "author_profile": "https://Stackoverflow.com/users/968244", "pm_score": 2, "selected": false, "text": "/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}\n[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n" }, { "answer_id": 54845819, "author": "karlzafiris", "author_id": 4141689, "author_profile": "https://Stackoverflow.com/users/4141689", "pm_score": 1, "selected": false, "text": "$(document).ready(function(){\n $('#submit').on('click', function(){\n var email = $('#email').val();\n var pat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if (email.match(pat)){\n $('#email')\n .addClass('input-valid');\n return false;\n } else {\n $('#email')\n .addClass('input-error')\n .val('');\n return false;\n }\n });\n}); .input-error {\n border: 1px solid red;\n color: red;\n}\n\n.input-valid {\n border: 1px solid green;\n color: green;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<form>\n <input type=\"text\" id=\"email\" placeholder=\"[email protected]\" class=\"\">\n <input type=\"submit\" id=\"submit\" value=\"Send\"/>\n</form>" }, { "answer_id": 54948659, "author": "B. Bohdan", "author_id": 8097218, "author_profile": "https://Stackoverflow.com/users/8097218", "pm_score": 0, "selected": false, "text": "EmailValidator.validate EmailValidator.validateKind export class EmailValidator {\n /**\n * @param {string} email\n * @return {string}\n * @throws {Error}\n */\n static validate(email) {\n email = this.prepareEmail(email);\n\n const isValid = this.validateKind(email);\n\n if (isValid)\n return email;\n\n throw new Error(`Got invalid email: ${email}.`);\n }\n\n /**\n * @param {string} email\n * @return {boolean}\n */\n static validateKind(email) {\n email = this.prepareEmail(email);\n\n const regex = this.getRegex();\n\n return regex.test(email);\n }\n\n /**\n * @return {RegExp}\n * @private\n */\n static getRegex() {\n return /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n }\n\n /**\n * @param {string} email\n * @return {string}\n * @private\n */\n static prepareEmail(email) {\n return String(email).toLowerCase();\n }\n}\n // First way.\n\ntry {\n EmailValidator.validate('[email protected]');\n} catch (e) {\n console.error(e.message);\n}\n // Second way.\n\nconst email = '[email protected]';\nconst isValid = EmailValidator.validateKind(email);\n\nif (isValid)\n console.log(`Email is valid: ${email}.`);\nelse\n console.log(`Email is invalid: ${email}.`);\n" }, { "answer_id": 55807372, "author": "Raheel", "author_id": 2812955, "author_profile": "https://Stackoverflow.com/users/2812955", "pm_score": 0, "selected": false, "text": "/**\n * @param {*} email\n */\nexport const validateEmail = email => {\n return new RegExp(/[\\w-]+@([\\w-]+\\.)+[\\w-]+/gm).test(email);\n};\n" }, { "answer_id": 55852057, "author": "Antonio", "author_id": 1282278, "author_profile": "https://Stackoverflow.com/users/1282278", "pm_score": 2, "selected": false, "text": "/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n" }, { "answer_id": 56458505, "author": "Nicolas Zozol", "author_id": 968988, "author_profile": "https://Stackoverflow.com/users/968988", "pm_score": 1, "selected": false, "text": "import {C,Streams} from '@masala/parser'\n\nconst illegalCharset = ' @\\u00A0\\n\\t';\nconst extendedIllegalCharset = illegalCharset + '.';\n\n\n// Assume '[email protected]'\nexport function simpleEmail() {\n\n return C.charNotIn(illegalCharset).rep() // 'nicolas'\n .then(C.char('@'))\n .then(subDns()) //'internal.masala.co.'\n .then(C.charNotIn(extendedIllegalCharset).rep()) //'uk'\n .eos(); // Must be end of the char stream\n}\n\n// [email protected] => extract 'internal.masala.co.'\nfunction subDns() {\n return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep()\n}\n\nfunction validateEmail(email:string) {\n console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted()));\n}\n\n\nvalidateEmail('[email protected]'); // True\nvalidateEmail('nz@co.'); // False, trailing \".\"\n \nfunction inQuote() {\n return C.char('\"')\n .then(C.notChar('\"').rep())\n .then(C.char('\"'))\n}\n\nfunction allEmail() {\n\n return inQuote().or(C.charNotIn(illegalCharset))\n .rep() // repeat (inQuote or anyCharacter)\n .then(C.char('@'))\n .then(subDns())\n .then(C.charNotIn(extendedIllegalCharset).rep())\n .eos() // Must be end of the character stream\n // Create a structure\n .map(function (characters) { return ({ email: characters.join('') }); });\n}\n '\"nicolas\"\"love-quotes\"@masala.co.uk'" }, { "answer_id": 57966778, "author": "jimmont", "author_id": 965666, "author_profile": "https://Stackoverflow.com/users/965666", "pm_score": 2, "selected": false, "text": "URL username hostname function validEmail(email=''){\n var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\\.-]{3,252}$/i;\n email = email.trim();\n try{\n url = new URL('http://'+email);\n $0 = `${url.username}@${url.hostname}`;\n isValid = emailPatternInput.test( email );\n if(!isValid) throw 'invalid email pattern on input:' + email;\n isValid = emailPatternUrl.test( $0 );\n if(!isValid) throw 'invalid email pattern on url:' + $0;\n console.log(`email looks legit \"${email}\" checking url-parts: \"${$0 === email ? '-SAME-':$0}\"`);\n }catch(err){\n console.error(`probably not an email address: \"${email}\"`, err);\n };\n return isValid;\n}\n\n['user+this@はじめよう.みんな', 'stuff@things', '[email protected]', 'Jean+Franç[email protected]','هيا@יאללה', '试@例子.测试.مثال.آزمایشی', 'not@@really', 'no'].forEach(email=>console.log(validEmail(email), email));\n" }, { "answer_id": 58905771, "author": "Eboubaker", "author_id": 10387008, "author_profile": "https://Stackoverflow.com/users/10387008", "pm_score": 1, "selected": false, "text": "/^[a-z]((?!\\.\\.)([a-z\\.])){4,28}[a-z0-9]@gmail.com$/i /^[a-z]((?!\\.\\.)([\\w\\.])){3,30}[\\w]@yahoo.com$/i /[a-z]((?!\\.\\.)([\\w\\.])){0,62}[\\w]@(outlook.com|hotmail.com)$/i" }, { "answer_id": 59498223, "author": "Renish Gotecha", "author_id": 8274534, "author_profile": "https://Stackoverflow.com/users/8274534", "pm_score": 3, "selected": false, "text": "~ # function validEmail(email){\n const regex = /^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$/;\n return regex.test(email);\n}\n function validEmail(email){\n const regex = /^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$/;\n return regex.test(email);\n}\n\nconst emails = [\n'[email protected]',\n'[email protected]',\n'[email protected]',\n'pio_#[email protected]',\n'pio_pio@#factory.com',\n'[email protected]#om',\n'[email protected]*om',\n'pio^[email protected]'\n]\n\nfor(const email of emails){\n document.write(email+' : '+validEmail(email)+'</br>');\n}" }, { "answer_id": 59901196, "author": "Mattia Rasulo", "author_id": 10626207, "author_profile": "https://Stackoverflow.com/users/10626207", "pm_score": 2, "selected": false, "text": "/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(emailValue)\n" }, { "answer_id": 59922013, "author": "endyourif", "author_id": 913166, "author_profile": "https://Stackoverflow.com/users/913166", "pm_score": 4, "selected": false, "text": "if (email.indexOf('@') > 0)\n" }, { "answer_id": 60042450, "author": "user1843640", "author_id": 1843640, "author_profile": "https://Stackoverflow.com/users/1843640", "pm_score": 3, "selected": false, "text": "function isValidEmail(value) {\n const atLocation = value.lastIndexOf(\"@\");\n const dotLocation = value.lastIndexOf(\".\"); \n return (\n atLocation > 0 &&\n dotLocation > atLocation + 1 &&\n dotLocation < value.length - 1\n );\n};\n" }, { "answer_id": 61180079, "author": "Jaskaran Singh", "author_id": 5162083, "author_profile": "https://Stackoverflow.com/users/5162083", "pm_score": 2, "selected": false, "text": "/^[a-z0-9](?!.*?[^\\na-z0-9]{2})[^\\s@]+@[^\\s@]+\\.[^\\s@]+[a-z0-9]$/\n" }, { "answer_id": 62778080, "author": "Ebrahim", "author_id": 1007945, "author_profile": "https://Stackoverflow.com/users/1007945", "pm_score": 3, "selected": false, "text": "email-validator //NodeJs\nconst validator = require(\"email-validator\");\nvalidator.validate(\"[email protected]\"); // true\n\n//TypeScript/JavaScript\nimport * as EmailValidator from 'email-validator';\nEmailValidator.validate(\"[email protected]\"); // true\n" }, { "answer_id": 64735657, "author": "Nazmul Haque", "author_id": 5689349, "author_profile": "https://Stackoverflow.com/users/5689349", "pm_score": 1, "selected": false, "text": " // Html form call function name at submit button\n\n <form name=\"form1\" action=\"#\"> \n <input type='text' name='text1'/>\n <input type=\"submit\" name=\"submit\" value=\"Submit\" \n onclick=\"ValidateEmail(document.form1.text1)\"/>\n </from>\n\n // Write the function name ValidateEmail below\n\n <script>\n function ValidateEmail(inputText)\n {\n var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;\n if(inputText.value.match(mailformat))\n {\n alert(\"Valid email address!\");\n document.form1.text1.focus();\n return true;\n }\n else\n {\n alert(\"You have entered an invalid email address!\");\n document.form1.text1.focus();\n return false;\n }\n }\n </script>\n" }, { "answer_id": 67089282, "author": "FDisk", "author_id": 175404, "author_profile": "https://Stackoverflow.com/users/175404", "pm_score": 1, "selected": false, "text": "/^([^\\s\\@])+\\@(([^\\s\\@\\.])+\\.)+([^\\s\\.]{2,})+$/\n" }, { "answer_id": 67295040, "author": "Force Bolt", "author_id": 15478252, "author_profile": "https://Stackoverflow.com/users/15478252", "pm_score": 1, "selected": false, "text": "// Try this regular Expression by ES6 function\n\nconst emailValidate = (email) => {\n const regexp= /^[\\w.%+-]+@[\\w.-]+\\.[\\w]{2,6}$/;\n return regexp.test(email);\n}\n" }, { "answer_id": 72018404, "author": "jimmont", "author_id": 965666, "author_profile": "https://Stackoverflow.com/users/965666", "pm_score": 1, "selected": false, "text": "URL user@host function validEmail(input=''){\n const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\\.-]{3,252}$/i;\n let email, url, valid = false, error, same = false;\n try{\n email = input.trim();\n // handles punycode, etc using browser's own maintained implementation\n url = new URL('http://'+email);\n let urlderived = `${url.username}@${url.hostname}`;\n same = urlderived === email;\n valid = emailPatternInput.test( email );\n if(!valid) throw new Error('invalid email pattern on input:' + email);\n valid = emailPatternUrl.test( urlderived );\n if(!valid) throw new Error('invalid email pattern on url:' + urlderived);\n }catch(err){\n error = err;\n };\n return {email, url, same, valid, error};\n}\n\n[\n 'user+this@はじめよう.みんな'\n, '[email protected]'\n, 'stuff@things'\n, '[email protected]'\n, 'Jean+Franç[email protected]','هيا@יאללה'\n, '试@例子.测试.مثال.آزمایشی'\n, 'not@@really'\n, 'no'\n].forEach(email=>console.log(validEmail(email), email));\n" }, { "answer_id": 73457425, "author": "Adam Whateverson", "author_id": 6730421, "author_profile": "https://Stackoverflow.com/users/6730421", "pm_score": 2, "selected": false, "text": "var email = '[email protected]'\nif(email.split('@').length == 2 && email.indexOf('.') > 0){\n // The split ensures there's only 1 @\n // The indexOf ensures there's at least 1 dot.\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72/" ]
46,160
<p>I am looking for a way to create an int\long representation of an arbitrary alpha-numeric String. Hash codes won't do it, because I can't afford hash collisions i.e. the representation must be unique and repeatable. </p> <p>The numeric representation will be used to perform efficient (hopefully) compares. The creation of the numeric key will take some time, but it only has to happen once, whereas I need to perform vast numbers of comparisons with it - which will hopefully be much faster than comparing the raw Strings.</p> <p>Any other idea's on faster String comparison will be most appreciated too...</p>
[ { "answer_id": 46211, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "String y = \"oiu291981u39u192u3198u389u28u389u\";\nBigInteger bi = new BigInteger(y, 36);\nSystem.out.println(bi);\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4216/" ]
46,189
<p>I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?</p>
[ { "answer_id": 46206, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 3, "selected": true, "text": "var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
46,214
<p>I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:</p> <p>Is <code>$("div.myclass")</code> faster than <code>$(".myclass")</code></p> <p>I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance?</p>
[ { "answer_id": 218846, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "getElementsByClassName()" }, { "answer_id": 382730, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 4, "selected": false, "text": "$(\".myclass\", a_DOM_element);\n $(\".myclass\");\n" }, { "answer_id": 416144, "author": "jQuery Lover", "author_id": 49200, "author_profile": "https://Stackoverflow.com/users/49200", "pm_score": 2, "selected": false, "text": "$('.select', this)" }, { "answer_id": 2061997, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 0, "selected": false, "text": ":has() :contains()" }, { "answer_id": 2062027, "author": "Reid", "author_id": 236139, "author_profile": "https://Stackoverflow.com/users/236139", "pm_score": 0, "selected": false, "text": "$('#foo bar div') $('bar div #foo') $('#foo a') a #foo" }, { "answer_id": 2255881, "author": "Lawrence", "author_id": 272206, "author_profile": "https://Stackoverflow.com/users/272206", "pm_score": 0, "selected": false, "text": "$(\"#myform th\").css(\"color\",\"red\");\n $(\"th\").css(\"color\",\"red\");\n $(\"#myform\").find(\"th\").css(\"color\",\"red\")\n.end().find(\"td\").css(\"color\",\"blue\");\n $(\"#myform th\").css(\"color\",\"red\");\n$(\"#myform td\").css(\"color\",\"blue\");\n" }, { "answer_id": 4113652, "author": "Philipp", "author_id": 499255, "author_profile": "https://Stackoverflow.com/users/499255", "pm_score": 3, "selected": false, "text": "$('#foo bar div') $('bar div #foo') #foo .find .children $('#foo').find('div') $('div.common[slow*=Search] input.rare') $('div.rare input.common[name*=slowSearch]')" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
46,219
<p>If I have a </p> <pre><code>&lt;input id="uploadFile" type="file" /&gt; </code></pre> <p>tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.</p> <p>In FF, I just do:</p> <pre><code>var selected = document.getElementById("uploadBox").files.length &gt; 0; </code></pre> <p>But that doesn't work in IE.</p>
[ { "answer_id": 46242, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": true, "text": "if(document.getElementById(\"uploadBox\").value != \"\") {\n // you have a file\n}\n" }, { "answer_id": 22152474, "author": "Atiqur", "author_id": 2804202, "author_profile": "https://Stackoverflow.com/users/2804202", "pm_score": 3, "selected": false, "text": "var nme = document.getElementById(\"uploadFile\");\nif(nme.value.length < 4) {\n alert('Must Select any of your photo for upload!');\n nme.focus();\n return false;\n}\n" }, { "answer_id": 42990754, "author": "Ashu", "author_id": 1874707, "author_profile": "https://Stackoverflow.com/users/1874707", "pm_score": 2, "selected": false, "text": "function validateAndUpload(input){\n var URL = window.URL || window.webkitURL;\n var file = input.files[0];\n\n if (file) {\n var image = new Image();\n\n image.onload = function() {\n if (this.width) {\n console.log('Image has width, I think it is real image');\n //TODO: upload to backend\n }\n };\n\n image.src = URL.createObjectURL(file);\n }\n};​\n\n<input type=\"file\" name=\"uploadPicture\" accept=\"image/*\" onChange=\"validateAndUpload(this);\"/>\n" }, { "answer_id": 50415093, "author": "Elion Limanaj", "author_id": 9807638, "author_profile": "https://Stackoverflow.com/users/9807638", "pm_score": 2, "selected": false, "text": " var files = uploadFile.files;\n\n if (files.length == 0) { console.log(true) } else { console.log(false) }\n if (files[0] == undefined) { console.log(true) } else { console.log(false) }\n if (files[0] == null) { console.log(true) } else { console.log(false) }\n" }, { "answer_id": 74571436, "author": "sifr_dot_in", "author_id": 2173890, "author_profile": "https://Stackoverflow.com/users/2173890", "pm_score": 0, "selected": false, "text": "var elements = document.getElementsByClassName('uploadFile_ClassName');\nfor (var i = 0; i < elements.length; ++i) {\n if(elements[i].value != \"\") {\n // file is selected here;\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698/" ]
46,220
<p>I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging. Essentially my app displays an image and when touched plays a short sound. When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.</p> <p>I get the following error:</p> <pre><code>Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;UIView 0x34efd0&gt; setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.' </code></pre> <p>kramerImage here is the image I'm using for the background.</p> <p>I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.</p>
[ { "answer_id": 46357, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 6, "selected": true, "text": "[@\"hello world\" length] // Objective-C 1.0\n@\"hello world\".length // Objective-C 2.0\n [@\"hello world\" valueForKey:@\"length\"]\n [@\"hello world\" valueForKey:@\"purpleMonkeyDishwasher\"]\n" }, { "answer_id": 3899224, "author": "Owen Hartnett", "author_id": 69724, "author_profile": "https://Stackoverflow.com/users/69724", "pm_score": 3, "selected": false, "text": " NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@\"rootCell-iPad\" owner:self options:nil];\n\n cell = [nib objectAtIndex:0];\n" }, { "answer_id": 4143957, "author": "Vipul Parmar", "author_id": 496955, "author_profile": "https://Stackoverflow.com/users/496955", "pm_score": 0, "selected": false, "text": "@interface MyFirstIphoneAppViewController : UIViewController<> {\n UIImageView *InitialkramerImage;\n}\n@property(nonatomic,retain) IBOutlet UIImageView *InitialkramerImage;\n @interface MyFirstIphoneAppViewController : UIViewController<> {\n UIImageView *kramerImage;\n}\n@property(nonatomic,retain) IBOutlet UIImageView *kramerImage;\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293/" ]
46,231
<p>I'm working on an application where users have to make a call and type a verification number with the keypad of their phone.</p> <p>I would like to be able to detect if the number they type is correct or not. The phone system does not have access to a list of valid numbers, but instead, it will validate the number against an algorithm (like a credit card number).</p> <p>Here are some of the requirements :</p> <ul> <li>It must be difficult to type a valid random code </li> <li>It must be difficult to have a valid code if I make a typo (transposition of digits, wrong digit)</li> <li>I must have a reasonable number of possible combinations (let's say 1M)</li> <li>The code must be as short as possible, to avoid errors from the user</li> </ul> <p>Given these requirements, how would you generate such a number?</p> <p>EDIT :</p> <p>@Haaked: The code has to be numerical because the user types it with its phone.</p> <p>@matt b: On the first step, the code is displayed on a Web page, the second step is to call and type in the code. I don't know the user's phone number.</p> <p>Followup : I've found several algorithms to <em>check</em> the validity of numbers (See this interesting Google Code project : <a href="http://code.google.com/p/checkdigits/wiki/CheckDigitSystems" rel="nofollow noreferrer">checkDigits</a>).</p>
[ { "answer_id": 46486, "author": "Costo", "author_id": 1130, "author_profile": "https://Stackoverflow.com/users/1130", "pm_score": 6, "selected": true, "text": "123456 mod(98 - mod(number * 100, 97), 97) mod(code, 97) == 1 mod(12345676, 97) = 1 mod(21345676, 97) = 50 mod(12345678, 97) = 10" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130/" ]
46,252
<p>I would like to have a VM to look at how applications appear and to develop OS-specific applications, however, I want to keep all my code on my Windows machine so if I decide to nuke a VM or anything like that, it's all still there.</p> <p>If it matters, I'm using VirtualBox.</p>
[ { "answer_id": 17328498, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 0, "selected": false, "text": "mkdir $HOME/Desktop/Common\nsudo echo “$USER ALL=(ALL) NOPASSWD:ALL” >> /etc/sudoers\nfind $HOME/Desktop/Common -maxdepth 0 -type d -empty -exec sudo \\\nmount -t vboxsf -o \\\nuid=`id -u $USER`,gid=`id -g $USER` Common $HOME/Desktop/Common \\;\nsource ~/.bashrc # Needed if you want to mount Common in this bash.\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
46,277
<p>We have an encryption service that we've exposed over net. tcp. Most of the time, the service is used to encrypt/decrypt strings. However, every now and then, we the need to encrypt large documents (pdf, JPG, bmp, etc.).</p> <p>What are the best endpoint settings for a scenario like this? Should I accept/return a stream? I've read a lot about this, but no one gives guidance on what to do when the large file doesn't occur frequently.</p>
[ { "answer_id": 47808, "author": "Jeremy McGee", "author_id": 3546, "author_profile": "https://Stackoverflow.com/users/3546", "pm_score": 3, "selected": true, "text": "net.tcp" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
46,281
<p>I have been hearing a lot of good things about DVCS systems, in particular about bazaar. Apart from the concept of distributed repository, I see two main advantages being touted: the merge is better automated, and the rename is handled right.</p> <p>Could someone please point me at some text explaining how exactly the improvements work? How does bazaar know that I renamed a file? What if I rename two files as part of the same commit? What happens when I refactor by putting half of the file's contents into a new file, re-indenting everything and losing some whitespace in nearly every line?</p> <p>In other words, I'd like to hear from people using bazaar (or another DVCS) in real life, or from people who know how it (they) works. Is the merge really that much better? And how is it achieved?</p> <hr> <p>Related question, with a useful answer:</p> <p><a href="https://stackoverflow.com/questions/43995/why-is-branching-and-merging-easier-in-mercurial-than-in-subversion">Why is branching and merging easier in Mercurial than in Subversion?</a></p>
[ { "answer_id": 46544, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "bzr rename <old> <new> --after bzr rename <old> <new> bzr add" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,282
<p>I am using a class library which represents some of its configuration in .xml. The configuration is read in using the <code>XmlSerializer</code>. Fortunately, the classes which represent the .xml use the <code>XmlAnyElement</code> attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Config&gt; &lt;data&gt;This is some data&lt;/data&gt; &lt;MyConfig&gt; &lt;data&gt;This is my data&lt;/data&gt; &lt;/MyConfig&gt; &lt;/Config&gt; </code></pre> <p>This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own <code>XmlSerializer</code> instances with a <code>XmlNodeReader</code> against the internal <code>XmlNode</code>.</p> <pre><code>public class Config { [XmlElement] public string data; [XmlAnyElement] public XmlNode element; } public class MyConfig { [XmlElement] public string data; } class Program { static void Main(string[] args) { using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open)) { XmlSerializer xser1 = new XmlSerializer(typeof(Config)); Config config = (Config)xser1.Deserialize(fs); if (config.element != null) { XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig)); MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element)); } } } </code></pre> <p>I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml? </p> <p>I realize that I have to initially call <code>XmlSerializer.Serialize</code> on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an <code>XmlNode</code> after calling <code>Serialize</code>. What is the best way to serialize an object into an <code>XmlNode</code> using the <code>XmlSerializer</code>?</p> <p>Thanks,</p> <p>-kevin</p> <p>btw-- It looks like an <code>XmlNodeWriter</code> class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?</p>
[ { "answer_id": 46378, "author": "Ed Schwehm", "author_id": 1206, "author_profile": "https://Stackoverflow.com/users/1206", "pm_score": 5, "selected": true, "text": "XmlSerializer xs = new XmlSerializer(typeof(MyConfig));\nStringWriter xout = new StringWriter();\nxs.Serialize(xout, myConfig);\nXmlDocument x = new XmlDocument();\nx.LoadXml(\"<myConfig>\" + xout.ToString() + \"</myConfig>\");\n" }, { "answer_id": 46401, "author": "Kevin", "author_id": 4599, "author_profile": "https://Stackoverflow.com/users/4599", "pm_score": 0, "selected": false, "text": "XmlSerializer xser1 = new XmlSerializer(typeof(Config));\nXmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));\n\nMyConfig myConfig = new MyConfig();\nmyConfig.data = \"My special data\";\n\nStringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nXmlWriter xw = new XmlTextWriter(sw);\nxser2.Serialize(xw, myConfig);\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(sb.ToString());\n\nConfig config = new Config();\nconfig.data = \"some new info\";\nconfig.element = doc.LastChild;\n\nxser1.Serialize(fs, config);\n" }, { "answer_id": 307707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));\nXmlSerializer serializer = new XmlSerializer(typeof(foo));\n\nXmlDocument doc = new XmlDocument();\nXPathNavigator nav = doc.CreateNavigator();\nXmlWriter writer = nav.AppendChild();\nwriter.WriteStartDocument();\n//serializer.WriteObject(writer, new foo { bar = 42 });\nserializer.Serialize(writer, new foo { bar = 42 });\nwriter.WriteEndDocument();\nwriter.Flush();\nwriter.Close();\n\nConsole.WriteLine(doc.OuterXml);\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
46,283
<p>We have a service that has some settings that are supported only over net.tcp. What's the best way to add another endpoint? Do I need to create an entire new host?</p>
[ { "answer_id": 50740, "author": "Dylan", "author_id": 4580, "author_profile": "https://Stackoverflow.com/users/4580", "pm_score": 3, "selected": false, "text": "<endpoint address=\"https://yourdomain.com/WCF/YourService.svc\"\n binding=\"basicHttpBinding\"\n bindingConfiguration=\"BasicHttpBinding_IYourService\"\n contract=\"MessagingService.IYourService\" \n name=\"BasicHttpBinding_IYourService\" />\n YourServiceClient client = new YourServiceClient();\n <endpoint address=\"https://yourotherdomain.com/WCF/YourService.svc\"\n binding=\"basicHttpBinding\"\n bindingConfiguration=\"BasicHttpBinding_IYourService\"\n contract=\"MessagingService.IYourService\" \n name=\"BasicHttpBinding_IYourService_ENDPOINT2\" />\n YourServiceClient client = new YourServiceClient(\"BasicHttpBinding_IYourService_ENDPOINT2\");\n" }, { "answer_id": 53812740, "author": "Vinoth", "author_id": 5052899, "author_profile": "https://Stackoverflow.com/users/5052899", "pm_score": 0, "selected": false, "text": " <service name=\"MessagePatternDemo.Service1\"> \n <endpoint name=\"ep1\" address=\"/ep1\" binding=\"basicHttpBinding\" \n contract=\"MessagePatternDemo.IService1\"/> \n <endpoint name=\"ep2\" address=\"/ep2\" binding=\"wsHttpBinding\" \n contract=\"MessagePatternDemo.IService1\" /> \n <endpoint name=\"mex\" contract=\"IMetadataExchange\" address=\"mex\" \n binding=\"mexHttpBinding\" /> \n </service> \n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
46,305
<p>I understand how I can change the <code>dns</code> settings for my domains by editing my bind configs, when I run my own name-servers. I know that I can define the name-servers with my registrar via their online control panels. But I have no idea how that part works...</p> <p>How does my registrar store the data about the name-servers? Is it something clever, like them having the authority to store NS records in the root name-servers?</p> <p>I'm confused by this part, can anyone explain?</p>
[ { "answer_id": 46321, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "# dig +trace ns stackoverflow.com \n\n; <<>> DiG 9.2.4 <<>> +trace ns stackoverflow.com\n;; global options: printcmd\n. 269431 IN NS B.ROOT-SERVERS.NET.\n. 269431 IN NS C.ROOT-SERVERS.NET.\n. 269431 IN NS D.ROOT-SERVERS.NET.\n. 269431 IN NS E.ROOT-SERVERS.NET.\n. 269431 IN NS F.ROOT-SERVERS.NET.\n. 269431 IN NS G.ROOT-SERVERS.NET.\n. 269431 IN NS H.ROOT-SERVERS.NET.\n. 269431 IN NS I.ROOT-SERVERS.NET.\n. 269431 IN NS J.ROOT-SERVERS.NET.\n. 269431 IN NS K.ROOT-SERVERS.NET.\n. 269431 IN NS L.ROOT-SERVERS.NET.\n. 269431 IN NS M.ROOT-SERVERS.NET.\n. 269431 IN NS A.ROOT-SERVERS.NET.\n;; Received 504 bytes from 83.138.151.80#53(83.138.151.80) in 3 ms\n\ncom. 172800 IN NS A.GTLD-SERVERS.NET.\ncom. 172800 IN NS B.GTLD-SERVERS.NET.\ncom. 172800 IN NS C.GTLD-SERVERS.NET.\ncom. 172800 IN NS D.GTLD-SERVERS.NET.\ncom. 172800 IN NS E.GTLD-SERVERS.NET.\ncom. 172800 IN NS F.GTLD-SERVERS.NET.\ncom. 172800 IN NS G.GTLD-SERVERS.NET.\ncom. 172800 IN NS H.GTLD-SERVERS.NET.\ncom. 172800 IN NS I.GTLD-SERVERS.NET.\ncom. 172800 IN NS J.GTLD-SERVERS.NET.\ncom. 172800 IN NS K.GTLD-SERVERS.NET.\ncom. 172800 IN NS L.GTLD-SERVERS.NET.\ncom. 172800 IN NS M.GTLD-SERVERS.NET.\n;; Received 495 bytes from 192.228.79.201#53(B.ROOT-SERVERS.NET) in 145 ms\n\nstackoverflow.com. 172800 IN NS ns51.domaincontrol.com.\nstackoverflow.com. 172800 IN NS ns52.domaincontrol.com.\n;; Received 119 bytes from 192.5.6.30#53(A.GTLD-SERVERS.NET) in 156 ms\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1951/" ]
46,324
<p>I'm going to guess that the answer is "no" based on the below error message (and <a href="http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php" rel="noreferrer">this Google result</a>), but is there anyway to perform a cross-database query using PostgreSQL?</p> <pre><code>databaseA=# select * from databaseB.public.someTableName; ERROR: cross-database references are not implemented: "databaseB.public.someTableName" </code></pre> <p>I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the <code>users</code> table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...</p>
[ { "answer_id": 46448, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 8, "selected": true, "text": "postgres_fdw postgres_fdw postgres_fdw file_fdw dblink" }, { "answer_id": 27054140, "author": "Manwal", "author_id": 2236219, "author_profile": "https://Stackoverflow.com/users/2236219", "pm_score": 6, "selected": false, "text": "SELECT * \nFROM table1 tb1 \nLEFT JOIN (\n SELECT *\n FROM dblink('dbname=db2','SELECT id, code FROM table2')\n AS tb2(id int, code text);\n) AS tb2 ON tb2.column = tb1.column;\n" }, { "answer_id": 55653353, "author": "Haroldo_OK", "author_id": 679240, "author_profile": "https://Stackoverflow.com/users/679240", "pm_score": 1, "selected": false, "text": "databasechangeloglock CREATE EXTENSION IF NOT EXISTS dblink;\n\nDO \n$$\nDECLARE database_name TEXT;\nDECLARE conn_template TEXT;\nDECLARE conn_string TEXT;\nDECLARE table_exists Boolean;\nBEGIN\n conn_template = 'user=myuser password=mypass dbname=';\n\n FOR database_name IN\n SELECT datname FROM pg_database\n WHERE datistemplate = false\n LOOP\n conn_string = conn_template || database_name;\n\n table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));\n IF table_exists THEN\n perform dblink_exec(conn_string, 'delete from databasechangeloglock');\n END IF; \n END LOOP;\n\nEND\n$$\n" }, { "answer_id": 66078827, "author": "Kind Contributor", "author_id": 887092, "author_profile": "https://Stackoverflow.com/users/887092", "pm_score": 2, "selected": false, "text": "DELETE\nALTER TABLE\nCREATE TABLE (CREATE TABLE AS is supported)\nGRANT\nREVOKE\nSHOW GRANTS\nSHOW ROLES\nSHOW ROLE GRANTS\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
46,338
<p>I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?</p>
[ { "answer_id": 46356, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 5, "selected": true, "text": "<?php\n// in your controller\n$model1 = new Model1();\n$model2 = new Model2();\n$model2->setWhatever($model1);\n?>\n" }, { "answer_id": 75087, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 4, "selected": false, "text": "class SomeModel extends Model\n{\n function doSomething($foo)\n {\n $CI =& get_instance();\n $CI->load->model('SomeOtherModel','NiceName',true);\n\n // use $CI instead of $this to query the other models\n $CI->NiceName->doSomethingElse();\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
46,346
<p>Any ideas on how to implement tab completion for a .NET (C#) Console Application? And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this: </p> <pre><code> string line = string.Empty; while (line != "exit") { //do something here Console.ReadLine(); } </code></pre> <p>I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user.</p>
[ { "answer_id": 47594, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 3, "selected": false, "text": "someCommand.Name.BeginsWith(currentinput)" }, { "answer_id": 57116500, "author": "Olivier Duhart", "author_id": 5006676, "author_profile": "https://Stackoverflow.com/users/5006676", "pm_score": 1, "selected": false, "text": "Console.ReadLine()" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
46,347
<p>Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?</p>
[ { "answer_id": 7605311, "author": "toxaq", "author_id": 97429, "author_profile": "https://Stackoverflow.com/users/97429", "pm_score": 8, "selected": true, "text": "<configuration>\n <system.webServer>\n <rewrite>\n <rules>\n <rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Redirect\" redirectType=\"Permanent\" url=\"https://{HTTP_HOST}/{R:1}\" />\n </rule>\n </rules>\n </rewrite>\n </system.webServer>\n</configuration>\n" }, { "answer_id": 44283235, "author": "Toolkit", "author_id": 631527, "author_profile": "https://Stackoverflow.com/users/631527", "pm_score": 0, "selected": false, "text": "protected void Application_BeginRequest()\n{\nif (!Context.Request.Url.AbsoluteUri.Contains(\"localhost\") && !Context.Request.IsSecureConnection)\nResponse.Redirect(Context.Request.Url.ToString().Replace(\"http:\", \"https:\"));\n}\n" }, { "answer_id": 53725455, "author": "Jean-Marc", "author_id": 2729328, "author_profile": "https://Stackoverflow.com/users/2729328", "pm_score": 0, "selected": false, "text": "if Request.ServerVariables(\"SERVER_PORT_SECURE\") <> \"1\" or Request.ServerVariables(\"HTTPS\") <> \"on\" then \n Response.Redirect \"https://\" & Request.ServerVariables(\"SERVER_NAME\") & Request.ServerVariables(\"URL\")\nend if\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312/" ]
46,350
<p>After lots of attempts and search I have never found a satisfactory way to do it with CSS2.</p> <p>A simple way to accomplish it is to wrap it into a handy <code>&lt;table&gt;</code> as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 0 auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;test&lt;br/&gt;test&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <hr /> <p>What I want to know is how to do it without a fixed width and also being a block.</p>
[ { "answer_id": 46391, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 4, "selected": true, "text": "<center> body {\n text-align: center;\n}\n\n.my-centered-content {\n margin: 0 auto; /* Centering */\n display: inline;\n} <div class=\"my-centered-content\">\n <p>test</p>\n <p>test</p>\n</div> width:100% display: inline-block; border: solid red 1px; .my-centered-content" }, { "answer_id": 46420, "author": "codeLes", "author_id": 3030, "author_profile": "https://Stackoverflow.com/users/3030", "pm_score": 0, "selected": false, "text": "<div style=\"border: 1px solid black; \n width: 300px; \n height: 300px;\">\n <div style=\"width: 150px; \n height: 150px; \n background-color: blue;\n position: relative;\n left: auto;\n right: auto;\n margin-right: auto;\n margin-left: auto;\">\n </div>\n</div>\n" }, { "answer_id": 46652, "author": "ironkeith", "author_id": 4106, "author_profile": "https://Stackoverflow.com/users/4106", "pm_score": 0, "selected": false, "text": "#wrapper {\n width: 100%;\n border: 1px solid #333;\n}\n#content {\n width: 200px;\n background: #0f0;\n} <div id=\"wrapper\" align=\"center\">\n <div id=\"content\" align=\"left\"> Content Here </div>\n</div>" }, { "answer_id": 50393, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<div style=\"display: table; margin: 0px auto 0 auto;\">test<br>test</div>\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
46,354
<p>I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:</p> <pre><code>SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query') </code></pre> <p>But if I try to add:</p> <pre><code>WHERE "Value" &gt; 0 </code></pre> <p>I get an error</p> <blockquote> <p>Invalid column name 'Value'</p> </blockquote> <p>Any ideas what I might be doing wrong?</p> <hr> <p>So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:</p> <p><a href="http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx" rel="noreferrer">http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx</a></p> <p>The order of evaluation in MSSQL is:</p> <ol> <li>FROM</li> <li>ON</li> <li>JOIN</li> <li>WHERE</li> <li>GROUP BY</li> <li>HAVING</li> <li>SELECT</li> <li>ORDER BY</li> </ol> <p>So the alias wasn't processed until after the WHERE and HAVING clauses.</p>
[ { "answer_id": 46375, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "SELECT whatever AS value FROM table HAVING value > 1;\n" }, { "answer_id": 46382, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 5, "selected": true, "text": "SELECT A.Value\nFROM (\nSELECT \"Ugly OLAP name\" as \"Value\" \nFROM OpenQuery( OLAP, 'OLAP Query')\n) AS a\nWHERE a.Value > 0\n" }, { "answer_id": 46552, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 3, "selected": false, "text": "SELECT \"Ugly OLAP name\" as \"Value\" \nFROM OpenQuery( OLAP, 'OLAP Query')\nWHERE \"Ugly OLAP name\" > 0\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
46,365
<p>We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1" rel="noreferrer">1</a>, it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?</p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1" rel="noreferrer">1</a> [<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1]" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&amp;SiteID=1]</a> “Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”</p>
[ { "answer_id": 168518, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 2, "selected": false, "text": "declare @t table (name nvarchar(128))\ninsert into @t select name from sys.databases --where is_fulltext_enabled \n\nwhile exists(SELECT * FROM @t)\nbegin\n declare @name nvarchar(128)\n select @name = name from @t\n declare @SQL nvarchar(4000)\n set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit'''\n print @sql\n exec sp_sqlexec @SQL\n delete from @t where name = @name\nend\n sys.databases" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4803/" ]
46,377
<p>What is the syntax for placing constraints on multiple types? The basic example:</p> <pre><code>class Animal&lt;SpeciesType&gt; where SpeciesType : Species </code></pre> <p>I would like to place constraints on both types in the following definition such that <code>SpeciesType</code> must inherit from <code>Species</code> and <code>OrderType</code> must inherit from <code>Order</code>:</p> <pre><code>class Animal&lt;SpeciesType, OrderType&gt; </code></pre>
[ { "answer_id": 46384, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 7, "selected": true, "text": "public class Animal<SpeciesType,OrderType>\n where SpeciesType : Species\n where OrderType : Order\n{\n}\n" }, { "answer_id": 46390, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 4, "selected": false, "text": "class Animal<SpeciesType, OrderType>\n where SpeciesType : Species\n where OrderType : Order {\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
46,380
<p>If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object? </p> <p>Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I'm a developer working with a complex join through several layers of application code, it's often very difficult to tell.</p> <p>My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.)</p> <p>Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table?</p> <hr> <p>Although I've accepted an answer which is relevant to the topic, it doesn't really answer my question: <em>Why isn't the name part of the error message?</em> If anyone can come up with the real answer, I'll be happy to change my vote.</p>
[ { "answer_id": 47143, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 2, "selected": false, "text": "SQL> select * from xx,abc;\nselect * from xx,abc\n *\nERROR at line 1:\nORA-00942: table or view does not exist\n\n\nSQL> select owner,table_name from all_tables where table_name in ('XX','ABC');\n\nOWNER TABLE_NAME\n------------------------------ ------------------------------\nMWATSON XX\n\nSQL> \n" }, { "answer_id": 52118, "author": "Nick Pierpoint", "author_id": 4003, "author_profile": "https://Stackoverflow.com/users/4003", "pm_score": 4, "selected": false, "text": "SQL> select\n 2 *\n 3 from\n 4 user_tables a,\n 5 non_existent_table b\n 6 where\n 7 a.table_name = b.table_name;\n non_existent_table b\n *\nERROR at line 5:\nORA-00942: table or view does not exist\n SQL> select * from user_tables a, non_existent_table b where a.table_name = b.table_name;\nselect * from user_tables a, non_existent_table b where a.table_name = b.table_name\n *\nERROR at line 1:\nORA-00942: table or view does not exist\n" }, { "answer_id": 770553, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "$ exec_sql.pl 'select * from daul'\nDBD::Oracle::db prepare failed: ORA-00942: table or view does not exist (DBD ERROR: error possibly near <*> indicator at char 14 in 'select * from <*>daul') [for Statement \"select * from daul\"] at exec_sql.pl line 68.\n SQL> select * from where dummy = 'X';\nselect * from where dummy = 'X'\n *\nERROR at line 1:\nORA-00903: invalid table name\n" }, { "answer_id": 4850892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "SQL> begin\n 2 execute immediate 'insert into blabla values(1)';\n 3 end;\n 4 /\nbegin\n*\nERROR at line 1:\nORA-00942: table or view does not exist\nORA-06512: at line 2\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3474/" ]
46,385
<p>What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? </p>
[ { "answer_id": 46386, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 7, "selected": true, "text": "DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)\n" }, { "answer_id": 46393, "author": "Riri", "author_id": 298, "author_profile": "https://Stackoverflow.com/users/298", "pm_score": 0, "selected": false, "text": "Delete article where id not in (select top 1000 id from article)\n" }, { "answer_id": 46404, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 5, "selected": false, "text": "DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)\n create table #nuke(NukeID int)\n\ninsert into #nuke(Nuke) select top 1000 id from article\n\ndelete article where not exists (select 1 from nuke where Nukeid = id)\n\ndrop table #nuke\n" }, { "answer_id": 46505, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "Delete a From Table a Inner Join (\n Select Top (Select Count(tableID) From Table) - 10) \n From Table Order By tableID Desc\n) b On b.tableID = A.tableID\n" }, { "answer_id": 46520, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 4, "selected": false, "text": "ORDER BY LIMIT TOP DELETE FROM table\nWHERE id NOT IN (SELECT id FROM table ORDER BY id LIMIT n);\n" }, { "answer_id": 509158, "author": "Noah", "author_id": 12113, "author_profile": "https://Stackoverflow.com/users/12113", "pm_score": 2, "selected": false, "text": "declare @n int\nSET @n = SELECT Count(*) FROM dTABLE;\nDELETE TOP (@n - 10 ) FROM dTable\n DELETE TOP 90 PERCENT FROM dTABLE;\n" }, { "answer_id": 13226312, "author": "Tim Wilson", "author_id": 1734757, "author_profile": "https://Stackoverflow.com/users/1734757", "pm_score": 3, "selected": false, "text": "DELETE \n Product\nFROM\n Product\n LEFT OUTER JOIN\n (\n SELECT TOP 10\n Product.id\n FROM\n Product\n ) TopProducts ON Product.id = TopProducts.id\nWHERE\n TopProducts.id IS NULL\n" }, { "answer_id": 55834751, "author": "Hrvoje", "author_id": 2119941, "author_profile": "https://Stackoverflow.com/users/2119941", "pm_score": 3, "selected": false, "text": "WITH CTE AS\n (\n SELECT ID\n FROM dbo.TableName\n ORDER BY ID DESC\n OFFSET 11 ROWS\n )\nDELETE CTE;\n ID OFFSET DESC ASC" }, { "answer_id": 63455642, "author": "clamchoda", "author_id": 591285, "author_profile": "https://Stackoverflow.com/users/591285", "pm_score": 0, "selected": false, "text": "TOP TOP MAX MaxId MaxId -- Declare Variable to hold the highest id we want to keep. \nDECLARE @MaxId as int = (\nSELECT MAX(temp.ID)\nFROM (SELECT TOP 10 ID FROM table ORDER BY ID ASC) temp\n)\n\n-- Delete anything greater than MaxId. If MaxId is null, there is nothing to delete.\nIF @MaxId IS NOT NULL\n DELETE FROM table WHERE ID > @MaxId\n ORDER BY MaxId" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
46,387
<p>I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option.</p> <p><a href="http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1" rel="nofollow noreferrer">http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1</a></p> <p>There is a version 1.2, already tested and get the same issue. The post looks something like this.</p> <pre><code>Host: foo.appspot.com User-Agent: lwp-request/1.38 Content-Type: text/plain Content-Length: 202 &lt;XML&gt; &lt;BLAH&gt;Hello World&lt;/BLAH&gt; &lt;/XML&gt; </code></pre> <p>I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow.</p> <p>Update: Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine!</p>
[ { "answer_id": 46551, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 1, "selected": false, "text": "my $size;\ndo {use bytes; $size = length($file_data)}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ]
46,425
<p>I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?</p> <pre><code>(defun biggerElems(x xs) (let ((xst)) (dolist (elem xs) (if (&gt; x elem) (setf xst (remove elem xs)))) xst)) </code></pre>
[ { "answer_id": 46437, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 4, "selected": true, "text": "(setf xst (remove elem xs))))\n setf xst nil (defun biggerElems (x xs)\n (remove-if (lambda (item) (> item x)) xs))\n" }, { "answer_id": 46474, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 1, "selected": false, "text": "(defun filterBig (x xs)\n (remove-if (lambda (item) (> item x)) xs))\n" }, { "answer_id": 46494, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "#' (remove-if #'oddp list)" }, { "answer_id": 46500, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "(defun biggerElems (x xs)\n (cond ((null xs) NIL)\n ((< x (car xs))\n (biggerElems x (cdr xs)))\n (t\n (cons (car xs) (biggerElems x (cdr xs))))))\n" }, { "answer_id": 72912, "author": "Bart", "author_id": 9792, "author_profile": "https://Stackoverflow.com/users/9792", "pm_score": 2, "selected": false, "text": "(defun bigger-elements (x xs) (remove x xs :test #'<))\n (< y x)\n (defun bigger-elements-2 (x xs) \n (loop for e in xs\n unless (< e x)\n collect e))\n" }, { "answer_id": 118049, "author": "Morikal", "author_id": 18272, "author_profile": "https://Stackoverflow.com/users/18272", "pm_score": 1, "selected": false, "text": "(defun biggerElems(x xs)\n (let ((xst xs))\n (dolist (elem xs)\n (when (> x elem)\n (setf xst (remove elem xst))))\n xst))\n (defun bigger-elems (x xs) ; I prefer hyphen separated to camelCase... to each his own\n (loop for elem in xs when (<= x elem) collect elem))\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450/" ]
46,439
<p>I have ms sql databases that grow very large. Upon examination I find that there is a bunch of unused space in certain tables. I don't do many physical deletes, so I don't think that its just deleted records. DBCC SHRINK doesn't make the file smaller. But, if I dump the table to a new, empty database, the size goes down about 80%. Instead of the 7gb I have in this table in the current database, I end up with about 1.5gb in the fresh database. Its as if sql server is allocating too much memory. Anyone encountered this before? I'd like to be able to shrink the table by removing unused allocated space without having to create a whole new database.</p> <p>Additional information:</p> <p>Full recovery model used. I'll try rebuilding the indexes, i think its been a while. ldf's are shrunk daily using some wacky stored proc that truncates them.</p>
[ { "answer_id": 116017, "author": "Rob", "author_id": 6201, "author_profile": "https://Stackoverflow.com/users/6201", "pm_score": 0, "selected": false, "text": "USE [DBNAME]\nGO\n\nDBCC SHRINKFILE (N'FILENAME' , 0, TRUNCATEONLY)\n\nGO\n" }, { "answer_id": 152738, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 0, "selected": false, "text": "PAD_INDEX=OFF PAD_INDEX" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300/" ]
46,454
<p>I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?</p>
[ { "answer_id": 46463, "author": "Oded", "author_id": 1583, "author_profile": "https://Stackoverflow.com/users/1583", "pm_score": 2, "selected": false, "text": "webCtrl.AutoScrollOffset = new Point(0, webCtrl.Height);\n" }, { "answer_id": 50264, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 4, "selected": true, "text": "webCtrl.Document.Window.ScrollTo(0, int.MaxValue);\n" }, { "answer_id": 22340865, "author": "IlPADlI", "author_id": 2430943, "author_profile": "https://Stackoverflow.com/users/2430943", "pm_score": 0, "selected": false, "text": "user2:\n new message ← a new message is insert on top\n\nuser1:\n old message\n" }, { "answer_id": 40783280, "author": "Chathuranga Abeyrathne", "author_id": 7204504, "author_profile": "https://Stackoverflow.com/users/7204504", "pm_score": 0, "selected": false, "text": " public virtual void ScrollMessageIntoView()\n {\n\n System.Windows.Forms.Application.DoEvents();\n if (browser == null || browser.IsDisposed)\n return;\n\n if (browser.Document == null)\n {\n browser.Document.Window.ScrollTo(0,\n browser.Document.Body.ScrollRectangle.Height);\n }\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
46,482
<p>Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?</p> <p>Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?</p>
[ { "answer_id": 46526, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 4, "selected": true, "text": "Using cn = New OleDbConnection(connectionstring)\n cn.Open()\n Dim ds As DataSet = new DataSet()\n\n Dim Schema As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, \"TABLE\"})\n For i As Integer = 0 To Schema.Rows.Count - 1\n Dim dt As DataTable = New DataTable(Schema.Rows(i)!TABLE_NAME.ToString())\n\n Using adapter = New OleDbDataAdapter(\"SELECT * FROM \" + Schema.Rows(i)!TABLE_NAME.ToString(), cn)\n adapter.Fill(dt)\n End Using\n\n ds.Tables.Add(dt)\n Next i\nEnd Using\n" }, { "answer_id": 46531, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": " public DataTable GetColumns(string tableName)\n {\n string[] restrictions = new string[4];\n restrictions[2] = tableName;\n\n _connDb.Open();\n\n DataTable mDT = _connDb.GetSchema(\"Columns\", restrictions);\n\n _connDb.Close();\n\n return mDT;\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
46,483
<p>What are the differences between <code>htmlspecialchars()</code> and <code>htmlentities()</code>. When should I use one or the other?</p>
[ { "answer_id": 46491, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 10, "selected": true, "text": "htmlspecialchars() htmlentities() htmlentities() htmlspecialchars echo htmlentities('<Il était une fois un être>.');\n // Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.\n // ^^^^^^^^ ^^^^^^^\n\n echo htmlspecialchars('<Il était une fois un être>.');\n // Output: &lt;Il était une fois un être&gt;.\n // ^ ^\n" }, { "answer_id": 3614330, "author": "Artefacto", "author_id": 127724, "author_profile": "https://Stackoverflow.com/users/127724", "pm_score": 7, "selected": false, "text": "htmlentities htmlspecialchars htmlentities" }, { "answer_id": 3614333, "author": "grossvogel", "author_id": 14957, "author_profile": "https://Stackoverflow.com/users/14957", "pm_score": 4, "selected": false, "text": "htmlspecialchars () htmlentities ()" }, { "answer_id": 3614344, "author": "Arseni Mourzenko", "author_id": 240613, "author_profile": "https://Stackoverflow.com/users/240613", "pm_score": 9, "selected": false, "text": "htmlspecialchars htmlentities htmlspecialchars echo htmlentities('<Il était une fois un être>.');\n// Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.\n// ^^^^^^^^ ^^^^^^^\n\necho htmlspecialchars('<Il était une fois un être>.');\n// Output: &lt;Il était une fois un être&gt;.\n// ^ ^\n" }, { "answer_id": 5570629, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 4, "selected": false, "text": "get_html_translation_table HTML_ENTITIES HTML_SPECIALCHARS" }, { "answer_id": 12079371, "author": "Kmeixner", "author_id": 1598979, "author_profile": "https://Stackoverflow.com/users/1598979", "pm_score": 4, "selected": false, "text": "htmlspecialchars($strText, ENT_QUOTES)" }, { "answer_id": 24351380, "author": "Berky", "author_id": 3500977, "author_profile": "https://Stackoverflow.com/users/3500977", "pm_score": 7, "selected": false, "text": "htmlentities implode( \"\\t\", array_values( get_html_translation_table( HTML_ENTITIES ) ) ) htmlspecialchars implode( \"\\t\", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) )" }, { "answer_id": 35146143, "author": "learn2reid", "author_id": 2141301, "author_profile": "https://Stackoverflow.com/users/2141301", "pm_score": 2, "selected": false, "text": "[1] => Altisoxxce Soluxxons S.à r.l.\n[5] => Joxxson & Joxxson\n $term = get_term_by('name', htmlentities($name), 'client'); htmlspecialchars" }, { "answer_id": 41745526, "author": "Anson Hwang", "author_id": 7033914, "author_profile": "https://Stackoverflow.com/users/7033914", "pm_score": 1, "selected": false, "text": "**HTML Character Entity Reference Chart at W3.org**\n &Tab;\n&NewLine;\n!\n&excl;\n\"\n&quot; &QUOT;\n#\n&num;\n$\n&dollar;\n%\n&percnt;\n&\n&amp; &AMP;\n'\n&apos;\n(\n&lpar;\n)\n&rpar;\n*\n&ast; &midast;\n+\n&plus;\n,\n&comma;\n.\n&period;\n/\n&sol;\n:\n&colon;\n;\n&semi;\n<\n&lt; &LT;\n=\n&equals;\n>\n&gt; &GT;\n?\n&quest;\n@\n&commat;\n[\n&lsqb; &lbrack;\n\\\n&bsol;\n]\n&rsqb; &rbrack;\n^\n&Hat;\n_\n&lowbar;\n`\n&grave; &DiacriticalGrave;\n{\n&lcub; &lbrace;\n|\n&verbar; &vert; &VerticalLine;\n}\n&rcub; &rbrace;\n\n&nbsp; &NonBreakingSpace;\n¡\n&iexcl;\n¢\n&cent;\n£\n&pound;\n¤\n&curren;\n¥\n&yen;\n¦\n&brvbar;\n§\n&sect;\n¨\n&Dot; &die; &DoubleDot; &uml;\n©\n&copy; &COPY;\nª\n&ordf;\n«\n&laquo;\n¬\n&not;\n&shy;\n®\n&reg; &circledR; &REG;\n¯\n&macr; &OverBar; &strns;\n°\n&deg;\n±\n&plusmn; &pm; &PlusMinus;\n²\n&sup2;\n³\n&sup3;\n´\n&acute; &DiacriticalAcute;\nµ\n&micro;\n¶\n&para;\n·\n&middot; &centerdot; &CenterDot;\n¸\n&cedil; &Cedilla;\n¹\n&sup1;\nº\n&ordm;\n»\n&raquo;\n¼\n&frac14;\n½\n&frac12; &half;\n¾\n&frac34;\n¿\n&iquest;\nÀ\n&Agrave;\nÁ\n&Aacute;\nÂ\n&Acirc;\nÃ\n&Atilde;\nÄ\n&Auml;\nÅ\n&Aring;\nÆ\n&AElig;\nÇ\n&Ccedil;\nÈ\n&Egrave;\nÉ\n&Eacute;\nÊ\n&Ecirc;\nË\n&Euml;\nÌ\n&Igrave;\nÍ\n&Iacute;\nÎ\n&Icirc;\nÏ\n&Iuml;\nÐ\n&ETH;\nÑ\n&Ntilde;\nÒ\n&Ograve;\nÓ\n&Oacute;\nÔ\n&Ocirc;\nÕ\n&Otilde;\nÖ\n&Ouml;\n×\n&times;\nØ\n&Oslash;\nÙ\n&Ugrave;\nÚ\n&Uacute;\nÛ\n&Ucirc;\nÜ\n&Uuml;\nÝ\n&Yacute;\nÞ\n&THORN;\nß\n&szlig;\nà\n&agrave;\ná\n&aacute;\nâ\n&acirc;\nã\n&atilde;\nä\n&auml;\nå\n&aring;\næ\n&aelig;\nç\n&ccedil;\nè\n&egrave;\né\n&eacute;\nê\n&ecirc;\në\n&euml;\nì\n&igrave;\ní\n&iacute;\nî\n&icirc;\nï\n&iuml;\nð\n&eth;\nñ\n&ntilde;\nò\n&ograve;\nó\n&oacute;\nô\n&ocirc;\nõ\n&otilde;\nö\n&ouml;\n÷\n&divide; &div;\nø\n&oslash;\nù\n&ugrave;\nú\n&uacute;\nû\n&ucirc;\nü\n&uuml;\ný\n&yacute;\nþ\n&thorn;\nÿ\n&yuml;\nĀ\n&Amacr;\nā\n&amacr;\nĂ\n&Abreve;\nă\n&abreve;\nĄ\n&Aogon;\ną\n&aogon;\nĆ\n&Cacute;\nć\n&cacute;\nĈ\n&Ccirc;\nĉ\n&ccirc;\nĊ\n&Cdot;\nċ\n&cdot;\nČ\n&Ccaron;\nč\n&ccaron;\nĎ\n&Dcaron;\nď\n&dcaron;\nĐ\n&Dstrok;\nđ\n&dstrok;\nĒ\n&Emacr;\nē\n&emacr;\nĖ\n&Edot;\nė\n&edot;\nĘ\n&Eogon;\nę\n&eogon;\nĚ\n&Ecaron;\ně\n&ecaron;\nĜ\n&Gcirc;\nĝ\n&gcirc;\nĞ\n&Gbreve;\nğ\n&gbreve;\nĠ\n&Gdot;\nġ\n&gdot;\nĢ\n&Gcedil;\nĤ\n&Hcirc;\nĥ\n&hcirc;\nĦ\n&Hstrok;\nħ\n&hstrok;\nĨ\n&Itilde;\nĩ\n&itilde;\nĪ\n&Imacr;\nī\n&imacr;\nĮ\n&Iogon;\nį\n&iogon;\nİ\n&Idot;\nı\n&imath; &inodot;\nIJ\n&IJlig;\nij\n&ijlig;\nĴ\n&Jcirc;\nĵ\n&jcirc;\nĶ\n&Kcedil;\nķ\n&kcedil;\nĸ\n&kgreen;\nĹ\n&Lacute;\nĺ\n&lacute;\nĻ\n&Lcedil;\nļ\n&lcedil;\nĽ\n&Lcaron;\nľ\n&lcaron;\nĿ\n&Lmidot;\nŀ\n&lmidot;\nŁ\n&Lstrok;\nł\n&lstrok;\nŃ\n&Nacute;\nń\n&nacute;\nŅ\n&Ncedil;\nņ\n&ncedil;\nŇ\n&Ncaron;\nň\n&ncaron;\nʼn\n&napos;\nŊ\n&ENG;\nŋ\n&eng;\nŌ\n&Omacr;\nō\n&omacr;\nŐ\n&Odblac;\nő\n&odblac;\nŒ\n&OElig;\nœ\n&oelig;\nŔ\n&Racute;\nŕ\n&racute;\nŖ\n&Rcedil;\nŗ\n&rcedil;\nŘ\n&Rcaron;\nř\n&rcaron;\nŚ\n&Sacute;\nś\n&sacute;\nŜ\n&Scirc;\nŝ\n&scirc;\nŞ\n&Scedil;\nş\n&scedil;\nŠ\n&Scaron;\nš\n&scaron;\nŢ\n&Tcedil;\nţ\n&tcedil;\nŤ\n&Tcaron;\nť\n&tcaron;\nŦ\n&Tstrok;\nŧ\n&tstrok;\nŨ\n&Utilde;\nũ\n&utilde;\nŪ\n&Umacr;\nū\n&umacr;\nŬ\n&Ubreve;\nŭ\n&ubreve;\nŮ\n&Uring;\nů\n&uring;\nŰ\n&Udblac;\nű\n&udblac;\nŲ\n&Uogon;\nų\n&uogon;\nŴ\n&Wcirc;\nŵ\n&wcirc;\nŶ\n&Ycirc;\nŷ\n&ycirc;\nŸ\n&Yuml;\nŹ\n&Zacute;\nź\n&zacute;\nŻ\n&Zdot;\nż\n&zdot;\nŽ\n&Zcaron;\nž\n&zcaron;\nƒ\n&fnof;\nƵ\n&imped;\nǵ\n&gacute;\nȷ\n&jmath;\nˆ\n&circ;\nˇ\n&caron; &Hacek;\n˘\n&breve; &Breve;\n˙\n&dot; &DiacriticalDot;\n˚\n&ring;\n˛\n&ogon;\n˜\n&tilde; &DiacriticalTilde;\n˝\n&dblac; &DiacriticalDoubleAcute;\n̑\n&DownBreve;\n̲\n&UnderBar;\nΑ\n&Alpha;\nΒ\n&Beta;\nΓ\n&Gamma;\nΔ\n&Delta;\nΕ\n&Epsilon;\nΖ\n&Zeta;\nΗ\n&Eta;\nΘ\n&Theta;\nΙ\n&Iota;\nΚ\n&Kappa;\nΛ\n&Lambda;\nΜ\n&Mu;\nΝ\n&Nu;\nΞ\n&Xi;\nΟ\n&Omicron;\nΠ\n&Pi;\nΡ\n&Rho;\nΣ\n&Sigma;\nΤ\n&Tau;\nΥ\n&Upsilon;\nΦ\n&Phi;\nΧ\n&Chi;\nΨ\n&Psi;\nΩ\n&Omega;\nα\n&alpha;\nβ\n&beta;\nγ\n&gamma;\nδ\n&delta;\nε\n&epsiv; &varepsilon; &epsilon;\nζ\n&zeta;\nη\n&eta;\nθ\n&theta;\nι\n&iota;\nκ\n&kappa;\nλ\n&lambda;\nμ\n&mu;\nν\n&nu;\nξ\n&xi;\nο\n&omicron;\nπ\n&pi;\nρ\n&rho;\nς\n&sigmav; &varsigma; &sigmaf;\nσ\n&sigma;\nτ\n&tau;\nυ\n&upsi; &upsilon;\nφ\n&phi; &phiv; &varphi;\nχ\n&chi;\nψ\n&psi;\nω\n&omega;\nϑ\n&thetav; &vartheta; &thetasym;\nϒ\n&Upsi; &upsih;\nϕ\n&straightphi;\nϖ\n&piv; &varpi;\nϜ\n&Gammad;\nϝ\n&gammad; &digamma;\nϰ\n&kappav; &varkappa;\nϱ\n&rhov; &varrho;\nϵ\n&epsi; &straightepsilon;\n϶\n&bepsi; &backepsilon;\nЁ\n&IOcy;\nЂ\n&DJcy;\nЃ\n&GJcy;\nЄ\n&Jukcy;\nЅ\n&DScy;\nІ\n&Iukcy;\nЇ\n&YIcy;\nЈ\n&Jsercy;\nЉ\n&LJcy;\nЊ\n&NJcy;\nЋ\n&TSHcy;\nЌ\n&KJcy;\nЎ\n&Ubrcy;\nЏ\n&DZcy;\nА\n&Acy;\nБ\n&Bcy;\nВ\n&Vcy;\nГ\n&Gcy;\nД\n&Dcy;\nЕ\n&IEcy;\nЖ\n&ZHcy;\nЗ\n&Zcy;\nИ\n&Icy;\nЙ\n&Jcy;\nК\n&Kcy;\nЛ\n&Lcy;\nМ\n&Mcy;\nН\n&Ncy;\nО\n&Ocy;\nП\n&Pcy;\nР\n&Rcy;\nС\n&Scy;\nТ\n&Tcy;\nУ\n&Ucy;\nФ\n&Fcy;\nХ\n&KHcy;\nЦ\n&TScy;\nЧ\n&CHcy;\nШ\n&SHcy;\nЩ\n&SHCHcy;\nЪ\n&HARDcy;\nЫ\n&Ycy;\nЬ\n&SOFTcy;\nЭ\n&Ecy;\nЮ\n&YUcy;\nЯ\n&YAcy;\nа\n&acy;\nб\n&bcy;\nв\n&vcy;\nг\n&gcy;\nд\n&dcy;\nе\n&iecy;\nж\n&zhcy;\nз\n&zcy;\nи\n&icy;\nй\n&jcy;\nк\n&kcy;\nл\n&lcy;\nм\n&mcy;\nн\n&ncy;\nо\n&ocy;\nп\n&pcy;\nр\n&rcy;\nс\n&scy;\nт\n&tcy;\nу\n&ucy;\nф\n&fcy;\nх\n&khcy;\nц\n&tscy;\nч\n&chcy;\nш\n&shcy;\nщ\n&shchcy;\nъ\n&hardcy;\nы\n&ycy;\nь\n&softcy;\nэ\n&ecy;\nю\n&yucy;\nя\n&yacy;\nё\n&iocy;\nђ\n&djcy;\nѓ\n&gjcy;\nє\n&jukcy;\nѕ\n&dscy;\nі\n&iukcy;\nї\n&yicy;\nј\n&jsercy;\nљ\n&ljcy;\nњ\n&njcy;\nћ\n&tshcy;\nќ\n&kjcy;\nў\n&ubrcy;\nџ\n&dzcy;\n \n&ensp;\n \n&emsp;\n \n&emsp13;\n \n&emsp14;\n \n&numsp;\n \n&puncsp;\n \n&thinsp; &ThinSpace;\n \n&hairsp; &VeryThinSpace;\n​\n&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;\n‌\n&zwnj;\n‍\n&zwj;\n‎\n&lrm;\n‏\n&rlm;\n‐\n&hyphen; &dash;\n–\n&ndash;\n—\n&mdash;\n―\n&horbar;\n‖\n&Verbar; &Vert;\n‘\n&lsquo; &OpenCurlyQuote;\n’\n&rsquo; &rsquor; &CloseCurlyQuote;\n‚\n&lsquor; &sbquo;\n“\n&ldquo; &OpenCurlyDoubleQuote;\n”\n&rdquo; &rdquor; &CloseCurlyDoubleQuote;\n„\n&ldquor; &bdquo;\n†\n&dagger;\n‡\n&Dagger; &ddagger;\n•\n&bull; &bullet;\n‥\n&nldr;\n…\n&hellip; &mldr;\n‰\n&permil;\n‱\n&pertenk;\n′\n&prime;\n″\n&Prime;\n‴\n&tprime;\n‵\n&bprime; &backprime;\n‹\n&lsaquo;\n›\n&rsaquo;\n‾\n&oline;\n⁁\n&caret;\n⁃\n&hybull;\n⁄\n&frasl;\n⁏\n&bsemi;\n⁗\n&qprime;\n \n&MediumSpace;\n⁠\n&NoBreak;\n⁡\n&ApplyFunction; &af;\n⁢\n&InvisibleTimes; &it;\n⁣\n&InvisibleComma; &ic;\n€\n&euro;\n⃛\n&tdot; &TripleDot;\n⃜\n&DotDot;\nℂ\n&Copf; &complexes;\n℅\n&incare;\nℊ\n&gscr;\nℋ\n&hamilt; &HilbertSpace; &Hscr;\nℌ\n&Hfr; &Poincareplane;\nℍ\n&quaternions; &Hopf;\nℎ\n&planckh;\nℏ\n&planck; &hbar; &plankv; &hslash;\nℐ\n&Iscr; &imagline;\nℑ\n&image; &Im; &imagpart; &Ifr;\nℒ\n&Lscr; &lagran; &Laplacetrf;\nℓ\n&ell;\nℕ\n&Nopf; &naturals;\n№\n&numero;\n℗\n&copysr;\n℘\n&weierp; &wp;\nℙ\n&Popf; &primes;\nℚ\n&rationals; &Qopf;\nℛ\n&Rscr; &realine;\nℜ\n&real; &Re; &realpart; &Rfr;\nℝ\n&reals; &Ropf;\n℞\n&rx;\n™\n&trade; &TRADE;\nℤ\n&integers; &Zopf;\nΩ\n&ohm;\n℧\n&mho;\nℨ\n&Zfr; &zeetrf;\n℩\n&iiota;\nÅ\n&angst;\nℬ\n&bernou; &Bernoullis; &Bscr;\nℭ\n&Cfr; &Cayleys;\nℯ\n&escr;\nℰ\n&Escr; &expectation;\nℱ\n&Fscr; &Fouriertrf;\nℳ\n&phmmat; &Mellintrf; &Mscr;\nℴ\n&order; &orderof; &oscr;\nℵ\n&alefsym; &aleph;\nℶ\n&beth;\nℷ\n&gimel;\nℸ\n&daleth;\nⅅ\n&CapitalDifferentialD; &DD;\nⅆ\n&DifferentialD; &dd;\nⅇ\n&ExponentialE; &exponentiale; &ee;\nⅈ\n&ImaginaryI; &ii;\n⅓\n&frac13;\n⅔\n&frac23;\n⅕\n&frac15;\n⅖\n&frac25;\n⅗\n&frac35;\n⅘\n&frac45;\n⅙\n&frac16;\n⅚\n&frac56;\n⅛\n&frac18;\n⅜\n&frac38;\n⅝\n&frac58;\n⅞\n&frac78;\n←\n&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;\n↑\n&uarr; &uparrow; &UpArrow; &ShortUpArrow;\n→\n&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;\n↓\n&darr; &downarrow; &DownArrow; &ShortDownArrow;\n↔\n&harr; &leftrightarrow; &LeftRightArrow;\n↕\n&varr; &updownarrow; &UpDownArrow;\n↖\n&nwarr; &UpperLeftArrow; &nwarrow;\n↗\n&nearr; &UpperRightArrow; &nearrow;\n↘\n&searr; &searrow; &LowerRightArrow;\n↙\n&swarr; &swarrow; &LowerLeftArrow;\n↚\n&nlarr; &nleftarrow;\n↛\n&nrarr; &nrightarrow;\n↝\n&rarrw; &rightsquigarrow;\n↞\n&Larr; &twoheadleftarrow;\n↟\n&Uarr;\n↠\n&Rarr; &twoheadrightarrow;\n↡\n&Darr;\n↢\n&larrtl; &leftarrowtail;\n↣\n&rarrtl; &rightarrowtail;\n↤\n&LeftTeeArrow; &mapstoleft;\n↥\n&UpTeeArrow; &mapstoup;\n↦\n&map; &RightTeeArrow; &mapsto;\n↧\n&DownTeeArrow; &mapstodown;\n↩\n&larrhk; &hookleftarrow;\n↪\n&rarrhk; &hookrightarrow;\n↫\n&larrlp; &looparrowleft;\n↬\n&rarrlp; &looparrowright;\n↭\n&harrw; &leftrightsquigarrow;\n↮\n&nharr; &nleftrightarrow;\n↰\n&lsh; &Lsh;\n↱\n&rsh; &Rsh;\n↲\n&ldsh;\n↳\n&rdsh;\n↵\n&crarr;\n↶\n&cularr; &curvearrowleft;\n↷\n&curarr; &curvearrowright;\n↺\n&olarr; &circlearrowleft;\n↻\n&orarr; &circlearrowright;\n↼\n&lharu; &LeftVector; &leftharpoonup;\n↽\n&lhard; &leftharpoondown; &DownLeftVector;\n↾\n&uharr; &upharpoonright; &RightUpVector;\n↿\n&uharl; &upharpoonleft; &LeftUpVector;\n⇀\n&rharu; &RightVector; &rightharpoonup;\n⇁\n&rhard; &rightharpoondown; &DownRightVector;\n⇂\n&dharr; &RightDownVector; &downharpoonright;\n⇃\n&dharl; &LeftDownVector; &downharpoonleft;\n⇄\n&rlarr; &rightleftarrows; &RightArrowLeftArrow;\n⇅\n&udarr; &UpArrowDownArrow;\n⇆\n&lrarr; &leftrightarrows; &LeftArrowRightArrow;\n⇇\n&llarr; &leftleftarrows;\n⇈\n&uuarr; &upuparrows;\n⇉\n&rrarr; &rightrightarrows;\n⇊\n&ddarr; &downdownarrows;\n⇋\n&lrhar; &ReverseEquilibrium; &leftrightharpoons;\n⇌\n&rlhar; &rightleftharpoons; &Equilibrium;\n⇍\n&nlArr; &nLeftarrow;\n⇎\n&nhArr; &nLeftrightarrow;\n⇏\n&nrArr; &nRightarrow;\n⇐\n&lArr; &Leftarrow; &DoubleLeftArrow;\n⇑\n&uArr; &Uparrow; &DoubleUpArrow;\n⇒\n&rArr; &Rightarrow; &Implies; &DoubleRightArrow;\n⇓\n&dArr; &Downarrow; &DoubleDownArrow;\n⇔\n&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;\n⇕\n&vArr; &Updownarrow; &DoubleUpDownArrow;\n⇖\n&nwArr;\n⇗\n&neArr;\n⇘\n&seArr;\n⇙\n&swArr;\n⇚\n&lAarr; &Lleftarrow;\n⇛\n&rAarr; &Rrightarrow;\n⇝\n&zigrarr;\n⇤\n&larrb; &LeftArrowBar;\n⇥\n&rarrb; &RightArrowBar;\n⇵\n&duarr; &DownArrowUpArrow;\n⇽\n&loarr;\n⇾\n&roarr;\n⇿\n&hoarr;\n∀\n&forall; &ForAll;\n∁\n&comp; &complement;\n∂\n&part; &PartialD;\n∃\n&exist; &Exists;\n∄\n&nexist; &NotExists; &nexists;\n∅\n&empty; &emptyset; &emptyv; &varnothing;\n∇\n&nabla; &Del;\n∈\n&isin; &isinv; &Element; &in;\n∉\n&notin; &NotElement; &notinva;\n∋\n&niv; &ReverseElement; &ni; &SuchThat;\n∌\n&notni; &notniva; &NotReverseElement;\n∏\n&prod; &Product;\n∐\n&coprod; &Coproduct;\n∑\n&sum; &Sum;\n−\n&minus;\n∓\n&mnplus; &mp; &MinusPlus;\n∔\n&plusdo; &dotplus;\n∖\n&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;\n∗\n&lowast;\n∘\n&compfn; &SmallCircle;\n√\n&radic; &Sqrt;\n∝\n&prop; &propto; &Proportional; &vprop; &varpropto;\n∞\n&infin;\n∟\n&angrt;\n∠\n&ang; &angle;\n∡\n&angmsd; &measuredangle;\n∢\n&angsph;\n∣\n&mid; &VerticalBar; &smid; &shortmid;\n∤\n&nmid; &NotVerticalBar; &nsmid; &nshortmid;\n∥\n&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;\n∦\n&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;\n∧\n&and; &wedge;\n∨\n&or; &vee;\n∩\n&cap;\n∪\n&cup;\n∫\n&int; &Integral;\n∬\n&Int;\n∭\n&tint; &iiint;\n∮\n&conint; &oint; &ContourIntegral;\n∯\n&Conint; &DoubleContourIntegral;\n∰\n&Cconint;\n∱\n&cwint;\n∲\n&cwconint; &ClockwiseContourIntegral;\n∳\n&awconint; &CounterClockwiseContourIntegral;\n∴\n&there4; &therefore; &Therefore;\n∵\n&becaus; &because; &Because;\n∶\n&ratio;\n∷\n&Colon; &Proportion;\n∸\n&minusd; &dotminus;\n∺\n&mDDot;\n∻\n&homtht;\n∼\n&sim; &Tilde; &thksim; &thicksim;\n∽\n&bsim; &backsim;\n∾\n&ac; &mstpos;\n∿\n&acd;\n≀\n&wreath; &VerticalTilde; &wr;\n≁\n&nsim; &NotTilde;\n≂\n&esim; &EqualTilde; &eqsim;\n≃\n&sime; &TildeEqual; &simeq;\n≄\n&nsime; &nsimeq; &NotTildeEqual;\n≅\n&cong; &TildeFullEqual;\n≆\n&simne;\n≇\n&ncong; &NotTildeFullEqual;\n≈\n&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;\n≉\n&nap; &NotTildeTilde; &napprox;\n≊\n&ape; &approxeq;\n≋\n&apid;\n≌\n&bcong; &backcong;\n≍\n&asympeq; &CupCap;\n≎\n&bump; &HumpDownHump; &Bumpeq;\n≏\n&bumpe; &HumpEqual; &bumpeq;\n≐\n&esdot; &DotEqual; &doteq;\n≑\n&eDot; &doteqdot;\n≒\n&efDot; &fallingdotseq;\n≓\n&erDot; &risingdotseq;\n≔\n&colone; &coloneq; &Assign;\n≕\n&ecolon; &eqcolon;\n≖\n&ecir; &eqcirc;\n≗\n&cire; &circeq;\n≙\n&wedgeq;\n≚\n&veeeq;\n≜\n&trie; &triangleq;\n≟\n&equest; &questeq;\n≠\n&ne; &NotEqual;\n≡\n&equiv; &Congruent;\n≢\n&nequiv; &NotCongruent;\n≤\n&le; &leq;\n≥\n&ge; &GreaterEqual; &geq;\n≦\n&lE; &LessFullEqual; &leqq;\n≧\n&gE; &GreaterFullEqual; &geqq;\n≨\n&lnE; &lneqq;\n≩\n&gnE; &gneqq;\n≪\n&Lt; &NestedLessLess; &ll;\n≫\n&Gt; &NestedGreaterGreater; &gg;\n≬\n&twixt; &between;\n≭\n&NotCupCap;\n≮\n&nlt; &NotLess; &nless;\n≯\n&ngt; &NotGreater; &ngtr;\n≰\n&nle; &NotLessEqual; &nleq;\n≱\n&nge; &NotGreaterEqual; &ngeq;\n≲\n&lsim; &LessTilde; &lesssim;\n≳\n&gsim; &gtrsim; &GreaterTilde;\n≴\n&nlsim; &NotLessTilde;\n≵\n&ngsim; &NotGreaterTilde;\n≶\n&lg; &lessgtr; &LessGreater;\n≷\n&gl; &gtrless; &GreaterLess;\n≸\n&ntlg; &NotLessGreater;\n≹\n&ntgl; &NotGreaterLess;\n≺\n&pr; &Precedes; &prec;\n≻\n&sc; &Succeeds; &succ;\n≼\n&prcue; &PrecedesSlantEqual; &preccurlyeq;\n≽\n&sccue; &SucceedsSlantEqual; &succcurlyeq;\n≾\n&prsim; &precsim; &PrecedesTilde;\n≿\n&scsim; &succsim; &SucceedsTilde;\n⊀\n&npr; &nprec; &NotPrecedes;\n⊁\n&nsc; &nsucc; &NotSucceeds;\n⊂\n&sub; &subset;\n⊃\n&sup; &supset; &Superset;\n⊄\n&nsub;\n⊅\n&nsup;\n⊆\n&sube; &SubsetEqual; &subseteq;\n⊇\n&supe; &supseteq; &SupersetEqual;\n⊈\n&nsube; &nsubseteq; &NotSubsetEqual;\n⊉\n&nsupe; &nsupseteq; &NotSupersetEqual;\n⊊\n&subne; &subsetneq;\n⊋\n&supne; &supsetneq;\n⊍\n&cupdot;\n⊎\n&uplus; &UnionPlus;\n⊏\n&sqsub; &SquareSubset; &sqsubset;\n⊐\n&sqsup; &SquareSuperset; &sqsupset;\n⊑\n&sqsube; &SquareSubsetEqual; &sqsubseteq;\n⊒\n&sqsupe; &SquareSupersetEqual; &sqsupseteq;\n⊓\n&sqcap; &SquareIntersection;\n⊔\n&sqcup; &SquareUnion;\n⊕\n&oplus; &CirclePlus;\n⊖\n&ominus; &CircleMinus;\n⊗\n&otimes; &CircleTimes;\n⊘\n&osol;\n⊙\n&odot; &CircleDot;\n⊚\n&ocir; &circledcirc;\n⊛\n&oast; &circledast;\n⊝\n&odash; &circleddash;\n⊞\n&plusb; &boxplus;\n⊟\n&minusb; &boxminus;\n⊠\n&timesb; &boxtimes;\n⊡\n&sdotb; &dotsquare;\n⊢\n&vdash; &RightTee;\n⊣\n&dashv; &LeftTee;\n⊤\n&top; &DownTee;\n⊥\n&bottom; &bot; &perp; &UpTee;\n⊧\n&models;\n⊨\n&vDash; &DoubleRightTee;\n⊩\n&Vdash;\n⊪\n&Vvdash;\n⊫\n&VDash;\n⊬\n&nvdash;\n⊭\n&nvDash;\n⊮\n&nVdash;\n⊯\n&nVDash;\n⊰\n&prurel;\n⊲\n&vltri; &vartriangleleft; &LeftTriangle;\n⊳\n&vrtri; &vartriangleright; &RightTriangle;\n⊴\n&ltrie; &trianglelefteq; &LeftTriangleEqual;\n⊵\n&rtrie; &trianglerighteq; &RightTriangleEqual;\n⊶\n&origof;\n⊷\n&imof;\n⊸\n&mumap; &multimap;\n⊹\n&hercon;\n⊺\n&intcal; &intercal;\n⊻\n&veebar;\n⊽\n&barvee;\n⊾\n&angrtvb;\n⊿\n&lrtri;\n⋀\n&xwedge; &Wedge; &bigwedge;\n⋁\n&xvee; &Vee; &bigvee;\n⋂\n&xcap; &Intersection; &bigcap;\n⋃\n&xcup; &Union; &bigcup;\n⋄\n&diam; &diamond; &Diamond;\n⋅\n&sdot;\n⋆\n&sstarf; &Star;\n⋇\n&divonx; &divideontimes;\n⋈\n&bowtie;\n⋉\n&ltimes;\n⋊\n&rtimes;\n⋋\n&lthree; &leftthreetimes;\n⋌\n&rthree; &rightthreetimes;\n⋍\n&bsime; &backsimeq;\n⋎\n&cuvee; &curlyvee;\n⋏\n&cuwed; &curlywedge;\n⋐\n&Sub; &Subset;\n⋑\n&Sup; &Supset;\n⋒\n&Cap;\n⋓\n&Cup;\n⋔\n&fork; &pitchfork;\n⋕\n&epar;\n⋖\n&ltdot; &lessdot;\n⋗\n&gtdot; &gtrdot;\n⋘\n&Ll;\n⋙\n&Gg; &ggg;\n⋚\n&leg; &LessEqualGreater; &lesseqgtr;\n⋛\n&gel; &gtreqless; &GreaterEqualLess;\n⋞\n&cuepr; &curlyeqprec;\n⋟\n&cuesc; &curlyeqsucc;\n⋠\n&nprcue; &NotPrecedesSlantEqual;\n⋡\n&nsccue; &NotSucceedsSlantEqual;\n⋢\n&nsqsube; &NotSquareSubsetEqual;\n⋣\n&nsqsupe; &NotSquareSupersetEqual;\n⋦\n&lnsim;\n⋧\n&gnsim;\n⋨\n&prnsim; &precnsim;\n⋩\n&scnsim; &succnsim;\n⋪\n&nltri; &ntriangleleft; &NotLeftTriangle;\n⋫\n&nrtri; &ntriangleright; &NotRightTriangle;\n⋬\n&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;\n⋭\n&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;\n⋮\n&vellip;\n⋯\n&ctdot;\n⋰\n&utdot;\n⋱\n&dtdot;\n⋲\n&disin;\n⋳\n&isinsv;\n⋴\n&isins;\n⋵\n&isindot;\n⋶\n&notinvc;\n⋷\n&notinvb;\n⋹\n&isinE;\n⋺\n&nisd;\n⋻\n&xnis;\n⋼\n&nis;\n⋽\n&notnivc;\n⋾\n&notnivb;\n⌅\n&barwed; &barwedge;\n⌆\n&Barwed; &doublebarwedge;\n⌈\n&lceil; &LeftCeiling;\n⌉\n&rceil; &RightCeiling;\n⌊\n&lfloor; &LeftFloor;\n⌋\n&rfloor; &RightFloor;\n⌌\n&drcrop;\n⌍\n&dlcrop;\n⌎\n&urcrop;\n⌏\n&ulcrop;\n⌐\n&bnot;\n⌒\n&profline;\n⌓\n&profsurf;\n⌕\n&telrec;\n⌖\n&target;\n⌜\n&ulcorn; &ulcorner;\n⌝\n&urcorn; &urcorner;\n⌞\n&dlcorn; &llcorner;\n⌟\n&drcorn; &lrcorner;\n⌢\n&frown; &sfrown;\n⌣\n&smile; &ssmile;\n⌭\n&cylcty;\n⌮\n&profalar;\n⌶\n&topbot;\n⌽\n&ovbar;\n⌿\n&solbar;\n⍼\n&angzarr;\n⎰\n&lmoust; &lmoustache;\n⎱\n&rmoust; &rmoustache;\n⎴\n&tbrk; &OverBracket;\n⎵\n&bbrk; &UnderBracket;\n⎶\n&bbrktbrk;\n⏜\n&OverParenthesis;\n⏝\n&UnderParenthesis;\n⏞\n&OverBrace;\n⏟\n&UnderBrace;\n⏢\n&trpezium;\n⏧\n&elinters;\n␣\n&blank;\nⓈ\n&oS; &circledS;\n─\n&boxh; &HorizontalLine;\n│\n&boxv;\n┌\n&boxdr;\n┐\n&boxdl;\n└\n&boxur;\n┘\n&boxul;\n├\n&boxvr;\n┤\n&boxvl;\n┬\n&boxhd;\n┴\n&boxhu;\n┼\n&boxvh;\n═\n&boxH;\n║\n&boxV;\n╒\n&boxdR;\n╓\n&boxDr;\n╔\n&boxDR;\n╕\n&boxdL;\n╖\n&boxDl;\n╗\n&boxDL;\n╘\n&boxuR;\n╙\n&boxUr;\n╚\n&boxUR;\n╛\n&boxuL;\n╜\n&boxUl;\n╝\n&boxUL;\n╞\n&boxvR;\n╟\n&boxVr;\n╠\n&boxVR;\n╡\n&boxvL;\n╢\n&boxVl;\n╣\n&boxVL;\n╤\n&boxHd;\n╥\n&boxhD;\n╦\n&boxHD;\n╧\n&boxHu;\n╨\n&boxhU;\n╩\n&boxHU;\n╪\n&boxvH;\n╫\n&boxVh;\n╬\n&boxVH;\n▀\n&uhblk;\n▄\n&lhblk;\n█\n&block;\n░\n&blk14;\n▒\n&blk12;\n▓\n&blk34;\n□\n&squ; &square; &Square;\n▪\n&squf; &squarf; &blacksquare; &FilledVerySmallSquare;\n▫\n&EmptyVerySmallSquare;\n▭\n&rect;\n▮\n&marker;\n▱\n&fltns;\n△\n&xutri; &bigtriangleup;\n▴\n&utrif; &blacktriangle;\n▵\n&utri; &triangle;\n▸\n&rtrif; &blacktriangleright;\n▹\n&rtri; &triangleright;\n▽\n&xdtri; &bigtriangledown;\n▾\n&dtrif; &blacktriangledown;\n▿\n&dtri; &triangledown;\n◂\n&ltrif; &blacktriangleleft;\n◃\n&ltri; &triangleleft;\n◊\n&loz; &lozenge;\n○\n&cir;\n◬\n&tridot;\n◯\n&xcirc; &bigcirc;\n◸\n&ultri;\n◹\n&urtri;\n◺\n&lltri;\n◻\n&EmptySmallSquare;\n◼\n&FilledSmallSquare;\n★\n&starf; &bigstar;\n☆\n&star;\n☎\n&phone;\n♀\n&female;\n♂\n&male;\n♠\n&spades; &spadesuit;\n♣\n&clubs; &clubsuit;\n♥\n&hearts; &heartsuit;\n♦\n&diams; &diamondsuit;\n♪\n&sung;\n♭\n&flat;\n♮\n&natur; &natural;\n♯\n&sharp;\n✓\n&check; &checkmark;\n✗\n&cross;\n✠\n&malt; &maltese;\n✶\n&sext;\n❘\n&VerticalSeparator;\n❲\n&lbbrk;\n❳\n&rbbrk;\n⟦\n&lobrk; &LeftDoubleBracket;\n⟧\n&robrk; &RightDoubleBracket;\n⟨\n&lang; &LeftAngleBracket; &langle;\n⟩\n&rang; &RightAngleBracket; &rangle;\n⟪\n&Lang;\n⟫\n&Rang;\n⟬\n&loang;\n⟭\n&roang;\n⟵\n&xlarr; &longleftarrow; &LongLeftArrow;\n⟶\n&xrarr; &longrightarrow; &LongRightArrow;\n⟷\n&xharr; &longleftrightarrow; &LongLeftRightArrow;\n⟸\n&xlArr; &Longleftarrow; &DoubleLongLeftArrow;\n⟹\n&xrArr; &Longrightarrow; &DoubleLongRightArrow;\n⟺\n&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;\n⟼\n&xmap; &longmapsto;\n⟿\n&dzigrarr;\n⤂\n&nvlArr;\n⤃\n&nvrArr;\n⤄\n&nvHarr;\n⤅\n&Map;\n⤌\n&lbarr;\n⤍\n&rbarr; &bkarow;\n⤎\n&lBarr;\n⤏\n&rBarr; &dbkarow;\n⤐\n&RBarr; &drbkarow;\n⤑\n&DDotrahd;\n⤒\n&UpArrowBar;\n⤓\n&DownArrowBar;\n⤖\n&Rarrtl;\n⤙\n&latail;\n⤚\n&ratail;\n⤛\n&lAtail;\n⤜\n&rAtail;\n⤝\n&larrfs;\n⤞\n&rarrfs;\n⤟\n&larrbfs;\n⤠\n&rarrbfs;\n⤣\n&nwarhk;\n⤤\n&nearhk;\n⤥\n&searhk; &hksearow;\n⤦\n&swarhk; &hkswarow;\n⤧\n&nwnear;\n⤨\n&nesear; &toea;\n⤩\n&seswar; &tosa;\n⤪\n&swnwar;\n⤳\n&rarrc;\n⤵\n&cudarrr;\n⤶\n&ldca;\n⤷\n&rdca;\n⤸\n&cudarrl;\n⤹\n&larrpl;\n⤼\n&curarrm;\n⤽\n&cularrp;\n⥅\n&rarrpl;\n⥈\n&harrcir;\n⥉\n&Uarrocir;\n⥊\n&lurdshar;\n⥋\n&ldrushar;\n⥎\n&LeftRightVector;\n⥏\n&RightUpDownVector;\n⥐\n&DownLeftRightVector;\n⥑\n&LeftUpDownVector;\n⥒\n&LeftVectorBar;\n⥓\n&RightVectorBar;\n⥔\n&RightUpVectorBar;\n⥕\n&RightDownVectorBar;\n⥖\n&DownLeftVectorBar;\n⥗\n&DownRightVectorBar;\n⥘\n&LeftUpVectorBar;\n⥙\n&LeftDownVectorBar;\n⥚\n&LeftTeeVector;\n⥛\n&RightTeeVector;\n⥜\n&RightUpTeeVector;\n⥝\n&RightDownTeeVector;\n⥞\n&DownLeftTeeVector;\n⥟\n&DownRightTeeVector;\n⥠\n&LeftUpTeeVector;\n⥡\n&LeftDownTeeVector;\n⥢\n&lHar;\n⥣\n&uHar;\n⥤\n&rHar;\n⥥\n&dHar;\n⥦\n&luruhar;\n⥧\n&ldrdhar;\n⥨\n&ruluhar;\n⥩\n&rdldhar;\n⥪\n&lharul;\n⥫\n&llhard;\n⥬\n&rharul;\n⥭\n&lrhard;\n⥮\n&udhar; &UpEquilibrium;\n⥯\n&duhar; &ReverseUpEquilibrium;\n⥰\n&RoundImplies;\n⥱\n&erarr;\n⥲\n&simrarr;\n⥳\n&larrsim;\n⥴\n&rarrsim;\n⥵\n&rarrap;\n⥶\n&ltlarr;\n⥸\n&gtrarr;\n⥹\n&subrarr;\n⥻\n&suplarr;\n⥼\n&lfisht;\n⥽\n&rfisht;\n⥾\n&ufisht;\n⥿\n&dfisht;\n⦅\n&lopar;\n⦆\n&ropar;\n⦋\n&lbrke;\n⦌\n&rbrke;\n⦍\n&lbrkslu;\n⦎\n&rbrksld;\n⦏\n&lbrksld;\n⦐\n&rbrkslu;\n⦑\n&langd;\n⦒\n" }, { "answer_id": 52678432, "author": "N Randhawa", "author_id": 4854721, "author_profile": "https://Stackoverflow.com/users/4854721", "pm_score": 3, "selected": false, "text": "echo htmlspecialchars('An example <br>'); // This will print - An example &lt; br &gt;\necho htmlspecialchars('µ †'); // This will print - µ †\n echo htmlentities('An example <br>'); // This will print - An example &lt; br &gt;\necho htmlentities('µ †'); // This will print - &micro; &dagger; \n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4137/" ]
46,484
<p>Is there a way to use <code>JQuery</code> to cloak or encrypt email addresses on an <code>HTML</code> page without changing the syntax in the <code>href</code>?</p>
[ { "answer_id": 46558, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<a href=\"mailto:some_address^^some_domain$$com\" style='display:none'>Email me</a>\n ^^ @ $$ ." } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241/" ]
46,489
<p>In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using <code>ClientScriptManager.GetWebResourceUrl()</code>. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.</p> <pre><code>this.drophint = document.createElement('img'); this.drophint.src = '/_layouts/images/dragdrophint.gif'; </code></pre> <p>Could become something like:</p> <pre><code>this.drophint = document.createElement('img'); this.drophint.src = '{resource:assembly.location.dragdrophint.gif}'; </code></pre>
[ { "answer_id": 47242, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 3, "selected": true, "text": "StringBuilder script = new StringBuilder();\nscript.Append(\"var imgResources = {};\");\nscript.AppendFormat(\"imgResources['{0}'] = '{1}';\", \n \"drophint\", \n Page.ClientScript.GetWebResourceUrl(Page.GetType(), \"assembly.location.dragdrophint.gif\"));\nscript.AppendFormat(\"imgResources['{0}'] = '{1}';\", \n \"anotherimg\", \n Page.ClientScript.GetWebResourceUrl(Page.GetType(), \"assembly.location.anotherimg.gif\"));\n\nPage.ClientScript.RegisterClientScriptBlock(\n Page.GetType(),\n \"imgResources\",\n script.ToString(), \n true);\n this.drophint = document.createElement('img');\nthis.drophint.src = imgResources['drophint'];\nthis.anotherimg = document.createElement('img');\nthis.anotherimg.src = imgResources['anotherimg'];\n" }, { "answer_id": 47750, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 2, "selected": false, "text": "C# img id WebResourceUrl Dictionary<string, string> List<MyImageResourceClass> DataContractJsonSerializer img" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67/" ]
46,495
<p>Why can't you do this and is there are work around?</p> <p>You get this error.</p> <p>Msg 2714, Level 16, State 1, Line 13 There is already an object named '#temptable' in the database.</p> <pre><code>declare @x int set @x = 1 if (@x = 0) begin select 1 as Value into #temptable end else begin select 2 as Value into #temptable end select * from #temptable drop table #temptable </code></pre>
[ { "answer_id": 46565, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL \nBEGIN\nDROP TABLE #temptable\nEND\n\nCREATE TABLE #temptable (Value INT)\n\ndeclare @x int\n\nset @x = 1\n\nif (@x = 0)\nbegin\n INSERT INTO #temptable (Value) select 1\nend\nelse\nbegin\n INSERT INTO #temptable (Value) select 2\nend\n\nselect * from #temptable\n\ndrop table #temptable\n" }, { "answer_id": 147571, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 2, "selected": true, "text": "SELECT field-list INTO #symbol ...\n DECLARE #symbol_sessionid TABLE(field-list)\nINSERT INTO #symbol_sessionid SELECT field-list ...\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184/" ]
46,496
<p>Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?</p>
[ { "answer_id": 130390, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "sentence: for(Sentence sentence: paragraph) {\n for(String word: sentence) {\n // do something\n if(isDone()) {\n continue sentence;\n }\n }\n}\n" }, { "answer_id": 479629, "author": "Ceilingfish", "author_id": 58991, "author_profile": "https://Stackoverflow.com/users/58991", "pm_score": 3, "selected": false, "text": "\nnextItem: for(CartItem item : user.getCart()) {\n\n nextCondition : for(PurchaseCondition cond : item.getConditions()) {\n if(!cond.check())\n continue nextItem;\n else\n continue nextCondition;\n\n }\n purchasedItems.add(item);\n}\n" }, { "answer_id": 481514, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 5, "selected": false, "text": "class MyFirstJavaProg { \n public static void main(String args[]) {\n http://www.javacoffeebreak.com/java101/java101.html\n System.out.println(\"Hello World!\");\n }\n}\n" }, { "answer_id": 2676495, "author": "Selenia", "author_id": 321444, "author_profile": "https://Stackoverflow.com/users/321444", "pm_score": 3, "selected": false, "text": "private static void testByFactoring() {\n primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {\n int toTest = m_toFactor[ctr];\n for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {\n // max (int) Math.sqrt(m_numberToTest) + 1 iterations\n if (toTest != m_divisors[ctr2]\n && toTest % m_divisors[ctr2] == 0) {\n continue primes; \n }\n } // end of the divisor loop\n } // end of primes loop\n} // method\n" }, { "answer_id": 40549383, "author": "polaretto", "author_id": 255931, "author_profile": "https://Stackoverflow.com/users/255931", "pm_score": 1, "selected": false, "text": "@Test\npublic void should_Clear_Cached_Element() throws Exception {\n given: {\n elementStream = defaultStream();\n elementStream.readElement();\n Assume.assumeNotNull(elementStream.lastRead());\n }\n when:\n elementStream.clearLast();\n then:\n assertThat(elementStream.lastRead()).isEmpty();\n}\n" }, { "answer_id": 69244209, "author": "Yassir Khaldi", "author_id": 5517465, "author_profile": "https://Stackoverflow.com/users/5517465", "pm_score": 0, "selected": false, "text": " private static boolean exists(int[][] array, int searchFor) {\n for (int[] nums : array) {\n for (int num : nums) {\n if (num == searchFor) {\n return true;\n }\n }\n }\n return false;\n }\n boolean exists = false;\nexistenceLoop:\nfor (int[] nums : array) {\n for (int num : nums) {\n if (num == searchFor) {\n exists = true;\n break existenceLoop;\n }\n }\n}\n\nreturn exists;\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628/" ]
46,512
<p>In the build log I'd like to the start and end time of each project's compilation. Is there any way to get VS to do this?</p>
[ { "answer_id": 3312614, "author": "Glennular", "author_id": 14753, "author_profile": "https://Stackoverflow.com/users/14753", "pm_score": 3, "selected": false, "text": "Time TIME /T\n" }, { "answer_id": 22603785, "author": "Denis Palnitsky", "author_id": 238123, "author_profile": "https://Stackoverflow.com/users/238123", "pm_score": 5, "selected": false, "text": "Tools -> Options -> Projects and Solutions -> Build and Run -> \n MSBuild project build output verbosity Normal ------ Build started: MyProject, Configuration: Debug x86 ------\nBuild started 24/03/2014 08:46:18.\n...\nBuild succeeded.\n\nTime Elapsed 00:00:05.18\n" }, { "answer_id": 62820002, "author": "DarrenMB", "author_id": 813266, "author_profile": "https://Stackoverflow.com/users/813266", "pm_score": 0, "selected": false, "text": "dim out : Set out = WScript.StdOut\nSet objShell = WScript.CreateObject(\"WScript.Shell\")\ndim regDir: regDir=\"HKEY_CURRENT_USER\\Software\\VB and VBA Program Settings\\GetTime.vbs\\\"\ndim msg: msg=\"\"\ndim s: s=\"\"\ndim e: e=\"\"\ndim st:st=\"\"\n' param s is start flag keyed to the application being built.\nif wscript.arguments.named.exists(\"s\") then\n s = wscript.arguments.named(\"s\")\n objShell.RegWrite regdir & s,now\nend if\nif wscript.arguments.named.exists(\"e\") then\n e = wscript.arguments.named(\"e\")\n st = cdate(objShell.RegRead(regDir & e))\nend if \n\nif e<>\"\" and isdate(st) then\n out.writeline e & \" ENDED \" & now & \" ELAPSED \" & datediff(\"s\",cdate(st),now) & \" seconds\"\nelseif e<>\"\" then\n out.writeline e & \" ENDED \" & now\nelseif s<>\"\" then\n out.writeline s & \" STARTED \" & now\nelse\n out.writeline now\nend if \n cscript \"../../../../Scorecards/gettime.vbs\" //B /s:\"$(ProjectName)\"\n cscript \"../../../../Scorecards/gettime.vbs\" //B /e:\"$(ProjectName)\"\n 2> OPResources STARTED 7/9/2020 12:59:04 PM\n2> ...\n2> OPResources ENDED 7/9/2020 12:59:05 PM ELAPSED 1 seconds\n1> OPLib_WF STARTED 7/9/2020 12:59:04 PM\n1> ...\n1> OPLib_WF ENDED 7/9/2020 12:59:05 PM ELAPSED 1 seconds\n4>------ Rebuild All started: Project: OPLib, Configuration: Debug Any CPU ------\n4> OPLib STARTED 7/9/2020 12:59:06 PM\n4> ...\n4> OPLib ENDED 7/9/2020 12:59:10 PM ELAPSED 4 seconds\n5>------ Rebuild All started: Project: PerfUpdater, Configuration: Debug Any CPU ------\n6>------ Rebuild All started: Project: Scorecards2, Configuration: Debug Any CPU ------\n7>------ Rebuild All started: Project: SingleSignOn, Configuration: Debug Any CPU ------\n7> SingleSignOn STARTED 7/9/2020 12:59:10 PM\n7> ...\n7> SingleSignOn ENDED 7/9/2020 12:59:12 PM ELAPSED 2 seconds\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
46,529
<p>I have a WebChartControl on my web page. When the chart was generated, an image is being produced and it was shown on the page. </p> <p>Is there a way to get and save this chart as an image output on runtime? </p>
[ { "answer_id": 283130, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " Dim chart As ChartControl = ChartControl1.Clone()\n chart.Size = New Size(800, 600)\n chart.ExportToImage(\"file.png\", System.Drawing.Imaging.ImageFormat.Png)\n" }, { "answer_id": 1809828, "author": "Martin Bell", "author_id": 220160, "author_profile": "https://Stackoverflow.com/users/220160", "pm_score": 1, "selected": false, "text": "((IChartContainer)[Your web chart control]).Chart.ExportToImage([Your file name], ImageFormat.Png);\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
46,532
<p>If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent?</p> <p>In other words, if I have the following XML:</p> <pre><code>&lt;parent xmlns:foo="abc"&gt; &lt;foo:child /&gt; &lt;/parent&gt; </code></pre> <p>and I remove the child element, will the child element's xml look like</p> <pre><code>&lt;child xmlns="abc" /&gt; </code></pre> <p>or like </p> <pre><code>&lt;child /&gt; </code></pre>
[ { "answer_id": 283130, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " Dim chart As ChartControl = ChartControl1.Clone()\n chart.Size = New Size(800, 600)\n chart.ExportToImage(\"file.png\", System.Drawing.Imaging.ImageFormat.Png)\n" }, { "answer_id": 1809828, "author": "Martin Bell", "author_id": 220160, "author_profile": "https://Stackoverflow.com/users/220160", "pm_score": 1, "selected": false, "text": "((IChartContainer)[Your web chart control]).Chart.ExportToImage([Your file name], ImageFormat.Png);\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,541
<p>Name the design considerations in deciding between use of a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton</a> versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)</p>
[ { "answer_id": 46542, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": -1, "selected": false, "text": "RegistryEditor editor = RegistryEditor.GetInstance();\neditor.Hive = LocalMachine\n ReadSubkeyFromLocalMachine" }, { "answer_id": 46553, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 2, "selected": false, "text": "MySingleton().getInstance().doSomething();\n MySingleton.doSomething();\n" }, { "answer_id": 46567, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "mysqli mysqli" }, { "answer_id": 47027, "author": "Landon Kuhn", "author_id": 1785, "author_profile": "https://Stackoverflow.com/users/1785", "pm_score": 0, "selected": false, "text": "Foo foo = Foo.getInstance();\ndoSomeWork(foo); // doSomeWork wont even know Foo is a singleton\n" }, { "answer_id": 47037, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 2, "selected": false, "text": "ObjectFactory.getInstance().makeObject();\n StringUtils.reverseString(\"Hello\");\nStringUtils.concat(\"Hello\", \"World\");\n" }, { "answer_id": 48896, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 3, "selected": false, "text": "/**\n * Grotty static semaphore\n **/\n public static class Ugly {\n\n private static int count;\n\n public synchronized static void increment(){\n count++;\n }\n\n public synchronized static void decrement(){\n count--;\n if( count<0 ) {\n count=0;\n }\n }\n\n public synchronized static boolean isClear(){\n return count==0; \n\n }\n }\n /**\n * Grotty static semaphore\n **/\n public static class LessUgly {\n private static LessUgly instance;\n\n private int count;\n\n private LessUgly(){\n }\n\n public static synchronized getInstance(){\n if( instance==null){\n instance = new LessUgly();\n }\n return instance;\n }\n public synchronized void increment(){\n count++;\n }\n\n public synchronized void decrement(){\n count--;\n if( count<0 ) {\n count=0;\n }\n }\n\n public synchronized boolean isClear(){\n return count==0; \n\n }\n }\n public static class LessUgly {\n private static Hashtable<String,LessUgly> session;\n private static FIFO<LessUgly> freePool = new FIFO<LessUgly>();\n private static final POOL_SIZE=5;\n private int count;\n\n private LessUgly(){\n }\n\n public static synchronized getInstance(){\n if( session==null){\n session = new Hashtable<String,LessUgly>(POOL_SIZE);\n for( int i=0; i < POOL_SIZE; i++){\n LessUgly instance = new LessUgly(); \n freePool.add( instance)\n }\n }\n LessUgly instance = session.get( Session.getSessionID());\n if( instance == null){\n instance = freePool.read();\n }\n if( instance==null){\n // TODO search sessions for expired ones. Return spares to the freePool. \n //FIXME took too long to write example in blog editor.\n }\n return instance;\n } \n" }, { "answer_id": 655587, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "MyStaticClass.GetInstance().DoSomething();\n MyStaticClass.DoSomething();\n var svc = new MyComplexServce(MyStaticClass.GetInstance());\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
46,545
<p>How do I do backups in MySQL? </p> <p>I'm hoping there'll be something better than just running mysqldump every "x" hours.</p> <p>Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup?</p> <p>Something like the DB log, where as long as the log doesn't die, you can restore up to the exact point where the DB died?</p> <p>Also, how do these things affect locking? I'd expect the online transactions to be locked for a while if I do a mysqldump.</p>
[ { "answer_id": 47353, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "mysqldump -u theuser -p mypassword thedatabase | gzip -9 - | gpg -e -r 12345 -r 23456 > 2008_01_02.tar.gz.gpg #!/usr/bin/env python\n#encoding:utf-8\n#\n# Creates a GPG encrypted web and database backups, and emails it\n\nimport os, sys, time, commands\n\n################################################\n### Config\n\nDATE = time.strftime(\"%Y-%m-%d_%H-%M\")\n\n# MySQL login\nSQL_USER = \"mysqluser\"\nSQL_PASS = \"mysqlpassword\"\nSQL_DB = \"databasename\"\n\n# Email addresses\nBACKUP_EMAIL=[\"[email protected]\", \"[email protected]\"] # Array of email(s)\nFROM_EMAIL = \"[email protected]\" # Only one email\n\n# Temp backup locations\nDB_BACKUP=\"/home/backupuser/db_backup/mysite_db-%(date)s.sql.gz.gpg\" % {'date':DATE}\nWEB_BACKUP=\"/home/backupuser/web_backup/mysite_web-%(date)s.tar.gz.gpg\" % {'date':DATE}\n\n# Email subjects\nDB_EMAIL_SUBJECT=\"%(date)s/db/mysite\" % {'date':DATE}\nWEB_EMAIL_SUBJECT=\"%(date)s/web/mysite\" % {'date':DATE}\n\nGPG_RECP = [\"MrAdmin\",\"MrOtherAdmin\"]\n### end Config\n################################################\n\n################################################\n### Process config\nGPG_RECP = \" \".join([\"-r %s\" % (x) for x in GPG_RECP]) # Format GPG_RECP as arg\n\nsql_backup_command = \"mysqldump -u %(SQL_USER)s -p%(SQL_PASS)s %(SQL_DB)s | gzip -9 - | gpg -e %(GPG_RECP)s > %(DB_BACKUP)s\" % {\n 'GPG_RECP':GPG_RECP,\n 'DB_BACKUP':DB_BACKUP,\n 'SQL_USER':SQL_USER,\n 'SQL_PASS':SQL_PASS,\n 'SQL_DB':SQL_DB\n}\n\nweb_backup_command = \"cd /var/www/; tar -c mysite.org/ | gzip -9 | gpg -e %(GPG_RECP)s > %(WEB_BACKUP)s\" % {\n 'GPG_RECP':GPG_RECP,\n 'WEB_BACKUP':WEB_BACKUP,\n}\n# end Process config\n################################################\n\n################################################\n### Main application\ndef main():\n \"\"\"Main backup function\"\"\"\n print \"Backing commencing at %s\" % (DATE)\n\n # Run commands\n print \"Creating db backup...\"\n sql_status,sql_cmd_out = commands.getstatusoutput(sql_backup_command)\n if sql_status == 0:\n db_file_size = round(float( os.stat(DB_BACKUP)[6] ) /1024/1024, 2) # Get file-size in MB\n print \"..successful (%.2fMB)\" % (db_file_size)\n try:\n send_mail(\n send_from = FROM_EMAIL,\n send_to = BACKUP_EMAIL,\n subject = DB_EMAIL_SUBJECT,\n text = \"Database backup\",\n files = [DB_BACKUP],\n server = \"localhost\"\n )\n print \"Sending db backup successful\"\n except Exception,errormsg:\n print \"Sending db backup FAILED. Error was:\",errormsg\n #end try\n\n # Remove backup file\n print \"Removing db backup...\"\n try:\n os.remove(DB_BACKUP)\n print \"...successful\"\n except Exception, errormsg:\n print \"...FAILED. Error was: %s\" % (errormsg)\n #end try\n else:\n print \"Creating db backup FAILED. Output was:\", sql_cmd_out\n #end if sql_status\n\n print \"Creating web backup...\"\n web_status,web_cmd_out = commands.getstatusoutput(web_backup_command)\n if web_status == 0:\n web_file_size = round(float( os.stat(WEB_BACKUP)[6] ) /1024/1024, 2) # File size in MB\n print \"..successful (%.2fMB)\" % (web_file_size)\n try:\n send_mail(\n send_from = FROM_EMAIL,\n send_to = BACKUP_EMAIL,\n subject = WEB_EMAIL_SUBJECT,\n text = \"Website backup\",\n files = [WEB_BACKUP],\n server = \"localhost\"\n )\n print \"Sending web backup successful\"\n except Exception,errormsg:\n print \"Sending web backup FAIELD. Error was: %s\" % (errormsg)\n #end try\n\n # Remove backup file\n print \"Removing web backup...\"\n try:\n os.remove(WEB_BACKUP)\n print \"...successful\"\n except Exception, errormsg:\n print \"...FAILED. Error was: %s\" % (errormsg)\n #end try\n else:\n print \"Creating web backup FAILED. Output was:\", web_cmd_out\n #end if web_status\n#end main\n################################################\n\n################################################\n# Send email function\n\n# needed email libs..\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEText import MIMEText\nfrom email.Utils import COMMASPACE, formatdate\nfrom email import Encoders\n\ndef send_mail(send_from, send_to, subject, text, files=[], server=\"localhost\"):\n assert type(send_to)==list\n assert type(files)==list\n\n msg = MIMEMultipart()\n msg['From'] = send_from\n msg['To'] = COMMASPACE.join(send_to)\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n\n msg.attach( MIMEText(text) )\n\n for f in files:\n part = MIMEBase('application', \"octet-stream\")\n try:\n part.set_payload( open(f,\"rb\").read() )\n except Exception, errormsg:\n raise IOError(\"File not found: %s\"%(errormsg))\n Encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f))\n msg.attach(part)\n #end for f\n\n smtp = smtplib.SMTP(server)\n smtp.sendmail(send_from, send_to, msg.as_string())\n smtp.close()\n#end send_mail\n################################################\n\nif __name__ == '__main__':\n main()\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
46,571
<p>I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <code>&lt;cfqueryparam</code>> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?</p> <p>If my query looks like this:</p> <pre><code>select * from Foo where name like '%Bob%' </code></pre> <p>what should my <code>&lt;cfqueryparam</code>> tag look like?</p>
[ { "answer_id": 47197, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 7, "selected": true, "text": "select a,b,c\nfrom Foo\nwhere name like <cfqueryparam cfsqltype=\"columnType\" value=\"%#variables.someName#%\" />\n" }, { "answer_id": 16583567, "author": "Ramalinga Raju", "author_id": 2358182, "author_profile": "https://Stackoverflow.com/users/2358182", "pm_score": 0, "selected": false, "text": "select a,b,c\nfrom Foo\nwhere name like <cfqueryparam cfsqltype=\"cf_sql_varchar\" value=\"%Bob%\" />;\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3271/" ]
46,582
<p>We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.</p> <p>I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();</p> <p>Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.</p> <p>Anyway, thanks for any and all responses.</p>
[ { "answer_id": 46700, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "string url = \"3rd Party Url\";\n\nStringBuilder postData = new StringBuilder();\n\npostData.Append(\"first_name=\" + HttpUtility.UrlEncode(txtFirstName.Text) + \"&\");\npostData.Append(\"last_name=\" + HttpUtility.UrlEncode(txtLastName.Text));\n\n//ETC for all Form Elements\n\n// Now to Send Data.\nStreamWriter writer = null;\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.Method = \"POST\";\nrequest.ContentType = \"application/x-www-form-urlencoded\"; \nrequest.ContentLength = postData.ToString().Length;\ntry\n{\n writer = new StreamWriter(request.GetRequestStream());\n writer.Write(postData.ToString());\n}\nfinally\n{\n if (writer != null)\n writer.Close();\n}\n\nResponse.Redirect(\"NewPage\");\n" }, { "answer_id": 47735, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 9, "selected": true, "text": "Response.Redirect() GET POST public void PageLoad(object sender, EventArgs e)\n{\n // Process the post on your side \n\n Response.Status = \"307 Temporary Redirect\";\n Response.AddHeader(\"Location\", \"http://example.com/page/to/post.to\");\n}\n action" }, { "answer_id": 1353717, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 1, "selected": false, "text": "Set-Cookie: name=value; Max-Age=120; Path=/redirect.html\n Set-Cookie: name=value; Max-Age=0; Path=/redirect.html\n const string StateCookieName = \"state\";\n\nstatic int StateCookieID;\n\nprotected void Relocate(string url, object state)\n{\n var key = \"__\" + StateCookieName + Interlocked\n .Add(ref StateCookieID, 1).ToInvariantString();\n\n var absoluteExpiration = DateTime.Now\n .Add(new TimeSpan(120 * TimeSpan.TicksPerSecond));\n\n Context.Cache.Insert(key, state, null, absoluteExpiration,\n Cache.NoSlidingExpiration);\n\n var path = Context.Response.ApplyAppPathModifier(url);\n\n Context.Response.Cookies\n .Add(new HttpCookie(StateCookieName, key)\n {\n Path = path,\n Expires = absoluteExpiration\n });\n\n Context.Response.Redirect(path, false);\n}\n\nprotected TData GetState<TData>()\n where TData : class\n{\n var cookie = Context.Request.Cookies[StateCookieName];\n if (cookie != null)\n {\n var key = cookie.Value;\n if (key.IsNonEmpty())\n {\n var obj = Context.Cache.Remove(key);\n\n Context.Response.Cookies\n .Add(new HttpCookie(StateCookieName)\n { \n Path = cookie.Path, \n Expires = new DateTime(1970, 1, 1) \n });\n\n return obj as TData;\n }\n }\n return null;\n}\n" }, { "answer_id": 2802848, "author": "Pavlo Neiman", "author_id": 164001, "author_profile": "https://Stackoverflow.com/users/164001", "pm_score": 7, "selected": false, "text": "Response.Clear();\n\nStringBuilder sb = new StringBuilder();\nsb.Append(\"<html>\");\nsb.AppendFormat(@\"<body onload='document.forms[\"\"form\"\"].submit()'>\");\nsb.AppendFormat(\"<form name='form' action='{0}' method='post'>\",postbackUrl);\nsb.AppendFormat(\"<input type='hidden' name='id' value='{0}'>\", id);\n// Other params go here\nsb.Append(\"</form>\");\nsb.Append(\"</body>\");\nsb.Append(\"</html>\");\n\nResponse.Write(sb.ToString());\n\nResponse.End();\n" }, { "answer_id": 12175053, "author": "ZooZ", "author_id": 772930, "author_profile": "https://Stackoverflow.com/users/772930", "pm_score": 3, "selected": false, "text": "Imports System.Web\nImports System.Runtime.CompilerServices\n\nModule WebExtensions\n\n <Extension()> _\n Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, _\n ByVal aData As NameValueCollection)\n aThis.Clear()\n Dim sb As StringBuilder = New StringBuilder()\n\n sb.Append(\"<html>\")\n sb.AppendFormat(\"<body onload='document.forms[\"\"form\"\"].submit()'>\")\n sb.AppendFormat(\"<form name='form' action='{0}' method='post'>\", aDestination)\n\n For Each key As String In aData\n sb.AppendFormat(\"<input type='hidden' name='{0}' value='{1}' />\", key, aData(key))\n Next\n\n sb.Append(\"</form>\")\n sb.Append(\"</body>\")\n sb.Append(\"</html>\")\n\n aThis.Write(sb.ToString())\n\n aThis.End()\n End Sub\n\nEnd Module\n" }, { "answer_id": 19598053, "author": "jacob", "author_id": 1784298, "author_profile": "https://Stackoverflow.com/users/1784298", "pm_score": 3, "selected": false, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>Heroku Add-ons SSO</title>\n </head>\n\n <body>\n <form method=\"POST\" action=\"https://XXXXXXXX/sso/login\">\n\n <input type=\"hidden\" name=\"email\" value=\"XXXXXXXX\" />\n\n <input type=\"hidden\" name=\"app\" value=\"XXXXXXXXXX\" />\n\n <input type=\"hidden\" name=\"id\" value=\"XXXXXXXX\" />\n\n <input type=\"hidden\" name=\"timestamp\" value=\"1382728968\" />\n\n <input type=\"hidden\" name=\"token\" value=\"XXXXXXX\" />\n\n <input type=\"hidden\" name=\"nav-data\" value=\"XXXXXXXXX\" />\n\n </form>\n\n <script type=\"text/javascript\">\n document.forms[0].submit();\n </script>\n </body>\n</html>\n" }, { "answer_id": 54929640, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 1, "selected": false, "text": " protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)\n {\n Response.Clear();\n\n const string template =\n@\"<html>\n<body onload='document.forms[\"\"form\"\"].submit()'>\n<form name='form' action='{0}' method='post'>\n{1}\n</form>\n</body>\n</html>\";\n\n var fieldsSection = string.Join(\n Environment.NewLine,\n fields.Select(x => $\"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>\")\n );\n\n var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);\n\n Response.Write(html);\n\n Response.End();\n }\n\n private const string JsonDataFieldName = \"_jsonData\";\n\n protected void RedirectPost<T>(string url, T bodyPayload)\n {\n var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);\n //explicit type declaration to prevent recursion\n IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()\n {new KeyValuePair<string, string>(JsonDataFieldName, json)};\n\n RedirectPost(url, postFields);\n\n }\n\n protected T GetPostData<T>() where T: class \n {\n var urlEncodedFieldData = Request.Params[JsonDataFieldName];\n if (string.IsNullOrEmpty(urlEncodedFieldData))\n {\n return null;// default(T);\n }\n\n var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);\n\n var result = JsonConvert.DeserializeObject<T>(fieldData);\n return result;\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
46,585
<p>From what I can gather, there are three categories:</p> <ol> <li>Never use <code>GET</code> and use <code>POST</code></li> <li>Never use <code>POST</code> and use <code>GET</code></li> <li>It doesn't matter which one you use.</li> </ol> <p>Am I correct in assuming those three cases? If so, what are some examples from each case?</p>
[ { "answer_id": 46614, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 10, "selected": true, "text": "POST POST GET http://myblog.org/admin/posts/delete/357\n POST GET GET method POST GET" }, { "answer_id": 46617, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "delete.php?id=5" }, { "answer_id": 46639, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 8, "selected": false, "text": "GET safe and idempotent POST neither safe nor idempotent use GETs safe and idempotent safe not change the data idempotent be the same PUTs not safe but idempotent POST neither safe or idempotent" }, { "answer_id": 46737, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": -1, "selected": false, "text": "mod_rewrite GET GET" }, { "answer_id": 2267837, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 3, "selected": false, "text": "textarea delete.php?id=1" }, { "answer_id": 2267848, "author": "prodigitalson", "author_id": 215966, "author_profile": "https://Stackoverflow.com/users/215966", "pm_score": 0, "selected": false, "text": "GET" }, { "answer_id": 2268041, "author": "Elizabeth Buckwalter", "author_id": 167034, "author_profile": "https://Stackoverflow.com/users/167034", "pm_score": 0, "selected": false, "text": "$_REQUEST $_GET $_POST" }, { "answer_id": 2268326, "author": "jellyfishtree", "author_id": 273632, "author_profile": "https://Stackoverflow.com/users/273632", "pm_score": 1, "selected": false, "text": "POST php.ini GET 255" }, { "answer_id": 18511298, "author": "Anagha", "author_id": 2063953, "author_profile": "https://Stackoverflow.com/users/2063953", "pm_score": 3, "selected": false, "text": "GET POST The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).\n The interaction is more like an order, or\n The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or\n The user be held accountable for the results of the interaction.\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
46,586
<p>Everyone is aware of Dijkstra's <a href="http://portal.acm.org/citation.cfm?doid=362947" rel="noreferrer">Letters to the editor: go to statement considered harmful</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html" rel="noreferrer">here</a> .html transcript and <a href="http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF" rel="noreferrer">here</a> .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in <a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx" rel="noreferrer">modern programming languages</a>. Even the advanced <a href="http://en.wikipedia.org/wiki/Goto#Continuations" rel="noreferrer">continuation</a> control structure in Scheme can be described as a sophisticated goto.</p> <p>What circumstances warrant the use of goto? When is it best to avoid?</p> <p>As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?</p> <hr /> <p>Dijkstra himself regretted that title, for which he was not responsible. At the end of <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html" rel="noreferrer">EWD1308</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF" rel="noreferrer">here</a> .pdf) he wrote:</p> <blockquote> <p>Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title &quot;<em>The goto statement considered harmful</em>&quot;, which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title &quot;X considered harmful&quot; for almost any X, including one titled &quot;Dijkstra considered harmful&quot;. But what had happened? I had submitted a paper under the title &quot;<em><strong>A case against the goto statement</strong></em>&quot;, which, in order to speed up its publication, the editor had changed into a &quot;letter to the Editor&quot;, and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth.</p> </blockquote> <p>A well thought out classic paper about this topic, to be matched to that of Dijkstra, is <a href="http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf" rel="noreferrer">Structured Programming with go to Statements</a>, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:</p> <blockquote> <p><em>Donald E. Knuth:</em> I believe that by presenting such a view I am not in fact disagreeing sharply with Dijkstra's ideas, since he recently wrote the following: &quot;Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. <strong>I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!</strong>&quot;</p> </blockquote>
[ { "answer_id": 46597, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "if while goto" }, { "answer_id": 46638, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 7, "selected": false, "text": " if (f() == false) goto err_cleanup;\n if (g() == false) goto err_cleanup;\n if (h() == false) goto err_cleanup;\n \n return;\n \n err_cleanup:\n ...\n" }, { "answer_id": 47472, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 7, "selected": false, "text": " for{\n for{\n for{\n for{\n for{\n if(stuff){\n GOTO ENDOFLOOPS;\n }\n }\n }\n }\n }\n }\n \n ENDOFLOOPS:\n" }, { "answer_id": 47476, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "goto goto goto goto goto" }, { "answer_id": 47517, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 6, "selected": false, "text": "goto setjmp longjmp goto goto 3420 IF A > 2 THEN GOTO 1430\n goto" }, { "answer_id": 47590, "author": "vt.", "author_id": 3905, "author_profile": "https://Stackoverflow.com/users/3905", "pm_score": 4, "selected": false, "text": "char run(char *pc) {\n void *opcodes[3] = {&&op_inc, &&op_lda_direct, &&op_hlt};\n #define NEXT_INSTR(stride) goto *(opcodes[*(pc += stride)])\n NEXT_INSTR(0);\n op_inc:\n ++acc;\n NEXT_INSTR(1);\n op_lda_direct:\n acc = ram[++pc];\n NEXT_INSTR(1);\n op_hlt:\n return acc;\n}" }, { "answer_id": 52307, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 9, "selected": true, "text": " a = b + 1\n /* do something with a */\n a b ...\n goto 10\n ...\n a = b + 1\n 10: /* do something with a */\n ...\n goto 10\n ...\n a b if (some condition) {\n action-1\n } else {\n action-2\n }\n" }, { "answer_id": 323815, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 3, "selected": false, "text": "request something\nwait for it to be done\nwhile some condition\n request something\n wait for it\n if one response\n while another condition\n request something\n wait for it\n do something\n endwhile\n request one more thing\n wait for it\n else if some other response\n ... some other similar sequence ...\n ... etc, etc.\nendwhile\n #define WAIT(n) do{state=(n); enque(this); return; L##n:;}while(0)\n#define DONE state = -1\n\n#define DISPATCH0 if state < 0) return;\n#define DISPATCH1 if(state==1) goto L1; DISPATCH0\n#define DISPATCH2 if(state==2) goto L2; DISPATCH1\n#define DISPATCH3 if(state==3) goto L3; DISPATCH2\n#define DISPATCH4 if(state==4) goto L4; DISPATCH3\n... as needed ...\n {\n DISPATCH4; // or as high a number as needed\n request something;\n WAIT(1); // each WAIT has a different number\n while (some condition){\n request something;\n WAIT(2);\n if (one response){\n while (another condition){\n request something;\n WAIT(3);\n do something;\n }\n request one more thing;\n WAIT(4);\n }\n else if (some other response){\n ... some other similar sequence ...\n }\n ... etc, etc.\n }\n DONE;\n}\n" }, { "answer_id": 357028, "author": "CurtTampa", "author_id": 18225, "author_profile": "https://Stackoverflow.com/users/18225", "pm_score": 4, "selected": false, "text": " YORN = ''\n LOOP\n UNTIL YORN = 'Y' OR YORN = 'N' DO\n CRT 'Is this correct? (Y/N) : ':\n INPUT YORN\n REPEAT\n IF YORN = 'N' THEN\n CRT 'Aborted!'\n STOP\n END\n 10: CRT 'Is this Correct (Y)es/(N)o ':\n\n INPUT YORN\n\n IF YORN='N' THEN\n CRT 'Aborted!'\n STOP\n ENDIF\n IF YORN<>'Y' THEN GOTO 10\n" }, { "answer_id": 453816, "author": "Rocketmagnet", "author_id": 55934, "author_profile": "https://Stackoverflow.com/users/55934", "pm_score": 3, "selected": false, "text": "SomeObject someObject; \n\nif (someObject.IsComplex()) // this test is trivial\n{\n // begin slow calculations here\n if (result of calculations)\n {\n // just discovered that I could use the fast calculation !\n goto Fast_Calculations;\n }\n // do the rest of the slow calculations here\n return;\n}\n\nif (someObject.IsmediumComplex()) // this test is slightly less trivial\n{\n Fast_Calculations:\n // Do fast calculations\n return;\n}\n\n// object is simple, no calculations needed.\n" }, { "answer_id": 548769, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": " do 10 i = 1,30\n ...blah...\n ...blah...\n if (k.gt.4) goto 37\n91 ...blah...\n ...blah...\n10 continue\n ...blah...\n return\n37 ...some computation...\n goto 91\n ...blah...\n i = 1\n goto 76\n123 ...blah...\n ...blah...\n i = 2\n goto 76\n79 ...blah...\n ...blah...\n goto 54\n ...blah...\n12 continue\n return\n76 ...calculate something...\n ...blah...\n goto (123, 79) i\n54 ...more calculation...\n goto 12\n" }, { "answer_id": 741517, "author": "tylerl", "author_id": 86060, "author_profile": "https://Stackoverflow.com/users/86060", "pm_score": 5, "selected": false, "text": "ptr = malloc(size);\nif (!ptr) goto label_fail;\nbytes_in = read(f_in,ptr,size);\nif (bytes_in=<0) goto label_fail;\nbytes_out = write(f_out,ptr,bytes_in);\nif (bytes_out != bytes_in) goto label_fail;\n success=false;\ndo {\n ptr = malloc(size);\n if (!ptr) break;\n bytes_in = read(f_in,ptr,size);\n if (count=<0) break;\n bytes_out = write(f_out,ptr,bytes_in);\n if (bytes_out != bytes_in) break;\n success = true;\n} while (false);\n while" }, { "answer_id": 1616884, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": 0, "selected": false, "text": "loop:\n GetSomeData;\n if GotData then\n Begin\n ProcessTheData;\n StoreTheResult;\n Goto Loop;\n End;\n Repeat\n GetSomeData;\n Flag := GotData;\n if Flag then\n Begin\n ProcessTheData;\n StoreTheResult;\n End;\nUntil Not Flag;\n Function GotTheData;\n\nBegin\n GetSomeData;\n Result := GotData;\nEnd;\n\nWhile GotTheData do\n Begin\n ProcessTheData;\n StoreTheResult;\n End;\n" }, { "answer_id": 1857927, "author": "DigitalRoss", "author_id": 140740, "author_profile": "https://Stackoverflow.com/users/140740", "pm_score": 4, "selected": false, "text": "goto Goto while foreach goto goto break return while break return goto else if if if if-then-else goto goto" }, { "answer_id": 2394549, "author": "dan04", "author_id": 287586, "author_profile": "https://Stackoverflow.com/users/287586", "pm_score": 6, "selected": false, "text": "GOTO GOTO goto break continue return if else while switch case GOTO IF ELSE 100 IF NOT condition THEN GOTO 200\n...stuff to do if condition is true...\n190 GOTO 300\n200 REM else\n...stuff to do if condition is false...\n300 REM end if\n IF ELSE GOTO DO...LOOP FOR GOTO IF...GOTO SELECT CASE ON...GOTO GOTO GOTO GOSUB...RETURN GOTO GOTO" }, { "answer_id": 10859707, "author": "Tim", "author_id": 1110442, "author_profile": "https://Stackoverflow.com/users/1110442", "pm_score": 2, "selected": false, "text": "int\nfoo(const char *arg)\n{\n char *argcopy = strdup(arg);\n\n if (!isvalid(argcopy))\n goto out1;\n\n FILE *myfile = fopen(argcopy, \"r\");\n if (myfile == NULL)\n goto out1;\n\n char bytes[10];\n if (fread(bytes, sizeof(bytes), 1, myfile) != sizeof(mybytes))\n goto out2;\n\n /* do some actual work */\n /* .... */\n /* end of actual work */\n\n out2:\n fclose(myfile);\n\n out1:\n free(argcopy);\n\n return 0;\n }\n" }, { "answer_id": 10921640, "author": "gkimsey", "author_id": 1224427, "author_profile": "https://Stackoverflow.com/users/1224427", "pm_score": 3, "selected": false, "text": "if(breakVariable)" }, { "answer_id": 14960832, "author": "guido", "author_id": 389099, "author_profile": "https://Stackoverflow.com/users/389099", "pm_score": 0, "selected": false, "text": "int firstUpper;\n\n/* Now check if there are any characters that need to be changed. */\nscan: {\n for (firstUpper = 0 ; firstUpper < count; ) {\n char c = value[offset+firstUpper];\n if ((c >= Character.MIN_HIGH_SURROGATE) &&\n (c <= Character.MAX_HIGH_SURROGATE)) {\n int supplChar = codePointAt(firstUpper);\n if (supplChar != Character.toLowerCase(supplChar)) {\n break scan;\n }\n firstUpper += Character.charCount(supplChar);\n } else {\n if (c != Character.toLowerCase(c)) {\n break scan;\n }\n firstUpper++;\n }\n }\n return this;\n}\n[... subsequent use of firstUpper ...]\n int firstUpper = indexOfFirstUpper();\n if (firstUpper < 0) return this; \n" }, { "answer_id": 24473250, "author": "Akavall", "author_id": 1078084, "author_profile": "https://Stackoverflow.com/users/1078084", "pm_score": 1, "selected": false, "text": "goto c++ goto goto goto goto" }, { "answer_id": 25773503, "author": "thb", "author_id": 1275653, "author_profile": "https://Stackoverflow.com/users/1275653", "pm_score": 5, "selected": false, "text": "bool" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
46,621
<p>I have a DotNetNuke site where my main logo is a PNG file using transparency. I tried GIF but the quality wasn't good enough.</p> <p>Anyways it worked great on IE7 but I just saw my site in IE6 and noticed that the transparency isn't working with my logo.</p> <p>Does anyone know of a quick way to fix this in a DotNetNuke portal?</p>
[ { "answer_id": 46633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<!--[if IE 6]>\nbackground-image:crappy.gif\n<![endif]-->\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4801/" ]
46,636
<p>What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?</p>
[ { "answer_id": 46640, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": true, "text": "copy \\\\myserver\\myshare\\myfolder\\myfile.txt c:\\myfiles\n" }, { "answer_id": 46646, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "net use net use /?\n" }, { "answer_id": 59326025, "author": "Wasif", "author_id": 12269857, "author_profile": "https://Stackoverflow.com/users/12269857", "pm_score": 0, "selected": false, "text": "xcopy robocopy xcopy \"\\\\server\\share\\path\" \"destination\"\n robocopy \"\\\\server\\share\\path\" \"destination\"\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
46,642
<p>I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible. </p> <p>Any suggestions?</p>
[ { "answer_id": 46821, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 1, "selected": false, "text": "jmap -histo <pid>" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
46,644
<p>just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.</p>
[ { "answer_id": 47378, "author": "berko", "author_id": 4884, "author_profile": "https://Stackoverflow.com/users/4884", "pm_score": 0, "selected": false, "text": "[AcceptVerbs(\"delete\")]\npublic object DoDeleteAction()\n" }, { "answer_id": 256889, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 0, "selected": false, "text": "[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Index()\n{ ... }\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Update()\n{ ... }\n\n[AcceptVerbs(HttpVerbs.Delete)]\npublic ActionResult Delete()\n{ ... }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
46,663
<p>Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.</p>
[ { "answer_id": 46681, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 7, "selected": false, "text": "String host = \"smtp.gmail.com\";\nString from = \"user name\";\nProperties props = System.getProperties();\nprops.put(\"mail.smtp.host\", host);\nprops.put(\"mail.smtp.user\", from);\nprops.put(\"mail.smtp.password\", \"asdfgh\");\nprops.put(\"mail.smtp.port\", \"587\"); // 587 is the port number of yahoo mail\nprops.put(\"mail.smtp.auth\", \"true\");\n\nSession session = Session.getDefaultInstance(props, null);\nMimeMessage message = new MimeMessage(session);\nmessage.setFrom(new InternetAddress(from));\n\nInternetAddress[] to_address = new InternetAddress[to.length];\nint i = 0;\n// To get the array of addresses\nwhile (to[i] != null) {\n to_address[i] = new InternetAddress(to[i]);\n i++;\n}\nSystem.out.println(Message.RecipientType.TO);\ni = 0;\nwhile (to_address[i] != null) {\n\n message.addRecipient(Message.RecipientType.TO, to_address[i]);\n i++;\n}\nmessage.setSubject(\"sending in a group\");\nmessage.setText(\"Welcome to JavaMail\");\n// alternately, to send HTML mail:\n// message.setContent(\"<p>Welcome to JavaMail</p>\", \"text/html\");\nTransport transport = session.getTransport(\"smtp\");\ntransport.connect(\"smtp.mail.yahoo.co.in\", \"user name\", \"asdfgh\");\ntransport.sendMessage(message, message.getAllRecipients());\ntransport.close();\n" }, { "answer_id": 47452, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 9, "selected": true, "text": "import java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class Main {\n\n private static String USER_NAME = \"*****\"; // GMail user name (just the part before \"@gmail.com\")\n private static String PASSWORD = \"********\"; // GMail password\n private static String RECIPIENT = \"[email protected]\";\n\n public static void main(String[] args) {\n String from = USER_NAME;\n String pass = PASSWORD;\n String[] to = { RECIPIENT }; // list of recipient email addresses\n String subject = \"Java send mail example\";\n String body = \"Welcome to JavaMail!\";\n\n sendFromGMail(from, pass, to, subject, body);\n }\n\n private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {\n Properties props = System.getProperties();\n String host = \"smtp.gmail.com\";\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", host);\n props.put(\"mail.smtp.user\", from);\n props.put(\"mail.smtp.password\", pass);\n props.put(\"mail.smtp.port\", \"587\");\n props.put(\"mail.smtp.auth\", \"true\");\n\n Session session = Session.getDefaultInstance(props);\n MimeMessage message = new MimeMessage(session);\n\n try {\n message.setFrom(new InternetAddress(from));\n InternetAddress[] toAddress = new InternetAddress[to.length];\n\n // To get the array of addresses\n for( int i = 0; i < to.length; i++ ) {\n toAddress[i] = new InternetAddress(to[i]);\n }\n\n for( int i = 0; i < toAddress.length; i++) {\n message.addRecipient(Message.RecipientType.TO, toAddress[i]);\n }\n\n message.setSubject(subject);\n message.setText(body);\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, from, pass);\n transport.sendMessage(message, message.getAllRecipients());\n transport.close();\n }\n catch (AddressException ae) {\n ae.printStackTrace();\n }\n catch (MessagingException me) {\n me.printStackTrace();\n }\n }\n}\n catch catch" }, { "answer_id": 886689, "author": "user109771", "author_id": 109771, "author_profile": "https://Stackoverflow.com/users/109771", "pm_score": 4, "selected": false, "text": "final Email email = new Email();\n\nString host = \"smtp.gmail.com\";\nInteger port = 587;\nString from = \"username\";\nString pass = \"password\";\nString[] to = {\"[email protected]\"};\n\nemail.setFromAddress(\"\", from);\nemail.setSubject(\"sending in a group\");\nfor( int i=0; i < to.length; i++ ) {\n email.addRecipient(\"\", to[i], RecipientType.TO);\n}\nemail.setText(\"Welcome to JavaMail\");\n\nnew Mailer(host, port, from, pass).sendMail(email);\n// you could also still use your mail session instead\nnew Mailer(session).sendMail(email);\n" }, { "answer_id": 935714, "author": "Ifnu", "author_id": 115520, "author_profile": "https://Stackoverflow.com/users/115520", "pm_score": 1, "selected": false, "text": " public class NewClass {\n\n public static void main(String[] args) {\n try {\n Properties props = System.getProperties();\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", \"smtp.gmail.com\");\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.port\", \"465\"); // smtp port\n Authenticator auth = new Authenticator() {\n\n @Override\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(\"username-gmail\", \"password-gmail\");\n }\n };\n Session session = Session.getDefaultInstance(props, auth);\n MimeMessage msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"[email protected]\"));\n msg.setSubject(\"Try attachment gmail\");\n msg.setRecipient(RecipientType.TO, new InternetAddress(\"[email protected]\"));\n //add atleast simple body\n MimeBodyPart body = new MimeBodyPart();\n body.setText(\"Try attachment\");\n //do attachment\n MimeBodyPart attachMent = new MimeBodyPart();\n FileDataSource dataSource = new FileDataSource(new File(\"file-sent.txt\"));\n attachMent.setDataHandler(new DataHandler(dataSource));\n attachMent.setFileName(\"file-sent.txt\");\n attachMent.setDisposition(MimeBodyPart.ATTACHMENT);\n Multipart multipart = new MimeMultipart();\n multipart.addBodyPart(body);\n multipart.addBodyPart(attachMent);\n msg.setContent(multipart);\n Transport.send(msg);\n } catch (AddressException ex) {\n Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n } catch (MessagingException ex) {\n Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n}\n" }, { "answer_id": 1013676, "author": "Jason Thrasher", "author_id": 124754, "author_profile": "https://Stackoverflow.com/users/124754", "pm_score": 5, "selected": false, "text": "<bean id=\"mailSender\" class=\"org.springframework.mail.javamail.JavaMailSenderImpl\">\n <property name=\"defaultEncoding\" value=\"UTF-8\"/>\n <property name=\"host\" value=\"smtp.gmail.com\"/>\n <property name=\"port\" value=\"465\"/>\n <property name=\"username\" value=\"${mail.username}\"/>\n <property name=\"password\" value=\"${mail.password}\"/>\n <property name=\"javaMailProperties\">\n <value>\n mail.debug=true\n mail.smtp.auth=true\n mail.smtp.socketFactory.class=java.net.SocketFactory\n mail.smtp.socketFactory.fallback=false\n </value>\n </property>\n</bean>\n" }, { "answer_id": 3970608, "author": "vishnu", "author_id": 480749, "author_profile": "https://Stackoverflow.com/users/480749", "pm_score": 2, "selected": false, "text": "//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar\nimport javax.mail.*;\nimport javax.mail.internet.*;\nimport java.util.*;\n\npublic class Mail\n{\n String d_email = \"[email protected]\",\n d_password = \"****\",\n d_host = \"smtp.gmail.com\",\n d_port = \"465\",\n m_to = \"[email protected]\",\n m_subject = \"Testing\",\n m_text = \"Hey, this is the testing email using smtp.gmail.com.\";\n public static void main(String[] args)\n {\n String[] to={\"[email protected]\"};\n String[] cc={\"[email protected]\"};\n String[] bcc={\"[email protected]\"};\n //This is for google\n Mail.sendMail(\"[email protected]\", \"password\", \"smtp.gmail.com\", \n \"465\", \"true\", \"true\", \n true, \"javax.net.ssl.SSLSocketFactory\", \"false\", \n to, cc, bcc, \n \"hi baba don't send virus mails..\", \n \"This is my style...of reply..If u send virus mails..\");\n }\n\n public synchronized static boolean sendMail(\n String userName, String passWord, String host, \n String port, String starttls, String auth, \n boolean debug, String socketFactoryClass, String fallback, \n String[] to, String[] cc, String[] bcc, \n String subject, String text) \n {\n Properties props = new Properties();\n //Properties props=System.getProperties();\n props.put(\"mail.smtp.user\", userName);\n props.put(\"mail.smtp.host\", host);\n if(!\"\".equals(port))\n props.put(\"mail.smtp.port\", port);\n if(!\"\".equals(starttls))\n props.put(\"mail.smtp.starttls.enable\",starttls);\n props.put(\"mail.smtp.auth\", auth);\n if(debug) {\n props.put(\"mail.smtp.debug\", \"true\");\n } else {\n props.put(\"mail.smtp.debug\", \"false\"); \n }\n if(!\"\".equals(port))\n props.put(\"mail.smtp.socketFactory.port\", port);\n if(!\"\".equals(socketFactoryClass))\n props.put(\"mail.smtp.socketFactory.class\",socketFactoryClass);\n if(!\"\".equals(fallback))\n props.put(\"mail.smtp.socketFactory.fallback\", fallback);\n\n try\n {\n Session session = Session.getDefaultInstance(props, null);\n session.setDebug(debug);\n MimeMessage msg = new MimeMessage(session);\n msg.setText(text);\n msg.setSubject(subject);\n msg.setFrom(new InternetAddress(\"[email protected]\"));\n for(int i=0;i<to.length;i++) {\n msg.addRecipient(Message.RecipientType.TO, \n new InternetAddress(to[i]));\n }\n for(int i=0;i<cc.length;i++) {\n msg.addRecipient(Message.RecipientType.CC, \n new InternetAddress(cc[i]));\n }\n for(int i=0;i<bcc.length;i++) {\n msg.addRecipient(Message.RecipientType.BCC, \n new InternetAddress(bcc[i]));\n }\n msg.saveChanges();\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, userName, passWord);\n transport.sendMessage(msg, msg.getAllRecipients());\n transport.close();\n return true;\n }\n catch (Exception mex)\n {\n mex.printStackTrace();\n return false;\n }\n }\n\n}\n" }, { "answer_id": 14191227, "author": "Ripon Al Wasim", "author_id": 617450, "author_profile": "https://Stackoverflow.com/users/617450", "pm_score": 3, "selected": false, "text": "package ripon.java.mail;\nimport java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class SendEmail\n{\npublic static void main(String [] args)\n{ \n // Sender's email ID needs to be mentioned\n String from = \"[email protected]\";\n String pass =\"test123\";\n // Recipient's email ID needs to be mentioned.\n String to = \"[email protected]\";\n\n String host = \"smtp.gmail.com\";\n\n // Get system properties\n Properties properties = System.getProperties();\n // Setup mail server\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.host\", host);\n properties.put(\"mail.smtp.user\", from);\n properties.put(\"mail.smtp.password\", pass);\n properties.put(\"mail.smtp.port\", \"587\");\n properties.put(\"mail.smtp.auth\", \"true\");\n\n // Get the default Session object.\n Session session = Session.getDefaultInstance(properties);\n\n try{\n // Create a default MimeMessage object.\n MimeMessage message = new MimeMessage(session);\n\n // Set From: header field of the header.\n message.setFrom(new InternetAddress(from));\n\n // Set To: header field of the header.\n message.addRecipient(Message.RecipientType.TO,\n new InternetAddress(to));\n\n // Set Subject: header field\n message.setSubject(\"This is the Subject Line!\");\n\n // Now set the actual message\n message.setText(\"This is actual message\");\n\n // Send message\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, from, pass);\n transport.sendMessage(message, message.getAllRecipients());\n transport.close();\n System.out.println(\"Sent message successfully....\");\n }catch (MessagingException mex) {\n mex.printStackTrace();\n }\n}\n}\n" }, { "answer_id": 20550855, "author": "Bryan", "author_id": 908570, "author_profile": "https://Stackoverflow.com/users/908570", "pm_score": 2, "selected": false, "text": "Session.getInstance(properties);\n Session.getDefaultInstance(properties);\n" }, { "answer_id": 21800051, "author": "Pyare", "author_id": 1911977, "author_profile": "https://Stackoverflow.com/users/1911977", "pm_score": 0, "selected": false, "text": "package my.test.service;\n\nimport java.util.Properties;\n\nimport javax.mail.Authenticator;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Message;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class Sample {\n public static void main(String args[]) {\n final String SMTP_HOST = \"smtp.gmail.com\";\n final String SMTP_PORT = \"587\";\n final String GMAIL_USERNAME = \"[email protected]\";\n final String GMAIL_PASSWORD = \"xxxxxxxxxx\";\n\n System.out.println(\"Process Started\");\n\n Properties prop = System.getProperties();\n prop.setProperty(\"mail.smtp.starttls.enable\", \"true\");\n prop.setProperty(\"mail.smtp.host\", SMTP_HOST);\n prop.setProperty(\"mail.smtp.user\", GMAIL_USERNAME);\n prop.setProperty(\"mail.smtp.password\", GMAIL_PASSWORD);\n prop.setProperty(\"mail.smtp.port\", SMTP_PORT);\n prop.setProperty(\"mail.smtp.auth\", \"true\");\n System.out.println(\"Props : \" + prop);\n\n Session session = Session.getInstance(prop, new Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(GMAIL_USERNAME,\n GMAIL_PASSWORD);\n }\n });\n\n System.out.println(\"Got Session : \" + session);\n\n MimeMessage message = new MimeMessage(session);\n try {\n System.out.println(\"before sending\");\n message.setFrom(new InternetAddress(GMAIL_USERNAME));\n message.addRecipients(Message.RecipientType.TO,\n InternetAddress.parse(GMAIL_USERNAME));\n message.setSubject(\"My First Email Attempt from Java\");\n message.setText(\"Hi, This mail came from Java Application.\");\n message.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(GMAIL_USERNAME));\n Transport transport = session.getTransport(\"smtp\");\n System.out.println(\"Got Transport\" + transport);\n transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);\n transport.sendMessage(message, message.getAllRecipients());\n System.out.println(\"message Object : \" + message);\n System.out.println(\"Email Sent Successfully\");\n } catch (AddressException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n } catch (MessagingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}\n" }, { "answer_id": 27402060, "author": "AlikElzin-kilaka", "author_id": 435605, "author_profile": "https://Stackoverflow.com/users/435605", "pm_score": 2, "selected": false, "text": "import java.util.Properties;\n\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class MessageSender {\n\n public static void sendHardCoded() throws AddressException, MessagingException {\n String to = \"[email protected]\";\n final String from = \"[email protected]\";\n\n Properties properties = new Properties();\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.auth\", \"true\");\n properties.put(\"mail.smtp.host\", \"smtp.gmail.com\");\n properties.put(\"mail.smtp.port\", \"587\");\n\n Session session = Session.getInstance(properties,\n new javax.mail.Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(from, \"BeNice\");\n }\n });\n\n MimeMessage message = new MimeMessage(session);\n message.setFrom(new InternetAddress(from));\n message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));\n message.setSubject(\"Hello\");\n message.setText(\"What's up?\");\n\n Transport.send(message);\n }\n\n}\n" }, { "answer_id": 31224370, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 0, "selected": false, "text": "Gmail JavaMail Maven import java.util.Properties;\n\nimport javax.activation.DataHandler;\nimport javax.activation.DataSource;\nimport javax.activation.FileDataSource;\nimport javax.mail.BodyPart;\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.Multipart;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeBodyPart;\nimport javax.mail.internet.MimeMessage;\nimport javax.mail.internet.MimeMultipart;\n\npublic class GmailSender\n{\n private static String protocol = \"smtp\";\n\n private String username;\n private String password;\n\n private Session session;\n private Message message;\n private Multipart multipart;\n\n public GmailSender()\n {\n this.multipart = new MimeMultipart();\n }\n\n public void setSender(String username, String password)\n {\n this.username = username;\n this.password = password;\n\n this.session = getSession();\n this.message = new MimeMessage(session);\n }\n\n public void addRecipient(String recipient) throws AddressException, MessagingException\n {\n message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));\n }\n\n public void setSubject(String subject) throws MessagingException\n {\n message.setSubject(subject);\n }\n\n public void setBody(String body) throws MessagingException\n {\n BodyPart messageBodyPart = new MimeBodyPart();\n messageBodyPart.setText(body);\n multipart.addBodyPart(messageBodyPart);\n\n message.setContent(multipart);\n }\n\n public void send() throws MessagingException\n {\n Transport transport = session.getTransport(protocol);\n transport.connect(username, password);\n transport.sendMessage(message, message.getAllRecipients());\n\n transport.close();\n }\n\n public void addAttachment(String filePath) throws MessagingException\n {\n BodyPart messageBodyPart = getFileBodyPart(filePath);\n multipart.addBodyPart(messageBodyPart);\n\n message.setContent(multipart);\n }\n\n private BodyPart getFileBodyPart(String filePath) throws MessagingException\n {\n BodyPart messageBodyPart = new MimeBodyPart();\n DataSource dataSource = new FileDataSource(filePath);\n messageBodyPart.setDataHandler(new DataHandler(dataSource));\n messageBodyPart.setFileName(filePath);\n\n return messageBodyPart;\n }\n\n private Session getSession()\n {\n Properties properties = getMailServerProperties();\n Session session = Session.getDefaultInstance(properties);\n\n return session;\n }\n\n private Properties getMailServerProperties()\n {\n Properties properties = System.getProperties();\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.host\", protocol + \".gmail.com\");\n properties.put(\"mail.smtp.user\", username);\n properties.put(\"mail.smtp.password\", password);\n properties.put(\"mail.smtp.port\", \"587\");\n properties.put(\"mail.smtp.auth\", \"true\");\n\n return properties;\n }\n}\n GmailSender sender = new GmailSender();\nsender.setSender(\"[email protected]\", \"mypassword\");\nsender.addRecipient(\"[email protected]\");\nsender.setSubject(\"The subject\");\nsender.setBody(\"The body\");\nsender.addAttachment(\"TestFile.txt\");\nsender.send();\n" }, { "answer_id": 41347492, "author": "Inzimam Tariq IT", "author_id": 5055401, "author_profile": "https://Stackoverflow.com/users/5055401", "pm_score": 0, "selected": false, "text": "Javamail API smtp-mail.outlook.com\n" }, { "answer_id": 62555019, "author": "Reto Höhener", "author_id": 1124509, "author_profile": "https://Stackoverflow.com/users/1124509", "pm_score": 2, "selected": false, "text": "Session.getInstance() Session.getDefaultInstance() import java.io.File;\n import java.nio.charset.StandardCharsets;\n import java.util.Properties;\n import java.util.logging.Level;\n import java.util.logging.Logger;\n import javax.activation.DataHandler;\n import javax.mail.Message;\n import javax.mail.Session;\n import javax.mail.Transport;\n import javax.mail.internet.InternetAddress;\n import javax.mail.internet.MimeBodyPart;\n import javax.mail.internet.MimeMessage;\n import javax.mail.internet.MimeMultipart;\n import javax.mail.util.ByteArrayDataSource;\n \n public class Gmailer {\n private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());\n \n public static void main(String[] args) {\n send();\n }\n \n public static void send() {\n Transport transport = null;\n try {\n String accountEmail = \"[email protected]\";\n String accountAppPassword = \"\";\n String displayName = \"Display-Name 東\";\n String replyTo = \"[email protected]\";\n \n String to = \"[email protected]\";\n String cc = \"[email protected]\";\n String bcc = \"[email protected]\";\n \n String subject = \"Subject 東\";\n String message = \"<span style='color: red;'>東</span>\";\n String type = \"html\"; // or \"plain\"\n String mimeTypeWithEncoding = \"text/\" + type + \"; charset=\" + StandardCharsets.UTF_8.name();\n \n File attachmentFile = new File(\"Attachment.pdf\");\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n String attachmentMimeType = \"application/pdf\";\n byte[] bytes = ...; // read file to byte array\n \n Properties properties = System.getProperties();\n properties.put(\"mail.debug\", \"true\");\n // i found that this is the only property necessary for a modern java mail version\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n // https://javaee.github.io/javamail/FAQ#getdefaultinstance\n Session session = Session.getInstance(properties);\n \n MimeMessage mimeMessage = new MimeMessage(session);\n \n // probably best to use the account email address, to avoid landing in spam or blacklists\n // not even sure if the server would accept a differing from address\n InternetAddress from = new InternetAddress(accountEmail);\n from.setPersonal(displayName, StandardCharsets.UTF_8.name());\n mimeMessage.setFrom(from);\n \n mimeMessage.setReplyTo(InternetAddress.parse(replyTo));\n \n mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));\n mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));\n mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));\n \n mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());\n \n MimeMultipart multipart = new MimeMultipart();\n \n MimeBodyPart messagePart = new MimeBodyPart();\n messagePart.setContent(mimeMessage, mimeTypeWithEncoding);\n multipart.addBodyPart(messagePart);\n \n MimeBodyPart attachmentPart = new MimeBodyPart();\n attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));\n attachmentPart.setFileName(attachmentFile.getName());\n multipart.addBodyPart(attachmentPart);\n \n mimeMessage.setContent(multipart);\n \n transport = session.getTransport();\n transport.connect(\"smtp.gmail.com\", 587, accountEmail, accountAppPassword);\n transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());\n }\n catch(Exception e) {\n // I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.\n // I also prefer not to force the exception in the signature.\n throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);\n }\n finally {\n if(transport != null) {\n try {\n transport.close();\n }\n catch(Exception e) {\n LOGGER.log(Level.WARNING, \"failed to close java mail transport: \" + e);\n }\n }\n }\n }\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
46,664
<p>Where can I find the redistributable version of the IBM DB2 Type 4 driver? I suppose this is the driver I would use to connect from a Java app (on windows) to DB2 on the mainframe?</p>
[ { "answer_id": 419401, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": " db2jcc_license_cisuz.jar\n cisuz cu z" }, { "answer_id": 11693489, "author": "harmender", "author_id": 1558460, "author_profile": "https://Stackoverflow.com/users/1558460", "pm_score": 2, "selected": false, "text": "C:\\Program Files\\IBM\\SQLLIB\\java\\db2jcc.jar db2jcc.jar" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,677
<p>I need to find/create an application that will create employee web usage reports from HTTP proxy logs. Does anyone know of a good product that will do this?</p> <p><em>@Joe Liversedge - Good point. I don't have to worry about this, however, as I am the only person in my company with the know-how to pull off an SSH tunnel.</em></p>
[ { "answer_id": 46976, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 3, "selected": true, "text": "awk sort uniq -c" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
46,704
<p>For the following HTML:</p> <pre><code>&lt;form name=&quot;myForm&quot;&gt; &lt;label&gt;One&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;S&quot; /&gt;&lt;/label&gt; &lt;label&gt;Two&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;R&quot; /&gt;&lt;/label&gt; &lt;label&gt;Three&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;O&quot; /&gt;&lt;/label&gt; &lt;label&gt;Four&lt;input name=&quot;area&quot; type=&quot;radio&quot; value=&quot;U&quot; /&gt;&lt;/label&gt; &lt;/form&gt; </code></pre> <p>Changing from the following JavaScript code:</p> <pre><code>$(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i&lt;radios.length; i++) { if (radios[i].value == &quot;S&quot;) { radios[i].checked = true; // Selected when form displays radioClicks(); // Execute the function, initial setup } radios[i].onclick = radioClicks; // Assign to run when clicked } }); </code></pre> <p>Thanks</p> <p>EDIT: The response I selected answers the question I asked, however I like the answer that uses <code>bind()</code> because it also shows how to distinguish the group of radio buttons</p>
[ { "answer_id": 46715, "author": "Adam Cuzzort", "author_id": 4760, "author_profile": "https://Stackoverflow.com/users/4760", "pm_score": 1, "selected": false, "text": "$(function() {\n $('input[@type=\"radio\"]').click(radioClicks);\n});\n" }, { "answer_id": 46717, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "$(function() {\n\n $(\"form#myForm input[type='radio']\").click( fn );\n\n});\n\nfunction fn()\n{\n //do stuff here\n}\n" }, { "answer_id": 46733, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 0, "selected": false, "text": "$(\"input[@type='radio']\").each(function(i) {\n if (this.val() == 'E') {\n radioClicks();\n this.get().checked = true;\n }\n}\n$(\"input[@type='radio']\").click(radioClicks);\n" }, { "answer_id": 46735, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 0, "selected": false, "text": "$(function() {\n $('#myForm :radio').each(function() {\n if ($(this).value == 'S') {\n $(this).attr(\"checked\", true);\n radioClicks();\n }\n\n $(this).click(radioClicks);\n });\n});\n" }, { "answer_id": 46800, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 5, "selected": true, "text": "$( function() {\n $(\"input:radio\")\n .click(radioClicks)\n .filter(\"[value='S']\")\n .attr(\"checked\", \"checked\");\n});\n" }, { "answer_id": 46824, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "$(document).ready(function(){\n $(\"input[name='area']\").bind(\"click\", radioClicks);\n});\n\nfunctionradioClicks() {\n alert($(this).val());\n}\n bind()" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
46,709
<p>When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change. </p> <p>MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated.</p> <p>(Note that I'm <em>not</em> talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level)</p> <p>This has been discussed in other posts here on Stack Overflow. [todo - links]</p> <p>I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC.</p>
[ { "answer_id": 50103, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 2, "selected": false, "text": "SELECT\n dbo.tblBook.BookId,\n dbo.tblBook.RevisionId,\n dbo.tblBook.Title,\n dbo.tblBook.AuthorId,\n dbo.tblBook.Price,\n dbo.tblBook.Deleted\nFROM\n dbo.tblBook INNER JOIN\n (\n SELECT\n BookId,\n MAX(RevisionId) AS RevisionId\n FROM\n dbo.tblBook\n GROUP BY\n BookId\n ) AS CurrentBookRevision ON\n dbo.tblBook.BookId = CurrentBookRevision.BookId AND\n dbo.tblBook.RevisionId = CurrentBookRevision.RevisionId\nWHERE\n dbo.tblBook.Deleted = 0\n ALTER procedure [dbo].[sp_Book_CreateUpdateDelete]\n @BookId uniqueidentifier,\n @RevisionId bigint,\n @Title varchar(256),\n @AuthorId uniqueidentifier,\n @Price smallmoney,\n @Deleted bit\nas\n insert into tblBook\n (\n BookId,\n RevisionId,\n Title,\n AuthorId,\n Price,\n Deleted\n )\n values\n (\n @BookId,\n @RevisionId,\n @Title,\n @AuthorId,\n @Price,\n @Deleted\n )\n Shared Sub Save(ByVal UserId As Guid, ByVal Explanation As String, ByVal Commands As Collections.Generic.Queue(Of SqlCommand))\n Dim Connection As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(\"Connection\").ConnectionString)\n Connection.Open()\n Dim Transaction As SqlTransaction = Connection.BeginTransaction\n Try\n Dim RevisionId As Integer = Nothing\n Dim RevisionCommand As SqlCommand = New SqlCommand(\"sp_Revision_Create\", Connection)\n RevisionCommand.CommandType = CommandType.StoredProcedure\n RevisionCommand.Parameters.AddWithValue(\"@RevisionId\", 0)\n RevisionCommand.Parameters(0).SqlDbType = SqlDbType.BigInt\n RevisionCommand.Parameters(0).Direction = ParameterDirection.Output\n RevisionCommand.Parameters.AddWithValue(\"@UserId\", UserId)\n RevisionCommand.Parameters.AddWithValue(\"@Explanation\", Explanation)\n RevisionCommand.Transaction = Transaction\n LogDatabaseActivity(RevisionCommand)\n If RevisionCommand.ExecuteNonQuery() = 1 Then 'rows inserted\n RevisionId = CInt(RevisionCommand.Parameters(0).Value) 'generated key\n Else\n Throw New Exception(\"Zero rows affected.\")\n End If\n For Each Command As SqlCommand In Commands\n Command.Connection = Connection\n Command.Transaction = Transaction\n Command.CommandType = CommandType.StoredProcedure\n Command.Parameters.AddWithValue(\"@RevisionId\", RevisionId)\n LogDatabaseActivity(Command)\n If Command.ExecuteNonQuery() < 1 Then 'rows inserted\n Throw New Exception(\"Zero rows affected.\")\n End If\n Next\n Transaction.Commit()\n Catch ex As Exception\n Transaction.Rollback()\n Throw New Exception(\"Rolled back transaction\", ex)\n Finally\n Connection.Close()\n End Try\nEnd Sub\n Public Class Book\n Implements iComparable\n\n#Region \" Constructors \"\n\n Private _BookId As Guid\n Private _RevisionId As Integer\n Private _Title As String\n Private _AuthorId As Guid\n Private _Price As Decimal\n Private _Deleted As Boolean\n\n ...\n\n Sub New(ByVal BookRow As DataRow)\n Try\n _BookId = New Guid(BookRow(\"BookId\").ToString)\n _RevisionId = CInt(BookRow(\"RevisionId\"))\n _Title = CStr(BookRow(\"Title\"))\n _AuthorId = New Guid(BookRow(\"AuthorId\").ToString)\n _Price = CDec(BookRow(\"Price\"))\n Catch ex As Exception\n 'TO DO: log exception\n Throw New Exception(\"DataRow does not contain valid Book data.\", ex)\n End Try\n End Sub\n\n#End Region\n\n...\n\n#Region \" Create, Update & Delete \"\n\n Function Save() As SqlCommand\n If _BookId = Guid.Empty Then\n _BookId = Guid.NewGuid()\n End If\n Dim Command As SqlCommand = New SqlCommand(\"sp_Book_CreateUpdateDelete\")\n Command.Parameters.AddWithValue(\"@BookId\", _BookId)\n Command.Parameters.AddWithValue(\"@Title\", _Title)\n Command.Parameters.AddWithValue(\"@AuthorId\", _AuthorId)\n Command.Parameters.AddWithValue(\"@Price\", _Price)\n Command.Parameters.AddWithValue(\"@Deleted\", _Deleted)\n Return Command\n End Function\n\n Shared Function Delete(ByVal BookId As Guid) As SqlCommand\n Dim Doomed As Book = FindByBookId(BookId)\n Doomed.Deleted = True\n Return Doomed.Save()\n End Function\n\n ...\n\n#End Region\n\n...\n\n#Region \" Finders \"\n\n Shared Function FindByBookId(ByVal BookId As Guid, Optional ByVal TryDeleted As Boolean = False) As Book\n Dim Command As SqlCommand\n If TryDeleted Then\n Command = New SqlCommand(\"sp_Book_FindByBookIdTryDeleted\")\n Else\n Command = New SqlCommand(\"sp_Book_FindByBookId\")\n End If\n Command.Parameters.AddWithValue(\"@BookId\", BookId)\n If Database.Find(Command).Rows.Count > 0 Then\n Return New Book(Database.Find(Command).Rows(0))\n Else\n Return Nothing\n End If\n End Function\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
46,714
<p>On Fedora Core 7, I'm writing some code that relies on <code>ARG_MAX</code>. However, even if I <code>#include &lt;limits.h&gt;</code>, the constant is still not defined. My investigations show that it's present in <code>&lt;sys/linux/limits.h&gt;</code>, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here?</p>
[ { "answer_id": 46822, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 4, "selected": true, "text": "sysconf" }, { "answer_id": 69613612, "author": "TheDudeAbides", "author_id": 785213, "author_profile": "https://Stackoverflow.com/users/785213", "pm_score": 1, "selected": false, "text": "cc -x c <(echo '\n #include <unistd.h>\n #include <stdio.h>\n int main() { printf(\"%li\\n\", sysconf(_SC_ARG_MAX)); }\n')\n cc thefile.c $ ./a.out\n262144\n $ ./a.out\n4611686018427387903\n\n$ ./a.out | numfmt --to=iec-i # 'numfmt' from GNU coreutils\n4.0Ei\n cpp <<HERE | tail -1\n#include <limits.h>\nARG_MAX\nHERE\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ]
46,718
<p>I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?</p> <p>Is there one elegant solution that works for the majority of the cases? </p>
[ { "answer_id": 46724, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 5, "selected": true, "text": "media=\"print\" <link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\" />\n" }, { "answer_id": 46728, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\" /> \n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"screen.css\" />\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329/" ]
46,719
<p>I have a regex call that I need help with.</p> <p>I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.</p> <p>Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.</p> <pre><code>RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @"&lt;b&gt;${text}&lt;/b&gt;", regexOptions); </code></pre>
[ { "answer_id": 46722, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "foreach(Match in Regex.Matches(...))\n{\n //do your stuff here\n}\n" }, { "answer_id": 46785, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 3, "selected": true, "text": " protected string FindAndTranslateIn(string content)\n {\n return Regex.Replace(content, @\"\\{\\^(.+?);(.+?)?}\", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase);\n }\n\npublic string TranslateHandler(Match m)\n{\n if (m.Success)\n {\n string key = m.Groups[1].Value;\n key = FindAndTranslateIn(key);\n string def = string.Empty;\n if (m.Groups.Count > 2)\n {\n def = m.Groups[2].Value;\n if(def.Length > 1)\n {\n def = FindAndTranslateIn(def);\n }\n }\n\n if (group == null)\n {\n return Translate(key, def);\n }\n else\n {\n return Translate(key, group, def);\n }\n }\n return string.Empty;\n}\n" }, { "answer_id": 46810, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 2, "selected": false, "text": "public void Stuff()\n{\n string pattern = @\"(?<firstNumber>\\d+)\\s*(?<operator>[*+-/])\\s*(?<secondNumber>\\d+)\";\n string input = \"something something 123 + 456 blah blah 100 - 55\";\n string output = Regex.Replace(input, pattern, MatchMath);\n //output will be \"something something 579 blah blah 45\"\n}\n\nprivate static string MatchMath(Match match)\n{\n try\n {\n double first = double.Parse(match.Groups[\"firstNumber\"].Value);\n double second = double.Parse(match.Groups[\"secondNumber\"].Value);\n switch (match.Groups[\"operator\"].Value)\n {\n case \"*\":\n return (first * second).ToString();\n case \"+\":\n return (first + second).ToString();\n case \"-\":\n return (first - second).ToString();\n case \"/\":\n return (first / second).ToString();\n }\n }\n catch { }\n return \"NaN\"; \n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
46,777
<p>I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.)</p> <p>So I'm thinking that the users shall be able to log in by sending an email to [email protected] with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with [email protected] and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site.</p> <p>Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)?</p> <hr> <p>I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). </p> <p>Since there will be different email addresses for different commands, like <strong>login</strong>@domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email.</p> <hr> <p>There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.</p>
[ { "answer_id": 46794, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 4, "selected": true, "text": "require ('pop3.php');\n\n$pop3 = new pop3_class();\n$pop3->hostname = MAILHOST;\n$pop3->Open();\n$pop3->Login('[email protected]', 'mypassword');\n\nforeach($pop3->ListMessages(\"\",\"\") as $msgidx => $msgsize)\n{\n $headers = \"\";\n $body = \"\";\n\n $pop3->RetrieveMessage($msgidx, $headers, $body, -1);\n}\n */5 * * * * \"wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'\" >> /dev/null 2>&1\n" }, { "answer_id": 55290, "author": "bmb", "author_id": 5298, "author_profile": "https://Stackoverflow.com/users/5298", "pm_score": 1, "selected": false, "text": ":0 hb:\n| /path/to/program\n #!/usr/bin/php\n<?php\n\n$fp=fopen('php://stdin','r');\nwhile($line = fgets($fp)) {\n [do something with each $line of input here]\n}\n\n?>\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
46,788
<p>Is there a way to bind a MemoryStream to asp:image control?</p>
[ { "answer_id": 46801, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 5, "selected": false, "text": "<%@ WebHandler Language=\"C#\" Class=\"ImageHandler\" %>\n\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Web;\n\npublic class ImageHandler : IHttpHandler\n{ \n public void ProcessRequest (HttpContext context)\n {\n context.Response.Clear();\n\n if (!String.IsNullOrEmpty(context.Request.QueryString[\"id\"]))\n {\n int id = Int32.Parse(context.Request.QueryString[\"id\"]);\n\n // Now you have the id, do what you want with it, to get the right image\n // More than likely, just pass it to the method, that builds the image\n Image image = GetImage(id);\n\n // Of course set this to whatever your format is of the image\n context.Response.ContentType = \"image/jpeg\";\n // Save the image to the OutputStream\n image.Save(context.Response.OutputStream, ImageFormat.Jpeg);\n }\n else\n {\n context.Response.ContentType = \"text/html\";\n context.Response.Write(\"<p>Need a valid id</p>\");\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n\n private Image GetImage(int id)\n {\n // Not sure how you are building your MemoryStream\n // Once you have it, you just use the Image class to \n // create the image from the stream.\n MemoryStream stream = new MemoryStream();\n return Image.FromStream(stream);\n }\n}\n <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:Image ID=\"myImage\" ImageUrl=\"~/ImageHandler.ashx?id=1\" runat=\"server\" />\n </div>\n </form>\n</body>\n</html>\n" }, { "answer_id": 46819, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<img src=\"GetImage.aspx?filename=foo\" ... />\n response.Expires = 0;\n response.Buffer = false;\n response.Clear();\n response.ClearHeaders();\n response.ClearContent();\n response.ContentType = \"image/jpeg\";\n response.BinaryWrite(stream);\n response.Flush();\n response.Close();\n" }, { "answer_id": 46894, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<asp:image/> image.ashx image.ashx?ImageID=[Your image ID here]" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
46,805
<p>I want to use an image or icon as a custom cursor in WPF app. How can I do that?</p>
[ { "answer_id": 46817, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 2, "selected": false, "text": "<Window Cursor=\"\"C:\\WINDOWS\\Cursors\\dinosaur.ani\"\" />\n" }, { "answer_id": 265989, "author": "PeterAllenWebb", "author_id": 21365, "author_profile": "https://Stackoverflow.com/users/21365", "pm_score": 6, "selected": true, "text": "this.Cursor = Cursors.None; Cursor(string fileName) Cursor(Stream cursorStream)" }, { "answer_id": 410517, "author": "Ben McIntosh", "author_id": 50859, "author_profile": "https://Stackoverflow.com/users/50859", "pm_score": 5, "selected": false, "text": "<Window.Resources>\n <ResourceDictionary>\n <TextBlock x:Key=\"CursorGrab\" Cursor=\"Resources/Cursors/grab.cur\"/>\n <TextBlock x:Key=\"CursorMagnify\" Cursor=\"Resources/Cursors/magnify.cur\"/>\n </ResourceDictionary>\n</Window.Resources>\n if (selectedTool == \"Hand\")\n myCanvas.Cursor = ((TextBlock)this.Resources[\"CursorGrab\"]).Cursor;\nelse if (selectedTool == \"Magnify\")\n myCanvas.Cursor = ((TextBlock)this.Resources[\"CursorMagnify\"]).Cursor;\nelse\n myCanvas.Cursor = Cursor.Arrow;\n" }, { "answer_id": 2837158, "author": "Ray Burns", "author_id": 199245, "author_profile": "https://Stackoverflow.com/users/199245", "pm_score": 4, "selected": false, "text": "public Cursor ConvertToCursor(FrameworkElement visual, Point hotSpot)\n{\n int width = (int)visual.Width;\n int height = (int)visual.Height;\n\n // Render to a bitmap\n var bitmapSource = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);\n bitmapSource.Render(visual);\n\n // Convert to System.Drawing.Bitmap\n var pixels = new int[width*height];\n bitmapSource.CopyPixels(pixels, width, 0);\n var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);\n for(int y=0; y<height; y++)\n for(int x=0; x<width; x++)\n bitmap.SetPixel(x, y, Color.FromArgb(pixels[y*width+x]));\n\n // Save to .ico format\n var stream = new MemoryStream();\n System.Drawing.Icon.FromHandle(resultBitmap.GetHicon()).Save(stream);\n\n // Convert saved file into .cur format\n stream.Seek(2, SeekOrigin.Begin);\n stream.WriteByte(2);\n stream.Seek(10, SeekOrigin.Begin);\n stream.WriteByte((byte)(int)(hotSpot.X * width));\n stream.WriteByte((byte)(int)(hotSpot.Y * height));\n stream.Seek(0, SeekOrigin.Begin);\n\n // Construct Cursor\n return new Cursor(stream);\n}\n <Grid x:Name=\"customCursor\" Width=\"32\" Height=\"32\">\n ...\n</Grid>\n someControl.Cursor = ConvertToCursor(customCursor, new Point(0.5, 0.5));\n <Image>" }, { "answer_id": 8346911, "author": "paulmcguinness", "author_id": 1076136, "author_profile": "https://Stackoverflow.com/users/1076136", "pm_score": 3, "selected": false, "text": "this.Cursor System.Windows.Resources.StreamResourceInfo info = \n Application.GetResourceStream(new \n Uri(\"/MainApp;component/Resources/HandDown.cur\", UriKind.Relative));\n\n this.Cursor = new System.Windows.Input.Cursor(info.Stream); \n MainApp Resources" }, { "answer_id": 8715560, "author": "Greg", "author_id": 555993, "author_profile": "https://Stackoverflow.com/users/555993", "pm_score": 3, "selected": false, "text": "myCanvas.Cursor = new Cursor(new System.IO.MemoryStream(myNamespace.Properties.Resources.Cursor1));\n" }, { "answer_id": 13395359, "author": "Matthias", "author_id": 1739297, "author_profile": "https://Stackoverflow.com/users/1739297", "pm_score": 1, "selected": false, "text": " public static Cursor CreateCursor(this Icon icon, bool includeCrossHair, System.Drawing.Color crossHairColor)\n {\n if (icon == null)\n return Cursors.Arrow;\n\n // create an empty image\n int width = icon.Width;\n int height = icon.Height;\n\n using (var cursor = new Bitmap(width * 2, height * 2))\n {\n // create a graphics context, so that we can draw our own cursor\n using (var gr = System.Drawing.Graphics.FromImage(cursor))\n {\n // a cursor is usually 32x32 pixel so we need our icon in the lower right part of it\n gr.DrawIcon(icon, new Rectangle(width, height, width, height));\n\n if (includeCrossHair)\n {\n using (var pen = new System.Drawing.Pen(crossHairColor))\n {\n // draw the cross-hair\n gr.DrawLine(pen, width - 3, height, width + 3, height);\n gr.DrawLine(pen, width, height - 3, width, height + 3);\n }\n }\n }\n\n try\n {\n using (var stream = new MemoryStream())\n {\n // Save to .ico format\n var ptr = cursor.GetHicon();\n var tempIcon = Icon.FromHandle(ptr);\n tempIcon.Save(stream);\n\n int x = cursor.Width/2;\n int y = cursor.Height/2;\n\n #region Convert saved stream into .cur format\n\n // set as .cur file format\n stream.Seek(2, SeekOrigin.Begin);\n stream.WriteByte(2);\n\n // write the hotspot information\n stream.Seek(10, SeekOrigin.Begin);\n stream.WriteByte((byte)(width));\n stream.Seek(12, SeekOrigin.Begin);\n stream.WriteByte((byte)(height));\n \n // reset to initial position\n stream.Seek(0, SeekOrigin.Begin);\n\n #endregion\n\n\n DestroyIcon(tempIcon.Handle); // destroy GDI resource\n\n return new Cursor(stream);\n }\n }\n catch (Exception)\n {\n return Cursors.Arrow;\n }\n }\n }\n\n /// <summary>\n /// Destroys the icon.\n /// </summary>\n /// <param name=\"handle\">The handle.</param>\n /// <returns></returns>\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n public extern static Boolean DestroyIcon(IntPtr handle);\n" }, { "answer_id": 16560633, "author": "kkCosmo", "author_id": 1374375, "author_profile": "https://Stackoverflow.com/users/1374375", "pm_score": 4, "selected": false, "text": "<Window.Resources> \n <Cursor x:Key=\"OpenHandCursor\">Resources/openhand.cur</Cursor>\n</Window.Resources>\n <StackPanel Cursor=\"{StaticResource OpenHandCursor}\" />\n" }, { "answer_id": 24246960, "author": "Gábor", "author_id": 2076286, "author_profile": "https://Stackoverflow.com/users/2076286", "pm_score": 3, "selected": false, "text": "private struct IconInfo {\n public bool fIcon;\n public int xHotspot;\n public int yHotspot;\n public IntPtr hbmMask;\n public IntPtr hbmColor;\n}\n\n[DllImport(\"user32.dll\")]\nprivate static extern IntPtr CreateIconIndirect(ref IconInfo icon);\n\n[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);\n\npublic Cursor ConvertToCursor(FrameworkElement cursor, Point HotSpot) {\n cursor.Arrange(new Rect(new Size(cursor.Width, cursor.Height)));\n var bitmap = new RenderTargetBitmap((int)cursor.Width, (int)cursor.Height, 96, 96, PixelFormats.Pbgra32);\n bitmap.Render(cursor);\n\n var info = new IconInfo();\n GetIconInfo(bitmap.ToBitmap().GetHicon(), ref info);\n info.fIcon = false;\n info.xHotspot = (byte)(HotSpot.X * cursor.Width);\n info.yHotspot = (byte)(HotSpot.Y * cursor.Height);\n\n return CursorInteropHelper.Create(new SafeFileHandle(CreateIconIndirect(ref info), true));\n}\n using DW = System.Drawing;\n\npublic static DW.Bitmap ToBitmap(this BitmapSource bitmapSource) {\n var bitmap = new DW.Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, DW.Imaging.PixelFormat.Format32bppPArgb);\n var data = bitmap.LockBits(new DW.Rectangle(DW.Point.Empty, bitmap.Size), DW.Imaging.ImageLockMode.WriteOnly, DW.Imaging.PixelFormat.Format32bppPArgb);\n bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);\n bitmap.UnlockBits(data);\n return bitmap;\n}\n public Cursor ConvertToCursor(FrameworkElement cursor, Point HotSpot) {\n cursor.Arrange(new Rect(new Size(cursor.Width, cursor.Height)));\n var bitmap = new RenderTargetBitmap((int)cursor.Width, (int)cursor.Height, 96, 96, PixelFormats.Pbgra32);\n bitmap.Render(cursor);\n var icon = System.Drawing.Icon.FromHandle(bitmap.ToBitmap().GetHicon());\n return CursorInteropHelper.Create(new SafeFileHandle(icon.Handle, true));\n}\n" }, { "answer_id": 27077188, "author": "gjacobs", "author_id": 3560034, "author_profile": "https://Stackoverflow.com/users/3560034", "pm_score": 4, "selected": false, "text": " public Cursor ConvertToCursor(UIElement control, Point hotSpot)\n {\n // convert FrameworkElement to PNG stream\n var pngStream = new MemoryStream();\n control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));\n Rect rect = new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height);\n RenderTargetBitmap rtb = new RenderTargetBitmap((int)control.DesiredSize.Width, (int)control.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);\n\n control.Arrange(rect);\n rtb.Render(control);\n\n PngBitmapEncoder png = new PngBitmapEncoder();\n png.Frames.Add(BitmapFrame.Create(rtb));\n png.Save(pngStream);\n\n // write cursor header info\n var cursorStream = new MemoryStream();\n cursorStream.Write(new byte[2] { 0x00, 0x00 }, 0, 2); // ICONDIR: Reserved. Must always be 0.\n cursorStream.Write(new byte[2] { 0x02, 0x00 }, 0, 2); // ICONDIR: Specifies image type: 1 for icon (.ICO) image, 2 for cursor (.CUR) image. Other values are invalid\n cursorStream.Write(new byte[2] { 0x01, 0x00 }, 0, 2); // ICONDIR: Specifies number of images in the file.\n cursorStream.Write(new byte[1] { (byte)control.DesiredSize.Width }, 0, 1); // ICONDIRENTRY: Specifies image width in pixels. Can be any number between 0 and 255. Value 0 means image width is 256 pixels.\n cursorStream.Write(new byte[1] { (byte)control.DesiredSize.Height }, 0, 1); // ICONDIRENTRY: Specifies image height in pixels. Can be any number between 0 and 255. Value 0 means image height is 256 pixels.\n cursorStream.Write(new byte[1] { 0x00 }, 0, 1); // ICONDIRENTRY: Specifies number of colors in the color palette. Should be 0 if the image does not use a color palette.\n cursorStream.Write(new byte[1] { 0x00 }, 0, 1); // ICONDIRENTRY: Reserved. Should be 0.\n cursorStream.Write(new byte[2] { (byte)hotSpot.X, 0x00 }, 0, 2); // ICONDIRENTRY: Specifies the horizontal coordinates of the hotspot in number of pixels from the left.\n cursorStream.Write(new byte[2] { (byte)hotSpot.Y, 0x00 }, 0, 2); // ICONDIRENTRY: Specifies the vertical coordinates of the hotspot in number of pixels from the top.\n cursorStream.Write(new byte[4] { // ICONDIRENTRY: Specifies the size of the image's data in bytes\n (byte)((pngStream.Length & 0x000000FF)),\n (byte)((pngStream.Length & 0x0000FF00) >> 0x08),\n (byte)((pngStream.Length & 0x00FF0000) >> 0x10),\n (byte)((pngStream.Length & 0xFF000000) >> 0x18)\n }, 0, 4);\n cursorStream.Write(new byte[4] { // ICONDIRENTRY: Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file\n (byte)0x16,\n (byte)0x00,\n (byte)0x00,\n (byte)0x00,\n }, 0, 4);\n\n // copy PNG stream to cursor stream\n pngStream.Seek(0, SeekOrigin.Begin);\n pngStream.CopyTo(cursorStream);\n\n // return cursor stream\n cursorStream.Seek(0, SeekOrigin.Begin);\n return new Cursor(cursorStream);\n }\n" }, { "answer_id": 43604577, "author": "Ahmad", "author_id": 6631692, "author_profile": "https://Stackoverflow.com/users/6631692", "pm_score": 2, "selected": false, "text": "this.Cursor = new Cursor(@\"<your address of icon>\");\n" }, { "answer_id": 44100957, "author": "Steve Miller", "author_id": 2079118, "author_profile": "https://Stackoverflow.com/users/2079118", "pm_score": 1, "selected": false, "text": "<Setter\n Property=\"Cursor\"\n Value=\"/assembly-name;component/location-name/curser-name.cur\" />\n" }, { "answer_id": 69804048, "author": "Imagin", "author_id": 17283045, "author_profile": "https://Stackoverflow.com/users/17283045", "pm_score": 0, "selected": false, "text": "<Button MyLibrary:FrameworkElementExtensions.Cursor=\"\"{MyLibrary:Uri MyAssembly, MyImageFolder/MyImage.png}\"\"/>\n using System;\nusing System.Windows;\nusing System.Windows.Media;\n\npublic static class FrameworkElementExtensions\n{\n #region Cursor\n\n public static readonly DependencyProperty CursorProperty = DependencyProperty.RegisterAttached(\"Cursor\", typeof(Uri), typeof(FrameworkElementExtensions), new UIPropertyMetadata(default(Uri), OnCursorChanged));\n public static Uri GetCursor(FrameworkElement i) => (Uri)i.GetValue(CursorProperty);\n public static void SetCursor(FrameworkElement i, Uri input) => i.SetValue(CursorProperty, input);\n static void OnCursorChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if (sender is FrameworkElement frameworkElement)\n {\n if (GetCursor(frameworkElement) != null)\n frameworkElement.Cursor = new ImageSourceConverter().ConvertFromString(((Uri)e.NewValue).OriginalString).As<ImageSource>().Bitmap().Cursor(0, 0).Convert();\n }\n }\n\n #endregion\n}\n using System.Drawing;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\n\npublic static class ImageSourceExtensions\n{\n public static Bitmap Bitmap(this ImageSource input) => input.As<BitmapSource>().Bitmap();\n}\n using System.IO;\nusing System.Windows.Media.Imaging;\n\npublic static class BitmapSourceExtensions\n{\n public static System.Drawing.Bitmap Bitmap(this BitmapSource input)\n {\n if (input == null)\n return null;\n\n System.Drawing.Bitmap result;\n using (var outStream = new MemoryStream())\n {\n var encoder = new PngBitmapEncoder();\n encoder.Frames.Add(BitmapFrame.Create(input));\n encoder.Save(outStream);\n result = new System.Drawing.Bitmap(outStream);\n }\n return result;\n }\n}\n using System;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\n\npublic static class BitmapExtensions\n{\n\n [StructLayout(LayoutKind.Sequential)]\n public struct ICONINFO\n {\n /// <summary>\n /// Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies an icon; FALSE specifies a cursor. \n /// </summary>\n public bool fIcon;\n\n /// <summary>\n /// Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.\n /// </summary>\n public Int32 xHotspot;\n\n /// <summary>\n /// Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored. \n /// </summary>\n public Int32 yHotspot;\n\n /// <summary>\n /// (HBITMAP) Specifies the icon bitmask bitmap. If this structure defines a black and white icon, this bitmask is formatted so that the upper half is the icon AND bitmask and the lower half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. If this structure defines a color icon, this mask only defines the AND bitmask of the icon. \n /// </summary>\n public IntPtr hbmMask;\n\n /// <summary>\n /// (HBITMAP) Handle to the icon color bitmap. This member can be optional if this structure defines a black and white icon. The AND bitmask of hbmMask is applied with the SRCAND flag to the destination; subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag. \n /// </summary>\n public IntPtr hbmColor;\n }\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr CreateIconIndirect([In] ref ICONINFO piconinfo);\n\n [DllImport(\"user32.dll\")]\n static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO piconinfo);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern bool DestroyIcon(IntPtr hIcon);\n\n public static System.Windows.Forms.Cursor Cursor(this Bitmap input, int hotX, int hotY)\n {\n ICONINFO Info = new ICONINFO();\n IntPtr Handle = input.GetHicon();\n GetIconInfo(Handle, out Info);\n\n Info.xHotspot = hotX;\n Info.yHotspot = hotY;\n Info.fIcon = false;\n\n IntPtr h = CreateIconIndirect(ref Info);\n return new System.Windows.Forms.Cursor(h);\n }\n}\n using Microsoft.Win32.SafeHandles;\n\npublic static class CursorExtensions\n{\n public static System.Windows.Input.Cursor Convert(this System.Windows.Forms.Cursor Cursor)\n {\n SafeFileHandle h = new SafeFileHandle(Cursor.Handle, false);\n return System.Windows.Interop.CursorInteropHelper.Create(h);\n }\n}\n public static Type As<Type>(this object input) => input is Type ? (Type)input : default;\n using System;\nusing System.Windows.Markup;\n\npublic class Uri : MarkupExtension\n{\n public string Assembly { get; set; } = null;\n\n public string RelativePath { get; set; }\n\n public Uri(string relativePath) : base()\n {\n RelativePath = relativePath;\n }\n\n public Uri(string assembly, string relativePath) : this(relativePath)\n {\n Assembly = assembly;\n }\n\n static Uri Get(string assemblyName, string relativePath) => new Uri($\"pack://application:,,,/{assemblyName};component/{relativePath}\", UriKind.Absolute);\n\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n if (Assembly == null)\n return new System.Uri(RelativePath, UriKind.Relative);\n\n return Get(Assembly, RelativePath);\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1133/" ]
46,827
<p>Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?</p>
[ { "answer_id": 46832, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 7, "selected": true, "text": "ALTER TABLE Orders\nADD CONSTRAINT FK_Customer_Order\nFOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)\n" }, { "answer_id": 46834, "author": "Ryan Shripat", "author_id": 1943, "author_profile": "https://Stackoverflow.com/users/1943", "pm_score": 3, "selected": false, "text": "ALTER TABLE tblAlpha\nADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES\ntblGamma(GammaID)\nON UPDATE CASCADE\n SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS\n" }, { "answer_id": 16894739, "author": "shahwazir haqmall", "author_id": 2447464, "author_profile": "https://Stackoverflow.com/users/2447464", "pm_score": 1, "selected": false, "text": "create table employee\n(\n empid int,\n empname varchar(40),\n designation varchar(30),\n hiredate datetime, \n Bsalary int,\n depno constraint emp_m foreign key references department(depno)\n)\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943/" ]
46,841
<p>Occasionally, on a ASP (classic) site users will get this error:</p> <pre><code>[DBNETLIB][ConnectionRead (recv()).]General network error. </code></pre> <p>Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?</p>
[ { "answer_id": 39923881, "author": "Shrikrishna Vhale", "author_id": 6938776, "author_profile": "https://Stackoverflow.com/users/6938776", "pm_score": 0, "selected": false, "text": "netsh advfirewall set allprofiles state off\n" }, { "answer_id": 49283898, "author": "AjV Jsy", "author_id": 2078245, "author_profile": "https://Stackoverflow.com/users/2078245", "pm_score": 0, "selected": false, "text": "OPTION (OPTIMIZE FOR UNKNOWN)" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4835/" ]
46,842
<p>What is the best way to determine duplicate records in a SQL Server table?</p> <p>For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).</p> <p>Sample data:</p> <pre><code>1 01/01/2008 [email protected] 2 02/01/2008 [email protected] 3 01/12/2008 [email protected] </code></pre>
[ { "answer_id": 46845, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 3, "selected": false, "text": "select email ,max(receiveddate) as MaxDate\nfrom YourTable\ngroup by email \nhaving count(email) > 1\n" }, { "answer_id": 46846, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 0, "selected": false, "text": "select * from table a, table b\nwhere a.email = b.email\n" }, { "answer_id": 46849, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "SELECT [id], [receivedate], [email]\nFROM [mytable]\nWHERE [email] IN ( SELECT [email]\n FROM [myTable]\n GROUP BY [email]\n HAVING COUNT([email]) > 1 )\n" }, { "answer_id": 46853, "author": "enigmatic", "author_id": 443575, "author_profile": "https://Stackoverflow.com/users/443575", "pm_score": 0, "selected": false, "text": "SELECT [info] FROM [table] t WHERE NOT EXISTS (SELECT * FROM [table] tCheck WHERE t.date > tCheck.date)\n SELECT [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 DESC\n SELECT TOP 1 [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 ORDER BY Date DESC\n" }, { "answer_id": 46861, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 0, "selected": false, "text": "Create table people (ID(PK), Name, Address, DOB)\n\nDelete from people where id not in (\nSelect min(ID) from people group by name, address, dob\n)\n" }, { "answer_id": 14757344, "author": "user2051770", "author_id": 2051770, "author_profile": "https://Stackoverflow.com/users/2051770", "pm_score": 1, "selected": false, "text": "SELECT * FROM (\n SELECT *, \n ROW_NUMBER() OVER (PARTITION BY ReceivedDate, Email ORDER BY ReceivedDate, Email DESC) AS RowNumber \n FROM EmailTable\n) a\nWHERE RowNumber = 1\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
46,860
<p>I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?</p>
[ { "answer_id": 46866, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "SendMessage EM_SETCUEBANNER" }, { "answer_id": 46878, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": false, "text": "TextInput myInput;\nboolean showingHint = true;\n\nmyInput.text = \"Search Terms\";\nmyInput.color = 0xcccccc;\n\nmyInput.onFocusGained = function() {\n if(showingHint) {\n myInput.text = \"\";\n myInput.color = 0x000000;\n showingHint = false;\n }\n}\n\nmyInput.onFocusLost = function() {\n if(!showingHint && myInput.text.length == 0) {\n myInput.text = \"Search Terms\";\n myInput.color = 0xcccccc;\n showingHint = true;\n }\n}\n" }, { "answer_id": 11971944, "author": "Esen", "author_id": 1221319, "author_profile": "https://Stackoverflow.com/users/1221319", "pm_score": 2, "selected": false, "text": " //Copyright (c) 2008 Jason Kemp\n\n //Permission is hereby granted, free of charge, to any person obtaining a copy\n //of this software and associated documentation files (the \"Software\"), to deal\n //in the Software without restriction, including without limitation the rights\n //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n //copies of the Software, and to permit persons to whom the Software is\n //furnished to do so, subject to the following conditions:\n\n //The above copyright notice and this permission notice shall be included in\n //all copies or substantial portions of the Software.\n\n //THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n //THE SOFTWARE.\n\n using System;\n using System.Runtime.InteropServices;\n using System.Windows.Forms;\n using System.Text;\n\n\n public static class Win32Utility\n {\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern Int32 SendMessage(IntPtr hWnd, int msg,\n int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SendMessage(IntPtr hwnd, int msg, int wParam, StringBuilder lParam);\n\n [DllImport(\"user32.dll\")]\n private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);\n\n [StructLayout(LayoutKind.Sequential)]\n private struct COMBOBOXINFO\n {\n public int cbSize;\n public RECT rcItem;\n public RECT rcButton;\n public IntPtr stateButton;\n public IntPtr hwndCombo;\n public IntPtr hwndItem;\n public IntPtr hwndList;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n private const int EM_SETCUEBANNER = 0x1501;\n private const int EM_GETCUEBANNER = 0x1502;\n\n public static void SetCueText(Control control, string text)\n {\n if (control is ComboBox)\n {\n COMBOBOXINFO info = GetComboBoxInfo(control);\n SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);\n }\n else\n {\n SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);\n }\n }\n\n private static COMBOBOXINFO GetComboBoxInfo(Control control)\n {\n COMBOBOXINFO info = new COMBOBOXINFO();\n //a combobox is made up of three controls, a button, a list and textbox;\n //we want the textbox\n info.cbSize = Marshal.SizeOf(info);\n GetComboBoxInfo(control.Handle, ref info);\n return info;\n }\n\n public static string GetCueText(Control control)\n {\n StringBuilder builder = new StringBuilder();\n if (control is ComboBox)\n {\n COMBOBOXINFO info = new COMBOBOXINFO();\n //a combobox is made up of two controls, a list and textbox;\n //we want the textbox\n info.cbSize = Marshal.SizeOf(info);\n GetComboBoxInfo(control.Handle, ref info);\n SendMessage(info.hwndItem, EM_GETCUEBANNER, 0, builder);\n }\n else\n {\n SendMessage(control.Handle, EM_GETCUEBANNER, 0, builder);\n }\n return builder.ToString();\n }\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826/" ]
46,863
<p>How do I concatenate together two strings, of unknown length, in COBOL? So for example:</p> <pre><code>WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. </code></pre> <p>If <code>FIRST-NAME = 'JOHN '</code> and <code>LAST-NAME = 'DOE '</code>, how can I get:</p> <pre><code>FULL-NAME = 'JOHN DOE ' </code></pre> <p>as opposed to:</p> <pre><code>FULL-NAME = 'JOHN DOE ' </code></pre>
[ { "answer_id": 46899, "author": "Eric H", "author_id": 4650, "author_profile": "https://Stackoverflow.com/users/4650", "pm_score": 2, "selected": false, "text": "WORK-FIELD PIC X(15) VALUE SPACES.\nTRAILING-SPACES PIC 9(3) VALUE ZERO.\nFIELD-LENGTH PIC 9(3) VALUE ZERO.\n" }, { "answer_id": 47119, "author": "Thayne", "author_id": 3749, "author_profile": "https://Stackoverflow.com/users/3749", "pm_score": 4, "selected": true, "text": "STRING\nFIRST-NAME DELIMITED BY \" \",\n\" \",\nLAST-NAME DELIMITED BY SIZE\nINTO FULL-NAME.\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4650/" ]
46,898
<p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p> <p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>
[ { "answer_id": 46905, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 8, "selected": false, "text": "Iterator entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n Entry thisEntry = (Entry) entries.next();\n Object key = thisEntry.getKey();\n Object value = thisEntry.getValue();\n // ...\n}\n" }, { "answer_id": 46908, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 13, "selected": true, "text": "Map<String, String> map = ...\nfor (Map.Entry<String, String> entry : map.entrySet()) {\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n}\n for (var entry : map.entrySet()) {\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n}\n" }, { "answer_id": 46912, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 5, "selected": false, "text": "map.entrySet() Map.Entry entry.getKey() entry.getValue() map.keySet() map.entrySet() valueSet() entrySet()" }, { "answer_id": 46926, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 7, "selected": false, "text": "Map<String,Thing> map = ...;\nfor (Map.Entry<String,Thing> entry : map.entrySet()) {\n String key = entry.getKey();\n Thing thing = entry.getValue();\n ...\n}\n HashMap SortedMap Comparator LinkedHashMap EnumMap IdentityHashMap entrySet Map.Entry entrySet Map.Entry" }, { "answer_id": 46989, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 7, "selected": false, "text": "Map SortedMap Map NavigableMap SortedMap entry higherEntry lowerEntry ceilingEntry floorEntry descendingMap" }, { "answer_id": 47004, "author": "ckpwong", "author_id": 2551, "author_profile": "https://Stackoverflow.com/users/2551", "pm_score": 6, "selected": false, "text": "map.keySet() map.values()" }, { "answer_id": 48720, "author": "Chris Dail", "author_id": 5077, "author_profile": "https://Stackoverflow.com/users/5077", "pm_score": 6, "selected": false, "text": "for (String key: map.keySet()) {\n System.out.println(key + \"/\" + map.get(key));\n}\n" }, { "answer_id": 1295383, "author": "serg", "author_id": 20128, "author_profile": "https://Stackoverflow.com/users/20128", "pm_score": 7, "selected": false, "text": "Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry<String, String> entry = entries.next();\n String key = entry.getKey();\n String value = entry.getValue();\n // ...\n}\n" }, { "answer_id": 2190043, "author": "abods", "author_id": 265011, "author_profile": "https://Stackoverflow.com/users/265011", "pm_score": 5, "selected": false, "text": "for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){\n\n Entry entry = (Entry) entries.next();\n\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n\n //...\n}\n" }, { "answer_id": 10632923, "author": "Fathah Rehman P", "author_id": 991065, "author_profile": "https://Stackoverflow.com/users/991065", "pm_score": 4, "selected": false, "text": "public class abcd{\n public static void main(String[] args)\n {\n Map<Integer, String> testMap = new HashMap<Integer, String>();\n testMap.put(10, \"a\");\n testMap.put(20, \"b\");\n testMap.put(30, \"c\");\n testMap.put(40, \"d\");\n for (Integer key:testMap.keySet()) {\n String value=testMap.get(key);\n System.out.println(value);\n }\n }\n}\n public class abcd {\n public static void main(String[] args)\n {\n Map<Integer, String> testMap = new HashMap<Integer, String>();\n testMap.put(10, \"a\");\n testMap.put(20, \"b\");\n testMap.put(30, \"c\");\n testMap.put(40, \"d\");\n for (Entry<Integer, String> entry : testMap.entrySet()) {\n Integer key=entry.getKey();\n String value=entry.getValue();\n }\n }\n}\n" }, { "answer_id": 13943066, "author": "Donald Raab", "author_id": 1570415, "author_profile": "https://Stackoverflow.com/users/1570415", "pm_score": 5, "selected": false, "text": "forEachKeyValue MapIterable MutableMap ImmutableMap MutableBag<String> result = Bags.mutable.empty();\nMutableMap<Integer, String> map = Maps.mutable.of(1, \"One\", 2, \"Two\", 3, \"Three\");\nmap.forEachKeyValue((key, value) -> result.add(key + value));\nAssert.assertEquals(Bags.mutable.of(\"1One\", \"2Two\", \"3Three\"), result);\n final MutableBag<String> result = Bags.mutable.empty();\nMutableMap<Integer, String> map = Maps.mutable.of(1, \"One\", 2, \"Two\", 3, \"Three\");\nmap.forEachKeyValue(new Procedure2<Integer, String>()\n{\n public void value(Integer key, String value)\n {\n result.add(key + value);\n }\n});\nAssert.assertEquals(Bags.mutable.of(\"1One\", \"2Two\", \"3Three\"), result);\n" }, { "answer_id": 15556457, "author": "Suresh Atta", "author_id": 1927832, "author_profile": "https://Stackoverflow.com/users/1927832", "pm_score": 3, "selected": false, "text": "Map nullpointerexception null null |\n |\n - - - -\n |\n |\nfor (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n}\n" }, { "answer_id": 17404976, "author": "Learner", "author_id": 1918772, "author_profile": "https://Stackoverflow.com/users/1918772", "pm_score": 4, "selected": false, "text": "Map<Integer, Integer> map = new HashMap<Integer, Integer>();\nIterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry<Integer, Integer> entry = entries.next();\n System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue());\n}\n" }, { "answer_id": 19491759, "author": "The Coordinator", "author_id": 1584255, "author_profile": "https://Stackoverflow.com/users/1584255", "pm_score": 8, "selected": false, "text": " Map<String,String> map = new HashMap<>();\n map.put(\"SomeKey\", \"SomeValue\");\n map.forEach( (k,v) -> [do something with key and value] );\n\n // such as\n map.forEach( (k,v) -> System.out.println(\"Key: \" + k + \": Value: \" + v));\n k v Map.Entry" }, { "answer_id": 20286334, "author": "dmunozfer", "author_id": 1276364, "author_profile": "https://Stackoverflow.com/users/1276364", "pm_score": 5, "selected": false, "text": "Map map = new HashMap();\nfor (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n}\n" }, { "answer_id": 20903678, "author": "J.B.Vala", "author_id": 3141443, "author_profile": "https://Stackoverflow.com/users/3141443", "pm_score": 3, "selected": false, "text": "Entry<K,V> entrySet() import java.util.*;\n import java.util.HashMap;\n import java.util.Iterator;\n import java.util.Map;\n\n public class IteratMapDemo{\n\n public static void main(String arg[]){\n Map<String, String> mapOne = new HashMap<String, String>();\n mapOne.put(\"1\", \"January\");\n mapOne.put(\"2\", \"February\");\n mapOne.put(\"3\", \"March\");\n mapOne.put(\"4\", \"April\");\n mapOne.put(\"5\", \"May\");\n mapOne.put(\"6\", \"June\");\n mapOne.put(\"7\", \"July\");\n mapOne.put(\"8\", \"August\");\n mapOne.put(\"9\", \"September\");\n mapOne.put(\"10\", \"Octomber\");\n mapOne.put(\"11\", \"November\");\n mapOne.put(\"12\", \"December\");\n\n Iterator it = mapOne.entrySet().iterator();\n while(it.hasNext())\n {\n Map.Entry me = (Map.Entry) it.next();\n //System.out.println(\"Get Key through While loop = \" + me.getKey());\n }\n for(Map.Entry<String, String> entry:mapOne.entrySet()){\n //System.out.println(entry.getKey() + \"=\" + entry.getValue());\n }\n\n for (Object key : mapOne.keySet()) {\n System.out.println(\"Key: \" + key.toString() + \" Value: \" +\n mapOne.get(key));\n }\n }\n }\n" }, { "answer_id": 21431305, "author": "Rupesh Yadav", "author_id": 918472, "author_profile": "https://Stackoverflow.com/users/918472", "pm_score": 5, "selected": false, "text": "keys values both (e.g., entrySet) keys -> keySet() Map<String, Object> map = ...;\n\n for (String key : map.keySet()) {\n //your Business logic...\n }\n values -> values() for (Object value : map.values()) {\n //your Business logic...\n }\n both -> entrySet() for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n //your Business logic...\n }\n //1.\nfor (Map.Entry entry : hm.entrySet()) {\n System.out.print(\"key,val: \");\n System.out.println(entry.getKey() + \",\" + entry.getValue());\n}\n\n//2.\nIterator iter = hm.keySet().iterator();\nwhile(iter.hasNext()) {\n Integer key = (Integer)iter.next();\n String val = (String)hm.get(key);\n System.out.println(\"key,val: \" + key + \",\" + val);\n}\n\n//3.\nIterator it = hm.entrySet().iterator();\nwhile (it.hasNext()) {\n Map.Entry entry = (Map.Entry) it.next();\n Integer key = (Integer)entry.getKey();\n String val = (String)entry.getValue();\n System.out.println(\"key,val: \" + key + \",\" + val);\n}\n" }, { "answer_id": 21570332, "author": "Darshan Patel", "author_id": 3131537, "author_profile": "https://Stackoverflow.com/users/3131537", "pm_score": 6, "selected": false, "text": "entrySet() for (Map.Entry<String,Integer> entry : testMap.entrySet()) {\n entry.getKey();\n entry.getValue();\n}\n keySet() for (String key : testMap.keySet()) {\n testMap.get(key);\n}\n entrySet() Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();\nwhile(itr1.hasNext()) {\n Map.Entry<String,Integer> entry = itr1.next();\n entry.getKey();\n entry.getValue();\n}\n keySet() Iterator itr2 = testMap.keySet().iterator();\nwhile(itr2.hasNext()) {\n String key = itr2.next();\n testMap.get(key);\n}\n this link" }, { "answer_id": 22513787, "author": "Fadid", "author_id": 3254469, "author_profile": "https://Stackoverflow.com/users/3254469", "pm_score": 4, "selected": false, "text": " Iterator iterator = map.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry element = (Map.Entry)it.next();\n LOGGER.debug(\"Key: \" + element.getKey());\n LOGGER.debug(\"value: \" + element.getValue()); \n }\n" }, { "answer_id": 25116661, "author": "Georgios Syngouroglou", "author_id": 1123501, "author_profile": "https://Stackoverflow.com/users/1123501", "pm_score": 5, "selected": false, "text": "myMap.entrySet().stream().forEach((entry) -> {\n Object currentKey = entry.getKey();\n Object currentValue = entry.getValue();\n});\n" }, { "answer_id": 25436802, "author": "fechidal89", "author_id": 1941878, "author_profile": "https://Stackoverflow.com/users/1941878", "pm_score": 2, "selected": false, "text": "HashMap product =(HashMap)shopping_truck.get(i);\nHashMap tmp = new HashMap();\nfor (Iterator it = product.entrySet().iterator(); it.hasNext();) {\n Map.Entry thisEntry = (Map.Entry) it.next();\n tmp.put(thisEntry.getKey(), thisEntry.getValue());\n}\n" }, { "answer_id": 27871427, "author": "JohnK", "author_id": 1431728, "author_profile": "https://Stackoverflow.com/users/1431728", "pm_score": 2, "selected": false, "text": "Map<Ktype, Vtype> myMap = [...];\nfor (Vtype v: myMap.values()) {\n System.out.println(\"value: \" + v);\n}\n Ktype Vtype" }, { "answer_id": 30215019, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 3, "selected": false, "text": "Map import java.util.Iterator;\nimport java.util.Map;\n\npublic class MapUtils {\n static interface ItemCallback<K, V> {\n void handler(K key, V value, Map<K, V> map);\n }\n\n public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {\n Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();\n\n while (it.hasNext()) {\n Map.Entry<K, V> entry = it.next();\n\n callback.handler(entry.getKey(), entry.getValue(), map);\n }\n }\n\n public static <K, V> void printMap(Map<K, V> map) {\n forEach(map, new ItemCallback<K, V>() {\n @Override\n public void handler(K key, V value, Map<K, V> map) {\n System.out.println(key + \" = \" + value);\n }\n });\n }\n}\n Map import java.util.*;\n\npublic class MapPrinter {\n public static void main(String[] args) {\n List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {\n private static final long serialVersionUID = 1L;\n {\n add(new LinkedHashMap<String, Integer>() {\n private static final long serialVersionUID = 1L;\n {\n put(\"One\", 0);\n put(\"Two\", 1);\n put(\"Three\", 3);\n }\n });\n\n add(new LinkedHashMap<String, Object>() {\n private static final long serialVersionUID = 1L;\n {\n put(\"Object\", new Object());\n put(\"Integer\", new Integer(0));\n put(\"Double\", new Double(0.0));\n }\n });\n }\n };\n\n for (Map<?, ?> map : maps) {\n MapUtils.printMap(map);\n System.out.println();\n }\n }\n}\n One = 0\nTwo = 1\nThree = 3\n\nObject = java.lang.Object@15db9742\nInteger = 0\nDouble = 0.0\n" }, { "answer_id": 30550239, "author": "Joshua Michael Calafell", "author_id": 2197975, "author_profile": "https://Stackoverflow.com/users/2197975", "pm_score": 2, "selected": false, "text": "/* For example, this could be a map object */\nMap<String, Integer> MAP = new Map<>();\n\n// Do something like put keys/value pairs into the map, etc...\nMAP.put(\"Denver\", 35);\nMAP.put(\"Patriots\", 14);\n\n/* Then, simply use a for each loop like this to iterate */\nfor (Object o : MAP.entrySet()) {\n Map.Entry pair = (Map.Entry) o;\n // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();\n}\n" }, { "answer_id": 32288690, "author": "tomaj", "author_id": 1758634, "author_profile": "https://Stackoverflow.com/users/1758634", "pm_score": 3, "selected": false, "text": "Map Map transform Maps import com.google.common.collect.Maps;\n Maps Maps.transformValues Maps.transformEntries public void transformMap(){\n Map<String, Integer> map = new HashMap<>();\n map.put(\"a\", 2);\n map.put(\"b\", 4);\n\n Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);\n result.forEach((key, val) -> print(key, Integer.toString(val)));\n // key=a,value=4\n // key=b,value=8\n\n Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + \"[\" + key + \"]\");\n result2.forEach(this::print);\n // key=a,value=2[a]\n // key=b,value=4[b]\n}\n\nprivate void print(String key, String val){\n System.out.println(\"key=\" + key + \",value=\" + val);\n}\n" }, { "answer_id": 32343110, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 5, "selected": false, "text": "forEach Map<String,String> sample = new HashMap<>();\nsample.put(\"A\",\"Apple\");\nsample.put(\"B\", \"Ball\");\n sample.keySet().forEach((k) -> System.out.println(k));\n sample.values().forEach((v) -> System.out.println(v));\n sample.forEach((k,v) -> System.out.println(k + \":\" + v)); \nsample.entrySet().stream().forEach((entry) -> {\n Object currentKey = entry.getKey();\n Object currentValue = entry.getValue();\n System.out.println(currentKey + \":\" + currentValue);\n });\n parallelStream() stream() forEachOrdered forEach forEach forEachOrdered forEach" }, { "answer_id": 32973406, "author": "Nitin Mahesh", "author_id": 1503859, "author_profile": "https://Stackoverflow.com/users/1503859", "pm_score": 5, "selected": false, "text": "HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();\n/*\n * Logic to put the Key,Value pair in your HashMap hm\n */\n\n// Print the key value pair in one line.\n\nhm.forEach((k, v) -> System.out.println(\"key: \" + k + \" value:\" + v));\n\n// Just copy and paste above line to your code.\n HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n Random rand = new Random(47);\n int i = 0;\n while(i < 5) {\n i++;\n int key = rand.nextInt(20);\n int value = rand.nextInt(50);\n System.out.println(\"Inserting key: \" + key + \" Value: \" + value);\n Integer imap = hm.put(key, value);\n if( imap == null) {\n System.out.println(\"Inserted\");\n } else {\n System.out.println(\"Replaced with \" + imap);\n } \n }\n\n hm.forEach((k, v) -> System.out.println(\"key: \" + k + \" value:\" + v));\n\nOutput:\n\nInserting key: 18 Value: 5\nInserted\nInserting key: 13 Value: 11\nInserted\nInserting key: 1 Value: 29\nInserted\nInserting key: 8 Value: 0\nInserted\nInserting key: 2 Value: 7\nInserted\nkey: 1 value:29\nkey: 18 value:5\nkey: 2 value:7\nkey: 8 value:0\nkey: 13 value:11\n Spliterator sit = hm.entrySet().spliterator();\n" }, { "answer_id": 33375492, "author": "Syd Lambert", "author_id": 5135746, "author_profile": "https://Stackoverflow.com/users/5135746", "pm_score": 2, "selected": false, "text": "LinkedHashMap Map LinkedHashMap<String,Integer> test=new LinkedHashMap();\n\ntest.put(\"foo\",69);\ntest.put(\"bar\",1337);\n\nfor(int i=0;i<test.size();i++){\n System.out.println(test.get(test.keySet().toArray()[i]));\n}\n 69\n1337\n" }, { "answer_id": 35558955, "author": "Slava Vedenin", "author_id": 4318868, "author_profile": "https://Stackoverflow.com/users/4318868", "pm_score": 11, "selected": false, "text": "long i = 0;\nIterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();\nwhile (it.hasNext()) {\n Map.Entry<Integer, Integer> pair = it.next();\n i += pair.getKey() + pair.getValue();\n}\n long i = 0;\nfor (Map.Entry<Integer, Integer> pair : map.entrySet()) {\n i += pair.getKey() + pair.getValue();\n}\n final long[] i = {0};\nmap.forEach((k, v) -> i[0] += k + v);\n long i = 0;\nfor (Integer key : map.keySet()) {\n i += key + map.get(key);\n}\n long i = 0;\nIterator<Integer> itr2 = map.keySet().iterator();\nwhile (itr2.hasNext()) {\n Integer key = itr2.next();\n i += key + map.get(key);\n}\n long i = 0;\nfor (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {\n Map.Entry<Integer, Integer> entry = entries.next();\n i += entry.getKey() + entry.getValue();\n}\n final long[] i = {0};\nmap.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());\n final long[] i = {0};\nmap.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());\n Apache Collections long i = 0;\nMapIterator<Integer, Integer> it = iterableMap.mapIterator();\nwhile (it.hasNext()) {\n i += it.next() + it.getValue();\n}\n final long[] i = {0};\nmutableMap.forEachKeyValue((key, value) -> {\n i[0] += key + value;\n});\n Benchmark Mode Cnt Score Error Units\ntest3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/op\ntest10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/op\ntest1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/op\ntest6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/op\ntest7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/op\ntest9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/op\ntest4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/op\ntest5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op\n Benchmark Mode Cnt Score Error Units\ntest10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/op\ntest3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/op\ntest6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/op\ntest1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/op\ntest7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/op\ntest4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/op\ntest5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op\ntest9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/op\n Benchmark Mode Cnt Score Error Units\ntest1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op\ntest10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op\ntest6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 µs/op\ntest5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 µs/op\ntest4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 µs/op\ntest3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/op\ntest7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/op\ntest9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/op\n 100 600 1100 1600 2100\ntest10 0.333 1.631 2.752 5.937 8.024\ntest3 0.309 1.971 4.147 8.147 10.473\ntest6 0.372 2.190 4.470 8.322 10.531\ntest1 0.405 2.237 4.616 8.645 10.707\ntest2 0.376 2.267 4.809 8.403 10.910\ntest7 0.473 2.448 5.668 9.790 12.125\ntest9 0.565 2.830 5.952 13.220 16.965\ntest4 0.808 5.012 8.813 13.939 17.407\ntest5 0.810 5.104 8.533 14.064 17.422\ntest8 5.173 12.499 17.351 24.671 30.403\n" }, { "answer_id": 36591840, "author": "Sajad NasiriNezhad", "author_id": 4533984, "author_profile": "https://Stackoverflow.com/users/4533984", "pm_score": 4, "selected": false, "text": " //Functional Oprations\n Map<String, String> mapString = new HashMap<>();\n mapString.entrySet().stream().map((entry) -> {\n String mapKey = entry.getKey();\n return entry;\n }).forEach((entry) -> {\n String mapValue = entry.getValue();\n });\n\n //Intrator\n Map<String, String> mapString = new HashMap<>();\n for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {\n Map.Entry<String, String> entry = it.next();\n String mapKey = entry.getKey();\n String mapValue = entry.getValue();\n }\n\n //Simple for loop\n Map<String, String> mapString = new HashMap<>();\n for (Map.Entry<String, String> entry : mapString.entrySet()) {\n String mapKey = entry.getKey();\n String mapValue = entry.getValue();\n\n }\n" }, { "answer_id": 40260450, "author": "Witold Kaczurba", "author_id": 6931119, "author_profile": "https://Stackoverflow.com/users/6931119", "pm_score": 5, "selected": false, "text": "map.forEach((k,v) -> { System.out.println(k + \":\" + v); });\n map.entrySet().forEach((e) -> {\n System.out.println(e.getKey() + \" : \" + e.getValue());\n });\n map.entrySet()\n .stream()\n .filter(e-> e.getValue() > 5)\n .forEach(System.out::println);\n public class HMIteration {\n\n\n public static void main(String[] args) {\n Map<Object, Object> linkedHashMap = new LinkedHashMap<>();\n Map<Object, Object> hashMap = new HashMap<>();\n\n for (int i=10; i>=0; i--) {\n linkedHashMap.put(i, i);\n hashMap.put(i, i);\n }\n\n System.out.println(\"LinkedHashMap (1): \");\n linkedHashMap.forEach((k,v) -> { System.out.print(k + \" (#=\"+k.hashCode() + \"):\" + v + \", \"); });\n\n System.out.println(\"\\nLinkedHashMap (2): \");\n\n linkedHashMap.entrySet().forEach((e) -> {\n System.out.print(e.getKey() + \" : \" + e.getValue() + \", \");\n });\n\n\n System.out.println(\"\\n\\nHashMap (1): \");\n hashMap.forEach((k,v) -> { System.out.print(k + \" (#:\"+k.hashCode() + \"):\" + v + \", \"); });\n\n System.out.println(\"\\nHashMap (2): \");\n\n hashMap.entrySet().forEach((e) -> {\n System.out.print(e.getKey() + \" : \" + e.getValue() + \", \");\n });\n }\n}\n LinkedHashMap (1):\n10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,\nLinkedHashMap (2):\n10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,\nHashMap (1):\n0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,\nHashMap (2):\n0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,\n" }, { "answer_id": 43247492, "author": "Rupendra Sharma", "author_id": 1706743, "author_profile": "https://Stackoverflow.com/users/1706743", "pm_score": 3, "selected": false, "text": "package com.test;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\npublic class Test {\n\n public static void main(String[] args) {\n Map<String, String> map = new HashMap<String, String>();\n map.put(\"ram\", \"ayodhya\");\n map.put(\"krishan\", \"mathura\");\n map.put(\"shiv\", \"kailash\");\n\n System.out.println(\"********* Keys *********\");\n Set<String> keys = map.keySet();\n for (String key : keys) {\n System.out.println(key);\n }\n\n System.out.println(\"********* Values *********\");\n Collection<String> values = map.values();\n for (String value : values) {\n System.out.println(value);\n }\n\n System.out.println(\"***** Keys and Values (Using for each loop) *****\");\n for (Map.Entry<String, String> entry : map.entrySet()) {\n System.out.println(\"Key: \" + entry.getKey() + \"\\t Value: \"\n + entry.getValue());\n }\n\n System.out.println(\"***** Keys and Values (Using while loop) *****\");\n Iterator<Entry<String, String>> entries = map.entrySet().iterator();\n while (entries.hasNext()) {\n Map.Entry<String, String> entry = (Map.Entry<String, String>) entries\n .next();\n System.out.println(\"Key: \" + entry.getKey() + \"\\t Value: \"\n + entry.getValue());\n }\n\n System.out\n .println(\"** Keys and Values (Using java 8 using lambdas )***\");\n map.forEach((k, v) -> System.out\n .println(\"Key: \" + k + \"\\t value: \" + v));\n }\n}\n" }, { "answer_id": 47122590, "author": "shivampip", "author_id": 6759926, "author_profile": "https://Stackoverflow.com/users/6759926", "pm_score": 4, "selected": false, "text": "for(Object key: map.keySet()){\n Object value= map.get(key);\n //Do your stuff\n}\n Map<String, int> data; for(Object key: data.keySet()){\n int value= data.get(key);\n}\n" }, { "answer_id": 47256829, "author": "Utpal Kumar", "author_id": 4745890, "author_profile": "https://Stackoverflow.com/users/4745890", "pm_score": 4, "selected": false, "text": "Map<String, Integer> m = new HashMap<String, Integer>();\n // ********** Using an iterator ****************\nIterator<Entry<String, Integer>> me = m.entrySet().iterator();\nwhile(me.hasNext()){\n Entry<String, Integer> pair = me.next();\n System.out.println(pair.getKey() + \":\" + pair.getValue());\n}\n\n// *********** Using foreach ************************\nfor(Entry<String, Integer> me : m.entrySet()){\n System.out.println(me.getKey() + \" : \" + me.getValue());\n}\n\n// *********** Using keySet *****************************\nfor(String s : m.keySet()){\n System.out.println(s + \" : \" + m.get(s));\n}\n\n// *********** Using keySet and iterator *****************\nIterator<String> me = m.keySet().iterator();\nwhile(me.hasNext()){\n String key = me.next();\n System.out.println(key + \" : \" + m.get(key));\n}\n" }, { "answer_id": 49885402, "author": "ABHAY JOHRI", "author_id": 7369238, "author_profile": "https://Stackoverflow.com/users/7369238", "pm_score": 4, "selected": false, "text": "map.entrySet().forEach(entry -> System.out.println(entry.getValue()));\n" }, { "answer_id": 49921231, "author": "bluehallu", "author_id": 512907, "author_profile": "https://Stackoverflow.com/users/512907", "pm_score": 5, "selected": false, "text": "map.entrySet().forEach(System.out::println);\n" }, { "answer_id": 50153908, "author": "Taras Melnyk", "author_id": 4813777, "author_profile": "https://Stackoverflow.com/users/4813777", "pm_score": 6, "selected": false, "text": "map.forEach((k, v) -> System.out.println((k + \":\" + v)));\n" }, { "answer_id": 53497541, "author": "anandchaugule", "author_id": 5756557, "author_profile": "https://Stackoverflow.com/users/5756557", "pm_score": 4, "selected": false, "text": "for for (String key : phnMap.keySet()) {\n System.out.println(\"Key: \" + key + \" Value: \" + phnMap.get(key));\n}\n forEach phnMap.forEach((k,v) -> System.out.println(\"Key: \" + k + \" Value: \" + v));\n phnMap.forEach((k,v)->{\n System.out.println(\"Key: \" + k + \" Value: \" + v);\n if(\"abc\".equals(k)){\n System.out.println(\"Hello abc\");\n }\n});\n" }, { "answer_id": 56467159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "int counter = 0;\nHashMap<String, String> m = new HashMap<String, String>();\nfor(int i = 0;i<items.length;i++)\n{\nm.put(\"firstname\"+i, items.get(i).getFirstName());\ncounter = i;\n}\n\nm.put(\"recordCount\",String.valueOf(counter));\n int recordCount = Integer.parseInf(m.get(\"recordCount\"));\nfor(int i =0 ;i<recordCount;i++)\n{\nSystem.out.println(\"First Name :\" + m.get(\"firstname\"+i));\n}\n" }, { "answer_id": 57321787, "author": "Lova Chittumuri", "author_id": 5256337, "author_profile": "https://Stackoverflow.com/users/5256337", "pm_score": 3, "selected": false, "text": "Map<String,String> sampleMap = new HashMap<>();\nfor (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {\n String key = entry.getKey();\n String value = entry.getValue();\n\n /* your Code as per the Business Justification */\n\n}\n Map<String,String> sampleMap = new HashMap<>();\n\nsampleMap.forEach((k, v) -> System.out.println(\"Key is : \" + k + \" Value is : \" + v));\n" }, { "answer_id": 58574145, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 5, "selected": false, "text": "Map Map Map Map Map TreeMap ConcurrentSkipListMap LinkedHashMap EnumMap NavigableMap NavigableMap TreeMap ConcurrentSkipListMap SortedMap NavigableMap Map TreeMap ConcurrentSkipListMap Comparable compareTo Comparator TreeMap ConcurrentSkipListMap Comparator LinkedHashMap DayOfWeek Month EnumMap DayOfWeek DayOfWeek.MONDAY DayOfWeek.SUNDAY Map Collections::synchronizedMap" }, { "answer_id": 59608364, "author": "Ali Akram", "author_id": 4332316, "author_profile": "https://Stackoverflow.com/users/4332316", "pm_score": 3, "selected": false, "text": "Map.forEach Map::forEach BiConsumer map.forEach((k,v)->{\n System.out.println(k+\"->\"+v);\n});\n" }, { "answer_id": 62378360, "author": "Younes El Ouarti", "author_id": 3705861, "author_profile": "https://Stackoverflow.com/users/3705861", "pm_score": 3, "selected": false, "text": "for (var entry : map.entrySet()) {\n System.out.println(entry.getKey() + \" : \" + entry.getValue());\n}\n" }, { "answer_id": 63910874, "author": "Dubstep", "author_id": 9363081, "author_profile": "https://Stackoverflow.com/users/9363081", "pm_score": 2, "selected": false, "text": "Map<String, String> map = \nfor (Map.Entry<String, String> entry : map.entrySet()) {\n MapKey = entry.getKey() \n MapValue = entry.getValue();\n}\n" }, { "answer_id": 65670377, "author": "Badri Paudel", "author_id": 9898251, "author_profile": "https://Stackoverflow.com/users/9898251", "pm_score": 2, "selected": false, "text": " Map<String, String> map = new HashMap();\n map.put(\"name\", \"Name\");\n map.put(\"age\", \"23\");\n map.put(\"address\", \"NP\");\n map.put(\"faculty\", \"BE\");\n map.put(\"major\", \"CS\");\n map.put(\"head\", \"MDK\");\n \n map.keySet(); for(String key : map.keySet()) {\n System.out.println(key);\n }\n map.values(); for(String value : map.values()) {\n System.out.println(value);\n }\n map.keySet(); //this prints the key value pair\n for (String k : map.keySet()) {\n System.out.println(k + \" \" + map.get(k) + \" \");\n }\n map.get(key)" }, { "answer_id": 69379440, "author": "anand krish", "author_id": 2147814, "author_profile": "https://Stackoverflow.com/users/2147814", "pm_score": 4, "selected": false, "text": "HashMap<Integer,String> map=new HashMap<Integer,String>();\n map.put(1,\"David\"); //Adding elements in Map\n map.put(2,\"John\");\n map.put(4,\"Samyuktha\");\n map.put(3,\"jasmin\");\n System.out.println(\"Iterating Hashmap...\");\n\n //way 1 (java 8 Method)\n map.forEach((key, value) -> {\n System.out.println(key+\" : \"+ value);\n });\n\n //way 2 (java 7 Method)\n for(Map.Entry me : map.entrySet()){\n System.out.println(me.getKey()+\" \"+me.getValue());\n }\n\n //way 3 (Legacy way to iterate HashMap)\n Iterator iterator = map.entrySet().iterator();//map.keySet().iterator()\n while (iterator.hasNext())\n {\n Map.Entry me =(Map.Entry)iterator.next();\n System.out.println(me.getKey()+\" : \"+ me.getValue());\n }\n \n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4807/" ]
46,909
<p>I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.</p> <p>Is this the proper way to use a mutex to prevent this from happening?</p> <pre><code>lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); } </code></pre>
[ { "answer_id": 46928, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 3, "selected": false, "text": "private Object _lock = new Object();\n\n// usage\nlock( _lock )\n{\n // thread-safe code here..\n}\n" }, { "answer_id": 46952, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 5, "selected": true, "text": "bool createdNew;\nusing (Mutex mtx = new Mutex(false, \"MyAwesomeMutex\", out createdNew))\n{\n try\n {\n mtx.WaitOne();\n\n MessageBox.Show(\"Click OK to release the mutex.\");\n }\n finally\n {\n mtx.ReleaseMutex();\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
46,915
<p>As a follow up to this question: <a href="https://stackoverflow.com/questions/46873/developing-a-online-exam-application-how-do-i-prevent-cheaters">Developing a online exam application, how do I prevent cheaters?</a></p> <p>Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?</p> <p>I read this: <a href="http://blog.flexmonkeypatches.com/2007/12/07/detecting-when-a-flex-application-loses-focus/" rel="nofollow noreferrer">Detecting when a Flex application loses focus</a> but was not very clear...</p>
[ { "answer_id": 47161, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 4, "selected": true, "text": "systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);\n" }, { "answer_id": 158463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<script language=\"JavaScript\" type=\"text/javascript\">\n<!--\n// -----------------------------------------------------------------------------\n// Globals\n// Major version of Flash required\nvar requiredMajorVersion = ${version_major};\n// Minor version of Flash required\nvar requiredMinorVersion = ${version_minor};\n// Minor version of Flash required\nvar requiredRevision = ${version_revision};\n// -----------------------------------------------------------------------------\n// -->\n\n\n function onAppFocusIn()\n {\n ${application}.onAppFocusIn();\n alert(\"onAppFocusIn\");\n }\n\n</script>\n<body scroll=\"no\" onFocus=\"onAppFocusIn()\">\n" }, { "answer_id": 6071245, "author": "Preeyanka", "author_id": 762650, "author_profile": "https://Stackoverflow.com/users/762650", "pm_score": 1, "selected": false, "text": "<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n layout=\"vertical\"\n verticalAlign=\"middle\"\n backgroundColor=\"white\"\n activate=\"activateHandler(event);\"\n deactivate=\"deactivateHandler(event);\">" }, { "answer_id": 20466605, "author": "Patrick", "author_id": 2495697, "author_profile": "https://Stackoverflow.com/users/2495697", "pm_score": 0, "selected": false, "text": "<object classid=\"clsid:D27WEE-A16D-21cf-90F2-422253540410\" width=\"100%\" height=\"100%\"\nid=\"MyApp\" name=\"MyApp\" align=\"middle\">\n<param name=\"movie\" value=\"MyApp.swf?v=1.00.008\" />\n<param name=\"wmode\" value=\"transparent\"> <----- take out this\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
46,918
<p>What is the proper way to minimize a WinForms app to the system tray? </p> <p>Note: minimize to <strong><em>system tray</em></strong>; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window.</p> <p>I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon."</p> <p>Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues.</p> <p>What's the proper way to do this?</p>
[ { "answer_id": 46927, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 3, "selected": false, "text": "this.WindowState = FormWindowState.Minimized \n" }, { "answer_id": 46970, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": " this.ShowIcon = false;//for the main form\n this.ShowInTaskbar = false;//for the main form\n this.notifyIcon1.Visible = true;//for notify icon\n this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject(\"notifyIcon1.Icon\")));//set an icon for notifyicon\n\n private void Form1_Shown(object sender, EventArgs e)\n {\n this.Hide();\n }\n" }, { "answer_id": 520291, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "this.Resize += new EventHandler(MainForm_Minimize);\n private void MainForm_Minimize(object sender, EventArgs e)\n {\n if(this.WindowState == FormWindowState.Minimized)\n Hide();\n }\n" }, { "answer_id": 533002, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " public form1()\n {\n Initialize Component();\n\n this.Resize += new EventHanlder(form1_Resize);\n } \n\n\n private void form1_Resize(object sender, EventArgs e)\n {\n if (this.WindowState == FormWindowState.Minimized && minimizeToTrayToolStripMenuItem.Checked == true)\n {\n NotificationIcon1.Visible = true;\n NotificationIcon1.BalloonTipText = \"Tool Tip Text\"\n NotificationIcon1.ShowBalloonTip(2); //show balloon tip for 2 seconds\n NotificationIcon1.Text = \"Balloon Text that shows when minimized to tray for 2 seconds\";\n this.WindowState = FormWindowState.Minimized;\n this.ShowInTaskbar = false;\n }\n }\n" }, { "answer_id": 3394963, "author": "James", "author_id": 409463, "author_profile": "https://Stackoverflow.com/users/409463", "pm_score": -1, "selected": false, "text": "this.Resize += new System.EventHandler(this.Form1_Resize);\n" }, { "answer_id": 3510214, "author": "Jeyavel", "author_id": 212809, "author_profile": "https://Stackoverflow.com/users/212809", "pm_score": 3, "selected": false, "text": "public partial class Form1 : Form\n{\n public static bool Close = false;\n Icon[] images;\n int offset = 0;\n\n public Form1()\n {\n InitializeComponent();\n\n notifyIcon1.BalloonTipText = \"My application still working...\";\n notifyIcon1.BalloonTipTitle = \"My Sample Application\";\n notifyIcon1.BalloonTipIcon = ToolTipIcon.Info; \n }\n\n private void Form1_Resize(object sender, EventArgs e)\n {\n if (FormWindowState.Minimized == WindowState)\n {\n this.Hide();\n notifyIcon1.ShowBalloonTip(500);\n //WindowState = FormWindowState.Minimized;\n }\n }\n\n private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)\n {\n this.Show();\n notifyIcon1.ShowBalloonTip(1000);\n WindowState = FormWindowState.Normal;\n }\n\n private void maximizeToolStripMenuItem_Click(object sender, EventArgs e)\n {\n this.Show();\n WindowState = FormWindowState.Normal;\n }\n\n private void closeToolStripMenuItem_Click(object sender, EventArgs e)\n {\n Close = true;\n this.Close(); \n }\n\n // Handle Closing of the Form.\n protected override void OnClosing(CancelEventArgs e)\n {\n if (Close)\n {\n e.Cancel = false;\n }\n else\n {\n WindowState = FormWindowState.Minimized;\n e.Cancel = true;\n }\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n // Load the basic set of eight icons.\n images = new Icon[5];\n images[0] = new Icon(\"C:\\\\icon1.ico\");\n images[1] = new Icon(\"C:\\\\icon2.ico\");\n images[2] = new Icon(\"C:\\\\icon3.ico\");\n images[3] = new Icon(\"C:\\\\icon4.ico\");\n images[4] = new Icon(\"C:\\\\icon5.ico\");\n }\n\n private void timer1_Tick(object sender, EventArgs e)\n {\n // Change the icon.\n // This event handler fires once every second (1000 ms).\n if (offset < 5)\n {\n notifyIcon1.Icon = images[offset];\n offset++;\n }\n else\n {\n offset = 0;\n }\n }\n}\n" }, { "answer_id": 63037966, "author": "Brian_The_Programmer", "author_id": 13975911, "author_profile": "https://Stackoverflow.com/users/13975911", "pm_score": 0, "selected": false, "text": "private void TransformWindow()\n {\n ContextMenu Menu = new ContextMenu();\n\n Menu.MenuItems.Add(RestoreMenu);\n Menu.MenuItems.Add(HideMenu);\n Menu.MenuItems.Add(new MenuItem(\"Exit\", new EventHandler(CleanExit)));\n\n notifyIcon = new NotifyIcon()\n {\n Icon = Properties.Resources.Microsft_Icon,\n Text = \"Folder Watcher\",\n Visible = true,\n ContextMenu = Menu\n };\n processHandle = Process.GetCurrentProcess().MainWindowHandle;\n ResizeWindow(false);\n\n }\n #region Getting Libraries\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetShellWindow();\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetDesktopWindow();\n public const Int32 SwMINIMIZE = 0;\n public const Int32 SwMaximize = 9;\n\n [DllImport(\"Kernel32.dll\", CallingConvention = CallingConvention.StdCall, SetLastError = true)]\n public static extern IntPtr GetConsoleWindow();\n\n [DllImport(\"User32.dll\", CallingConvention = CallingConvention.StdCall, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);\n public static void MinimizeConsoleWindow()\n {\n IntPtr hWndConsole = processHandle;\n ShowWindow(hWndConsole, SwMINIMIZE);\n\n }\n public static void MaximizeConsoleWindow()\n {\n IntPtr hWndConsole = processHandle;\n ShowWindow(hWndConsole, SwMaximize);\n\n }\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n public static void ResizeWindow(bool show)\n {\n RestoreMenu.Enabled = !show;\n HideMenu.Enabled = show;\n SetParent(processHandle, WinDesktop);\n\n if (show)\n MaximizeConsoleWindow();\n else\n MinimizeConsoleWindow();\n\n }\n public static void MinimizeClick(object sender, EventArgs e) => ResizeWindow(false);\n public static void MaximizeClick(object sender, EventArgs e) => ResizeWindow(true);\n public static IntPtr processHandle;\n public static IntPtr WinShell;\n public static IntPtr WinDesktop;\n public static NotifyIcon notifyIcon;\n public static MenuItem HideMenu = new MenuItem(\"Hide\", new EventHandler(MinimizeClick));\n public static MenuItem RestoreMenu = new MenuItem(\"Restore\", new EventHandler(MaximizeClick));\n public void CleanExit(object sender, EventArgs e)\n {\n notifyIcon.Visible = false;\n this.Close();\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
46,924
<p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p> <p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p> <p>I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>
[ { "answer_id": 47002, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 3, "selected": true, "text": "(defun buildtree (wordlist) ...code to build tree recursively returns the tree...)\n(define lookup (tree word) ...code to look up word using tree, returns t or nil...)\n\n(defun lookupmany (tree querylist)\n (if (eq querylist nil)\n nil\n (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist))\n )\n)\n\n(defun main (wordlist querylist) ; the main entry point\n (lookupmany (buildtree wordlist) querylist)\n)\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4177/" ]
46,933
<p>I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:</p> <pre><code>abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog : Animal { public override DogLeg Leg() {...} } class DogLeg : Leg { } </code></pre> <p>This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.</p> <p><strong>EDIT</strong>: I modified this somewhat, since I'm actually using properties instead of functions in my code. </p> <p><strong>EDIT</strong>: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function <strong>shouldn't</strong> work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.</p>
[ { "answer_id": 46935, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 2, "selected": false, "text": "public class ClientObj{\n public void doStuff(){\n Animal a=getAnimal();\n if(a is Dog){\n DogLeg dl = (DogLeg)a.GetLeg();\n }\n }\n}\n" }, { "answer_id": 46940, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 3, "selected": false, "text": "class Dog : Animal\n{\n public override DogLeg GetLeg() {...}\n}\n class Dog : Animal\n{\n public override Leg GetLeg() {...}\n}\n if(a instanceof Dog){\n DogLeg dl = (DogLeg)a.GetLeg();\n" }, { "answer_id": 46959, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 0, "selected": false, "text": "public class Dog{\n public Leg GetLeg(){\n DogLeg dl = new DogLeg(super.GetLeg());\n //set dogleg specific properties\n }\n}\n\n\n Animal a = getDog();\n Leg l = a.GetLeg();\n l.kick();\n" }, { "answer_id": 46964, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "abstract class Animal\n{\n public virtual Leg GetLeg ()\n}\n\nabstract class Leg { }\n\nclass Dog : Animal\n{\n public override Leg GetLeg () { return new DogLeg(); }\n}\n\nclass DogLeg : Leg { void Hump(); }\n Leg myleg = myDog.GetLeg();\n if (myleg is DogLeg) { ((DogLeg)myLeg).Hump()); }\n foreach (Animal a in animals)\n{\n a.GetLeg().SomeMethodThatIsOnAllLegs();\n}\n" }, { "answer_id": 46967, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "Animal dog = new Dog();\ndog.SetLeg(new CatLeg());\n" }, { "answer_id": 46968, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 0, "selected": false, "text": "public void AddLeg(Animal a)\n{\n a.Leg = new Leg();\n}\n AddLeg(new Dog());\n" }, { "answer_id": 47256, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "abstract class Leg { }\n\ninterface IAnimal { Leg GetLeg(); }\n\nabstract class Animal<TLeg> : IAnimal where TLeg : Leg\n { public abstract TLeg GetLeg();\n Leg IAnimal.GetLeg() { return this.GetLeg(); }\n }\n\nclass Dog : Animal<Dog.DogLeg>\n { public class DogLeg : Leg { }\n public override DogLeg GetLeg() { return new DogLeg();}\n } \n" }, { "answer_id": 68313, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "abstract class Animal<LegType> where LegType : Leg\n{\n public abstract LegType GetLeg();\n}\n\nabstract class Leg { }\n\nclass Dog : Animal<DogLeg>\n{\n public override DogLeg GetLeg()\n {\n return new DogLeg();\n }\n}\n\nclass DogLeg : Leg { }\n" }, { "answer_id": 73720, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 1, "selected": false, "text": "abstract class Leg { }\nclass DogLeg : Leg { }\n\ninterface IAnimal\n{\n Leg GetLeg();\n}\n\nclass Dog : IAnimal\n{\n public override DogLeg GetLeg() { /* */ }\n\n Leg IAnimal.GetLeg() { return GetLeg(); }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
46,981
<p>I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.</p> <p>The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher? </p> <p>PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent). </p> <p>PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.</p>
[ { "answer_id": 404706, "author": "Rob Fonseca-Ensor", "author_id": 21433, "author_profile": "https://Stackoverflow.com/users/21433", "pm_score": 0, "selected": false, "text": "public static Dispatcher RootVisualDispatcher { get; set; }\n\nprivate void Application_Startup(object sender, StartupEventArgs e)\n{\n this.RootVisual = new Page();\n RootVisualDispatcher = RootVisual.Dispatcher;\n}\n" }, { "answer_id": 1261531, "author": "Brandon ", "author_id": 151840, "author_profile": "https://Stackoverflow.com/users/151840", "pm_score": 0, "selected": false, "text": "Form m_MainWindow; //Reference to the main window of my application\nprotected virtual void OnPropertyChanged(string propertyName)\n{\n if(PropertyChanged != null)\n if(m_MainWindow.InvokeRequired)\n m_MainWindow.Invoke(\n PropertyChanged, this, new PropertyChangedEventArgs(propertyName);\n else\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName);\n}\n" }, { "answer_id": 1929825, "author": "Phil", "author_id": 138757, "author_profile": "https://Stackoverflow.com/users/138757", "pm_score": 3, "selected": false, "text": "System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});\n" }, { "answer_id": 16381177, "author": "Doitdotnet", "author_id": 2348909, "author_profile": "https://Stackoverflow.com/users/2348909", "pm_score": 0, "selected": false, "text": "Deployment.Current.Dispatcher.BeginInvoke( () =>\n\n{\n\nUpdateUI(); // DO the actions in the function Update UI\n\n});\n\npublic void UpdateUI()\n\n{\n\n//to do :Update UI elements here\n\n}\n" }, { "answer_id": 18246948, "author": "Jignesh.Raj", "author_id": 1928157, "author_profile": "https://Stackoverflow.com/users/1928157", "pm_score": 0, "selected": false, "text": "INotifyPropertyChanged INotifyPropertyChanged using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Runtime.CompilerServices;\nusing System.Windows.Forms;\n\n// Change the namespace to the project name. \nnamespace TestNotifyPropertyChangedCS\n{\n // This form demonstrates using a BindingSource to bind \n // a list to a DataGridView control. The list does not \n // raise change notifications. However the DemoCustomer type \n // in the list does. \n public partial class Form1 : Form\n {\n // This button causes the value of a list element to be changed. \n private Button changeItemBtn = new Button();\n\n // This DataGridView control displays the contents of the list. \n private DataGridView customersDataGridView = new DataGridView();\n\n // This BindingSource binds the list to the DataGridView control. \n private BindingSource customersBindingSource = new BindingSource();\n\n public Form1()\n {\n InitializeComponent();\n\n // Set up the \"Change Item\" button.\n this.changeItemBtn.Text = \"Change Item\";\n this.changeItemBtn.Dock = DockStyle.Bottom;\n this.changeItemBtn.Click +=\n new EventHandler(changeItemBtn_Click);\n this.Controls.Add(this.changeItemBtn);\n\n // Set up the DataGridView.\n customersDataGridView.Dock = DockStyle.Top;\n this.Controls.Add(customersDataGridView);\n\n this.Size = new Size(400, 200);\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n // Create and populate the list of DemoCustomer objects \n // which will supply data to the DataGridView.\n BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();\n customerList.Add(DemoCustomer.CreateNewCustomer());\n customerList.Add(DemoCustomer.CreateNewCustomer());\n customerList.Add(DemoCustomer.CreateNewCustomer());\n\n // Bind the list to the BindingSource. \n this.customersBindingSource.DataSource = customerList;\n\n // Attach the BindingSource to the DataGridView. \n this.customersDataGridView.DataSource =\n this.customersBindingSource;\n\n }\n\n // Change the value of the CompanyName property for the first \n // item in the list when the \"Change Item\" button is clicked.\n void changeItemBtn_Click(object sender, EventArgs e)\n {\n // Get a reference to the list from the BindingSource.\n BindingList<DemoCustomer> customerList =\n this.customersBindingSource.DataSource as BindingList<DemoCustomer>;\n\n // Change the value of the CompanyName property for the \n // first item in the list.\n customerList[0].CustomerName = \"Tailspin Toys\";\n customerList[0].PhoneNumber = \"(708)555-0150\";\n }\n\n }\n\n // This is a simple customer class that \n // implements the IPropertyChange interface. \n public class DemoCustomer : INotifyPropertyChanged\n {\n // These fields hold the values for the public properties. \n private Guid idValue = Guid.NewGuid();\n private string customerNameValue = String.Empty;\n private string phoneNumberValue = String.Empty;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n // This method is called by the Set accessor of each property. \n // The CallerMemberName attribute that is applied to the optional propertyName \n // parameter causes the property name of the caller to be substituted as an argument. \n private void NotifyPropertyChanged([CallerMemberName] String propertyName = \"\")\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n // The constructor is private to enforce the factory pattern. \n private DemoCustomer()\n {\n customerNameValue = \"Customer\";\n phoneNumberValue = \"(312)555-0100\";\n }\n\n // This is the public factory method. \n public static DemoCustomer CreateNewCustomer()\n {\n return new DemoCustomer();\n }\n\n // This property represents an ID, suitable \n // for use as a primary key in a database. \n public Guid ID\n {\n get\n {\n return this.idValue;\n }\n }\n\n public string CustomerName\n {\n get\n {\n return this.customerNameValue;\n }\n\n set\n {\n if (value != this.customerNameValue)\n {\n this.customerNameValue = value;\n NotifyPropertyChanged();\n }\n }\n }\n\n public string PhoneNumber\n {\n get\n {\n return this.phoneNumberValue;\n }\n\n set\n {\n if (value != this.phoneNumberValue)\n {\n this.phoneNumberValue = value;\n NotifyPropertyChanged();\n }\n }\n }\n }\n}\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/46981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
47,003
<p>I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. </p> <p>Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?</p>
[ { "answer_id": 40882625, "author": "JRA", "author_id": 6711884, "author_profile": "https://Stackoverflow.com/users/6711884", "pm_score": 1, "selected": false, "text": "public void Demo()\n {\n NpgsqlConnection connection = new NpgsqlConnection();\n connection = d_connection; // your connection string\n connection.Open(); \n NpgsqlCommand cmd = new NpgsqlCommand();\n try\n {\n cmd.Connection = connection;\n cmd.CommandText = \"select * from your table name\";\n cmd.CommandType = System.Data.CommandType.Text;\n using (var dataReader = cmd.ExecuteReader())\n {\n while (dataReader.Read())\n {\n\n string answer= dataReader.IsDBNull(0) ? \"\" : dataReader.GetString(0);\n\n }\n dataReader.Dispose();\n }\n }\n catch (Exception e)\n {\n }\n finally\n {\n cmd.Dispose();\n connection.Dispose();\n } \n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
47,005
<p>Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change.</p> <p>Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set.</p> <p>Thanks for any help</p>
[ { "answer_id": 47054, "author": "Harry", "author_id": 4704, "author_profile": "https://Stackoverflow.com/users/4704", "pm_score": 3, "selected": true, "text": "CHAR VARCHAR SET NAMES utf8" }, { "answer_id": 47059, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "CHAR VARCHAR" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4563/" ]
47,007
<p>A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.</p>
[ { "answer_id": 47012, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 5, "selected": false, "text": "p4 changes -m1 @<clientname>\n Change 12345 on 2008/08/21 by joebloggs@mainline-client '....top line of description...'\n" }, { "answer_id": 47019, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "p4 counter change sync" }, { "answer_id": 256455, "author": "Syeberman", "author_id": 14576, "author_profile": "https://Stackoverflow.com/users/14576", "pm_score": 8, "selected": true, "text": "p4 changes -s submitted -m1\n p4 changes -m1 @clientname\n p4 sync -n @changelist_number\n" }, { "answer_id": 668631, "author": "eel ghEEz", "author_id": 80772, "author_profile": "https://Stackoverflow.com/users/80772", "pm_score": 4, "selected": false, "text": "p4 changes -m1 \"./...#have\"\n $ p4 changes -m1 \"./...#have\"\nRequest too large (over 850000); see 'p4 help maxresults'.\n\n$ p4 -G files \"./...#have\" | python c:/cygwin/usr/local/bin/p4lastchange.py\nFiles: 266948\n2427657\n #! /usr/bin/env python\nimport sys, os, marshal\n\nif os.name == \"nt\":\n # Disable newline translation in Windows. Other operating systems do not\n # translate file contents.\n import msvcrt\n msvcrt.setmode( sys.stdin.fileno(), os.O_BINARY )\n\nlastcl = 0\nnum = 0\ntry:\n while 1:\n dict = marshal.load(sys.stdin)\n num = num + 1\n for key in dict.keys():\n # print \"%s: %s\" % (key,dict[key])\n if key == \"change\":\n cl = int(dict[key])\n if cl > lastcl:\n lastcl = cl\nexcept EOFError:\n pass\nprint \"Files: %s\" % num\nprint lastcl\n" }, { "answer_id": 10182886, "author": "gmaghera", "author_id": 209849, "author_profile": "https://Stackoverflow.com/users/209849", "pm_score": 3, "selected": false, "text": "cstat -- Dump change/sync status for current client\n\np4 cstat [files...]\n\nLists changes that are needed, had or partially synced in the current\nclient. The output is returned in tagged format, similar to the fstat\ncommand.\n\nThe fields that cstat displays are:\n\n change changelist number\n status 'have', 'need' or 'partial'\n" }, { "answer_id": 10937773, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "p4 counter change\n" }, { "answer_id": 33069657, "author": "gsf", "author_id": 1870790, "author_profile": "https://Stackoverflow.com/users/1870790", "pm_score": 4, "selected": false, "text": "p4 changes -m1 @clientname p4 cstat ...#have | grep change | awk '$3 > x { x = $3 };END { print x }'\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2102/" ]
47,009
<p>I originally asked <a href="https://stackoverflow.com/questions/46933/why-doesnt-inheritance-work-the-way-i-think-it-should-work">this question</a>, but in finding an answer, discovered that my original problem was a lack of support in C# for covariance on inherited methods' return types. After discovering that, I became curious as to what languages <em>do</em> support this feature.</p> <p>I will accept the answer of whoever can name the most.</p> <p><strong>EDIT</strong>: John Millikin correctly pointed out that lots of dynamic languages support this. To clarify: </p> <p><strong>I am only looking for static/strongly typed languages.</strong></p>
[ { "answer_id": 47053, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "get() set() Leg get_leg() set_leg(DogLeg) get_leg() set_leg()" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
47,022
<p>I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location.</p> <p>As far as <code>svn status</code> is concerned, the directory is unknown (the name of the directory is <code>type</code>).</p> <pre> $ svn status ? type </pre> <p>When I try to add the directory, the server says it already exists.</p> <pre> $ svn add type svn: warning: 'type' is already under version control </pre> <p>If I try to update the directory, it's gone again.</p> <pre> $ svn update type svn: '.' is not under version control </pre> <p>If I try to commit it, the server complains that it's old parent directory no longer exists.</p> <pre> $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found </pre> <p>To add to the mystery, the contents of the directory are marked as modified.</p> <pre> $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java </pre> <p>If I try to update from within the directory, I get this.</p> <pre> $ cd type $ svn update svn: Two top-level reports with no target </pre> <p>Committing from within the directory gives the same <code>path not found</code> error as above.</p> <p>What's going on and how do I fix it?</p> <p>EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse.</p> <p>UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages <em>mean</em> precisely and (b) how to actually <em>fix</em> the problem.</p>
[ { "answer_id": 47098, "author": "Rob Oxspring", "author_id": 1867, "author_profile": "https://Stackoverflow.com/users/1867", "pm_score": 5, "selected": true, "text": "type IntegerType.java IntegerType.java .svn" }, { "answer_id": 1891622, "author": "déo", "author_id": 102550, "author_profile": "https://Stackoverflow.com/users/102550", "pm_score": 0, "selected": false, "text": "$ svn switch path/to/foo\n" }, { "answer_id": 6645011, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 1, "selected": false, "text": ".svn" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
47,045
<p>Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? </p>
[ { "answer_id": 47049, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 10, "selected": true, "text": "// Store the formatted string in 'result'\nString result = String.format(\"%4d\", i * j);\n\n// Write the result to standard output\nSystem.out.println( result );\n" }, { "answer_id": 198356, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "String formatted = \"%s: %s\".format(key, value);\n format() Replace() \"I Like Wine\".Replace(\"Wine\",\"Beer\");\n Replace() inputText.Replace(\" \", \"%20\");\n inputText = inputText.Replace(\" \",\"%20\");\n Replace() format() String inputText = String.Replace(inputText, \" \", \"%20\");\n int length = \"123\".Length();\n" }, { "answer_id": 31405706, "author": "догонят", "author_id": 3199507, "author_profile": "https://Stackoverflow.com/users/3199507", "pm_score": 2, "selected": false, "text": "format() sprintf() final static String HexChars = \"0123456789abcdef\";\n\npublic static String getHexQuad(long v) {\n String ret;\n if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = \"\";\n ret += String.format(\"%c%c%c%c\",\n HexChars.charAt((int) ((v >> 12) & 0x0f)),\n HexChars.charAt((int) ((v >> 8) & 0x0f)),\n HexChars.charAt((int) ((v >> 4) & 0x0f)),\n HexChars.charAt((int) ( v & 0x0f)));\n return ret;\n}\n replace(char oldchar , char newchar) ...\n ret += \"ABCD\".\n replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).\n replace('B', HexChars.charAt((int) ((v >> 8) & 0x0f))).\n replace('C', HexChars.charAt((int) ((v >> 4) & 0x0f))).\n replace('D', HexChars.charAt((int) ( v & 0x0f)));\n ...\n ret ...\nret += HexChars.charAt((int) ((v >> 12) & 0x0f)));\nret += HexChars.charAt((int) ((v >> 8) & 0x0f)));\n...\n" }, { "answer_id": 57359951, "author": "armagedescu", "author_id": 4582948, "author_profile": "https://Stackoverflow.com/users/4582948", "pm_score": 1, "selected": false, "text": "PrintStream ps = new PrintStream(baos);\nps.printf(\"there is a %s from %d %s\", \"hello\", 3, \"friends\");\nSystem.out.println(baos.toString());\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n PrintStream ps = new PrintStream(baos);\nps.printf(\"there is a %s from %d %s \", \"hello\", 3, \"friends\");\nps.printf(\"there are %d % from a %\", 2, \"kisses\", \"girl\");\nSystem.out.println(baos.toString());\n ps.printf(\"there is a %s from %d %s\", \"flip\", 5, \"haters\");\nbaos.reset(); //need reset to write new string\nps.printf(\"there are %d % from a %\", 2, \"kisses\", \"girl\");\nSystem.out.println(baos.toString());\n" }, { "answer_id": 62706682, "author": "andreoss", "author_id": 12462444, "author_profile": "https://Stackoverflow.com/users/12462444", "pm_score": 3, "selected": false, "text": "formatted String.format() Assertions.assertEquals(\n \"%s %d %.3f\".formatted(\"foo\", 123, 7.89),\n \"foo 123 7.890\"\n);\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4498/" ]
47,052
<p>I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e. </p> <pre><code>LIKE '%this%' LIKE 'Sm_th' LIKE '[C-P]arsen' </code></pre> <p>What's the best approach to doing this?</p> <p>P.S. I'm looking to do this on the .Net Framework (C#).</p>
[ { "answer_id": 47088, "author": "Martin", "author_id": 2581, "author_profile": "https://Stackoverflow.com/users/2581", "pm_score": 2, "selected": false, "text": "/^(.*this.*|Sm.th|[C-P]arsen)$/\n % becomes .*\n_ becomes .\n" }, { "answer_id": 13180223, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 4, "selected": true, "text": "MatchEvaluator string regexPattern = \"^\" + Regex.Replace(\n likePattern,\n @\"[%_]|\\[[^]]*\\]|[^%_[]+\",\n match =>\n {\n if (match.Value == \"%\")\n {\n return \".*\";\n }\n if (match.Value == \"_\")\n {\n return \".\";\n }\n if (match.Value.StartsWith(\"[\") && match.Value.EndsWith(\"]\"))\n {\n return match.Value;\n }\n return Regex.Escape(match.Value);\n }) + \"$\";\n" }, { "answer_id": 29847510, "author": "TheEadie", "author_id": 1930030, "author_profile": "https://Stackoverflow.com/users/1930030", "pm_score": 2, "selected": false, "text": "LIKE '!%' ESCAPE '!' public Regex ConvertSqlLikeToDotNetRegex(string regex, char? likeEscape = null)\n {\n var pattern = string.Format(@\"\n {0}[%_]|\n [%_]|\n \\[[^]]*\\]|\n [^%_[{0}]+\n \", likeEscape);\n\n var regexPattern = Regex.Replace(\n regex,\n pattern,\n ConvertWildcardsAndEscapedCharacters,\n RegexOptions.IgnorePatternWhitespace);\n\n regexPattern = \"^\" + regexPattern + \"$\";\n\n return new Regex(regexPattern,\n !m_CaseSensitive ? RegexOptions.IgnoreCase : RegexOptions.None);\n }\n\n private string ConvertWildcardsAndEscapedCharacters(Match match)\n {\n // Wildcards\n switch (match.Value)\n {\n case \"%\":\n return \".*\";\n case \"_\":\n return \".\";\n }\n\n // Remove SQL defined escape characters from C# regex\n if (StartsWithEscapeCharacter(match.Value, likeEscape))\n {\n return match.Value.Remove(0, 1);\n }\n\n // Pass anything contained in []s straight through \n // (These have the same behaviour in SQL LIKE Regex and C# Regex)\n if (StartsAndEndsWithSquareBrackets(match.Value))\n {\n return match.Value;\n }\n\n return Regex.Escape(match.Value);\n }\n\n private static bool StartsAndEndsWithSquareBrackets(string text)\n {\n return text.StartsWith(\"[\", StringComparison.Ordinal) &&\n text.EndsWith(\"]\", StringComparison.Ordinal);\n }\n\n private bool StartsWithEscapeCharacter(string text, char? likeEscape)\n {\n return (likeEscape != null) &&\n text.StartsWith(likeEscape.ToString(), StringComparison.Ordinal);\n }\n" } ]
2008/09/05
[ "https://Stackoverflow.com/questions/47052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4843/" ]