qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
327,366 | <p>I have two tables with the same columns, and I need to copy one table's rows to the other table's rows to create one big table with all the values from both tables. Right now I am doing this query to return the same thing:</p>
<pre><code>SELECT col1, col2, col3 from Table1
union
SELECT col1, col2, col3 from Table2
</code></pre>
<p>However, it seems horribly inefficient, and on my system is very slow (returns 1210189 records).</p>
| [
{
"answer_id": 327369,
"author": "Tommy",
"author_id": 1270,
"author_profile": "https://Stackoverflow.com/users/1270",
"pm_score": 5,
"selected": true,
"text": "SELECT col1, col2, col3 \nINTO Table1\nFROM Table2 \n"
},
{
"answer_id": 327374,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 4,
"selected": false,
"text": "select col1, col2, col3 from Table1\nunion all\nselect col1, col2, col3 from Table2\n"
},
{
"answer_id": 327393,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 2,
"selected": false,
"text": "SELECT col1, col2, col3 from Table1\nunion all\nSELECT col1, col2, col3 from Table2\n"
},
{
"answer_id": 327425,
"author": "Hosam Aly",
"author_id": 41283,
"author_profile": "https://Stackoverflow.com/users/41283",
"pm_score": 2,
"selected": false,
"text": "Insert into table2 select * from table1;\n Insert into table2(col1, col2, col3) select col1, col2, col3 from table1;\n"
},
{
"answer_id": 10010335,
"author": "user1157685",
"author_id": 1157685,
"author_profile": "https://Stackoverflow.com/users/1157685",
"pm_score": 0,
"selected": false,
"text": "select * into new table(your new table name) \nfrom table1.col1,table1.col2,table2.col1;\n"
},
{
"answer_id": 51451005,
"author": "Carl",
"author_id": 10113080,
"author_profile": "https://Stackoverflow.com/users/10113080",
"pm_score": 0,
"selected": false,
"text": "select * into newtable from table1\nunion all\nselect * from table2\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2504/"
] |
327,372 | <p>How is a breakpoint implemented on PPC (On OS X, to be specific)?</p>
<p>For example, on x86 it's typically done with the INT 3 instruction (0xCC) -- is there an instruction comparable to this for ppc? Or is there some other way they're set/implemented?</p>
| [
{
"answer_id": 327540,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 2,
"selected": false,
"text": "IABR IABR2 DABR DABR2"
},
{
"answer_id": 10286705,
"author": "tc.",
"author_id": 349112,
"author_profile": "https://Stackoverflow.com/users/349112",
"pm_score": 3,
"selected": false,
"text": "0b01111111111000000000000000001000\n 011111 31\n 11111 condition flags: lt, gt, ge, logical lt, logical gt\n 00000 rA\n 00000 rB\n 0000000100 constant 4\n 0 reserved\n trap tw twi"
},
{
"answer_id": 44245592,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 0,
"selected": false,
"text": "TRAP IABR"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41764/"
] |
327,379 | <p>For one of the projects I'm doing right now, I need to look at the performance (amongst other things) of different <a href="http://en.wikipedia.org/wiki/Concurrent_computing" rel="nofollow noreferrer">concurrent enabled</a> programming languages.</p>
<p>At the moment I'm looking into comparing <a href="http://www.stackless.com/" rel="nofollow noreferrer">stackless python</a> and <a href="https://computing.llnl.gov/tutorials/pthreads/" rel="nofollow noreferrer">C++ PThreads</a>, so the focus is on these two languages, but other languages will probably be tested later. Ofcourse the comparison must be as representative and accurate as possible, so my first thought was to start looking for some standard <strong><em>concurrent/multi-threaded benchmark problems</em></strong>, alas I couldn't find any decent or standard, tests/problems/benchmarks.</p>
<p>So my question is as follows: <em>Do you have a suggestion for a good, easy or quick problem to test the performance of the programming language</em> (and to expose it's strong and weak points in the process)?</p>
| [
{
"answer_id": 327860,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 0,
"selected": false,
"text": "#include <cstdlib> //for atoi\n#include <iostream>\n#include <iomanip> //for setw and setfill\n#include <vector>\n\n\nint DoThread(const double x, const double y, int maxiter) {\n double curX,curY,xSquare,ySquare;\n int i;\n\n curX = x + x*x - y*y;\n curY = y + x*y + x*y;\n ySquare = curY*curY;\n xSquare = curX*curX;\n\n for (i=0; i<maxiter && ySquare + xSquare < 4;i++) {\n ySquare = curY*curY;\n xSquare = curX*curX;\n curY = y + curX*curY + curX*curY;\n curX = x - ySquare + xSquare;\n }\n return i;\n}\n\nvoid SingleThreaded(int horizPixels, int vertPixels, int maxiter, std::vector<std::vector<int> >& result) {\n for(int x = horizPixels; x > 0; x--) {\n for(int y = vertPixels; y > 0; y--) {\n //3.0 -> so we always have -1.5 -> 1.5 as the window; (x - (horizPixels / 2) will go from -horizPixels/2 to +horizPixels/2\n result[x-1][y-1] = DoThread((3.0 / horizPixels) * (x - (horizPixels / 2)),(3.0 / vertPixels) * (y - (vertPixels / 2)),maxiter);\n }\n }\n}\n\nint main(int argc, char* argv[]) {\n //first arg = length along horizontal axis\n int horizPixels = atoi(argv[1]);\n\n //second arg = length along vertical axis\n int vertPixels = atoi(argv[2]);\n\n //third arg = iterations\n int maxiter = atoi(argv[3]);\n\n //fourth arg = threads\n int threadCount = atoi(argv[4]);\n\n std::vector<std::vector<int> > result(horizPixels, std::vector<int>(vertPixels,0)); //create and init 2-dimensional vector\n SingleThreaded(horizPixels, vertPixels, maxiter, result);\n\n //TODO: remove these lines\n for(int y = 0; y < vertPixels; y++) {\n for(int x = 0; x < horizPixels; x++) {\n std::cout << std::setw(2) << std::setfill('0') << std::hex << result[x][y] << \" \";\n }\n std::cout << std::endl;\n }\n}\n"
},
{
"answer_id": 333412,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 0,
"selected": false,
"text": "#include <cstdlib> //for atoi\n#include <iostream>\n#include <iomanip> //for setw and setfill\n#include <vector>\n\n#include \"bitmap_Image.h\" //for saving the mandelbrot as a bmp\n\n#include <pthread.h>\n\npthread_mutex_t mutexCounter;\nint sharedCounter(0);\nint percent(0);\n\nint horizPixels(0);\nint vertPixels(0);\nint maxiter(0);\n\n//doesn't need to be locked\nstd::vector<std::vector<int> > result; //create 2 dimensional vector\n\nvoid *DoThread(void *null) {\n double curX,curY,xSquare,ySquare,x,y;\n int i, intx, inty, counter;\n counter = 0;\n\n do {\n counter++;\n pthread_mutex_lock (&mutexCounter); //lock\n intx = int((sharedCounter / vertPixels) + 0.5);\n inty = sharedCounter % vertPixels;\n sharedCounter++;\n pthread_mutex_unlock (&mutexCounter); //unlock\n\n //exit thread when finished\n if (intx >= horizPixels) {\n std::cout << \"exited thread - I did \" << counter << \" calculations\" << std::endl;\n pthread_exit((void*) 0);\n }\n\n //set x and y to the correct value now -> in the range like singlethread\n x = (3.0 / horizPixels) * (intx - (horizPixels / 1.5));\n y = (3.0 / vertPixels) * (inty - (vertPixels / 2));\n\n curX = x + x*x - y*y;\n curY = y + x*y + x*y;\n ySquare = curY*curY;\n xSquare = curX*curX;\n\n for (i=0; i<maxiter && ySquare + xSquare < 4;i++){\n ySquare = curY*curY;\n xSquare = curX*curX;\n curY = y + curX*curY + curX*curY;\n curX = x - ySquare + xSquare;\n }\n result[intx][inty] = i;\n } while (true);\n}\n\nint DoSingleThread(const double x, const double y) {\n double curX,curY,xSquare,ySquare;\n int i;\n\n curX = x + x*x - y*y;\n curY = y + x*y + x*y;\n ySquare = curY*curY;\n xSquare = curX*curX;\n\n for (i=0; i<maxiter && ySquare + xSquare < 4;i++){\n ySquare = curY*curY;\n xSquare = curX*curX;\n curY = y + curX*curY + curX*curY;\n curX = x - ySquare + xSquare;\n }\n return i;\n\n}\n\nvoid SingleThreaded(std::vector<std::vector<int> >& result) {\n for(int x = horizPixels - 1; x != -1; x--) {\n for(int y = vertPixels - 1; y != -1; y--) {\n //3.0 -> so we always have -1.5 -> 1.5 as the window; (x - (horizPixels / 2) will go from -horizPixels/2 to +horizPixels/2\n result[x][y] = DoSingleThread((3.0 / horizPixels) * (x - (horizPixels / 1.5)),(3.0 / vertPixels) * (y - (vertPixels / 2)));\n }\n }\n}\n\nvoid MultiThreaded(int threadCount, std::vector<std::vector<int> >& result) {\n /* Initialize and set thread detached attribute */\n pthread_t thread[threadCount];\n pthread_attr_t attr;\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n\n for (int i = 0; i < threadCount - 1; i++) {\n pthread_create(&thread[i], &attr, DoThread, NULL);\n }\n std::cout << \"all threads created\" << std::endl;\n\n for(int i = 0; i < threadCount - 1; i++) {\n pthread_join(thread[i], NULL);\n }\n std::cout << \"all threads joined\" << std::endl;\n}\n\nint main(int argc, char* argv[]) {\n //first arg = length along horizontal axis\n horizPixels = atoi(argv[1]);\n\n //second arg = length along vertical axis\n vertPixels = atoi(argv[2]);\n\n //third arg = iterations\n maxiter = atoi(argv[3]);\n\n //fourth arg = threads\n int threadCount = atoi(argv[4]);\n\n result = std::vector<std::vector<int> >(horizPixels, std::vector<int>(vertPixels,21)); // init 2-dimensional vector\n if (threadCount <= 1) {\n SingleThreaded(result);\n } else {\n MultiThreaded(threadCount, result);\n }\n\n\n //TODO: remove these lines\n bitmapImage image(horizPixels, vertPixels);\n for(int y = 0; y < vertPixels; y++) {\n for(int x = 0; x < horizPixels; x++) {\n image.setPixelRGB(x,y,16777216*result[x][y]/maxiter % 256, 65536*result[x][y]/maxiter % 256, 256*result[x][y]/maxiter % 256);\n //std::cout << std::setw(2) << std::setfill('0') << std::hex << result[x][y] << \" \";\n }\n std::cout << std::endl;\n }\n\n image.saveToBitmapFile(\"~/Desktop/test.bmp\",32);\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
] |
327,382 | <p>We have a large ASP.Net website that has a single css stylesheet which is getting out of control.</p>
<p>I am thinking of using the following strategy (taken from <a href="http://www.techrepublic.com/article/developing-a-css-strategy/5437796/" rel="nofollow noreferrer">http://www.techrepublic.com/article/developing-a-css-strategy/5437796/</a>) which seems logical to me...</p>
<p><em>you might have one CSS file devoted to sitewide styles and separate CSS files for identifiable subsets of site pages (such as pages for a specific department or pages with a different layout style). For styles that are unique to a specific page, use a separate CSS file for each page (if there are too many styles to fit comfortably in the document header). You link or import the appropriate CSS files for each page, so that you load all the styles needed to display that page, but very few unnecessary styles that only appear on other pages.</em></p>
<p>Is this a good way to proceed? What are the alternatives?</p>
| [
{
"answer_id": 327498,
"author": "Chris Hawes",
"author_id": 22776,
"author_profile": "https://Stackoverflow.com/users/22776",
"pm_score": 1,
"selected": false,
"text": "layout.css\ncontent.css\nmenu.css\ntypography.css\n font-weight, text-decoration, font-family\n h1, h2, h3, h4, h5, h6, a, p, li\n #logo h1 {text-indent: -9999px}\n #logo h1 a {display: block; width: 200px; height: 98px; backround...}\n"
},
{
"answer_id": 330147,
"author": "Cody Caughlan",
"author_id": 25398,
"author_profile": "https://Stackoverflow.com/users/25398",
"pm_score": 0,
"selected": false,
"text": "<body id=\"users_list_body\">\n #users_list_body table \n #users_list_body table thead \n //javascript\n if(V.views.users_list) { V.views.user_list(); }\n V = {};\nV.views = {};\nV.views.user_list = function() {\n //any code you want to run for the Users controller / List action..\n //jQuery or something\n $('#save_button').click({ ... });\n}\n"
},
{
"answer_id": 671481,
"author": "hlfcoding",
"author_id": 65465,
"author_profile": "https://Stackoverflow.com/users/65465",
"pm_score": 2,
"selected": false,
"text": "/** Start Module 1 */\n[css]\n/* End Module 1 **/\n Start Module 1 /** these types of comments **/ .container {}\n .container .inner {}\n .container .head {}\n .container .inner.alt {}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] |
327,401 | <p>What is the difference between <code>find-grep</code> and <code>grep-find</code> in Emacs?</p>
| [
{
"answer_id": 331902,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 4,
"selected": true,
"text": "M-x describe-function C-h f find-grep find-grep is an alias for `grep-find' in `progmodes/grep.el'.\n(find-grep COMMAND-ARGS)\n...\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
327,404 | <p>I'm attempting to write a couple of NAnt tasks for interacting with Microsoft Virtual Server 2005 R2 SP1, and I've lifted the code found on "Virtual PC Guy's WebLog", in the <a href="http://blogs.msdn.com/virtual_pc_guy/archive/2006/06/13/630165.aspx" rel="nofollow noreferrer">"Controlling Virtual Server through PowerShell"</a> post.</p>
<p>It doesn't work: I always get a failure when calling CreateVirtualMachine:</p>
<p><code>System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)</code></p>
<p><code>at Microsoft.VirtualServer.Interop.VMVirtualServerClass.CreateVirtualMachine(String configurationName, String configurationPath)</code></p>
<p>My code is as follows:</p>
<pre><code>var virtualServer = new VMVirtualServerClass();
SetSecurity(virtualServer);
var virtualMachine = virtualServer.CreateVirtualMachine("TEST",
@"D:\Virtual Server\TEST.vmc");
</code></pre>
<p>...where SetSecurity is defined as follows:</p>
<pre><code> private static void SetSecurity(object dcomObject)
{
IntPtr pProxy = Marshal.GetIUnknownForObject(dcomObject);
int hr = CoSetProxyBlanket(pProxy,
RPC_C_AUTHN_DEFAULT,
RPC_C_AUTHZ_DEFAULT,
IntPtr.Zero,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
IntPtr.Zero,
EOAC_DYNAMIC_CLOAKING);
Marshal.ThrowExceptionForHR(hr);
}
private const uint RPC_C_AUTHN_NONE = 0;
private const uint RPC_C_AUTHN_WINNT = 10;
private const uint RPC_C_AUTHN_DEFAULT = 0xFFFFFFFF;
private const uint RPC_C_AUTHZ_NONE = 0;
private const uint RPC_C_AUTHZ_DEFAULT = 0xFFFFFFFF;
private const uint RPC_C_AUTHN_LEVEL_DEFAULT = 0;
private const uint RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6;
private const uint RPC_C_IMP_LEVEL_IDENTIFY = 2;
private const uint RPC_C_IMP_LEVEL_IMPERSONATE = 3;
private const uint EOAC_NONE = 0;
private const uint EOAC_DYNAMIC_CLOAKING = 0x40;
private const uint EOAC_DEFAULT = 0x0800;
[DllImport("Ole32.dll")]
public static extern int CoSetProxyBlanket(IntPtr pProxy,
UInt32 dwAuthnSvc,
UInt32 dwAuthzSvc,
IntPtr pServerPrincName,
UInt32 dwAuthnLevel,
UInt32 dwImpLevel,
IntPtr pAuthInfo,
UInt32 dwCapabilities);
</code></pre>
<p>If I write a standalone program and add a call to <code>CoInitializeSecurity</code>, then it works. However, I don't want a standalone program -- I want a set of NAnt tasks (so a DLL), and I don't want to call <code>CoInitializeSecurity</code>, because there's no way of guaranteeing that some other NAnt task won't have called it already.</p>
<p>Has anyone got this working?</p>
| [
{
"answer_id": 331902,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 4,
"selected": true,
"text": "M-x describe-function C-h f find-grep find-grep is an alias for `grep-find' in `progmodes/grep.el'.\n(find-grep COMMAND-ARGS)\n...\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
327,408 | <p>I'm trying to run dot net console application via Java:</p>
<pre><code>process = Runtime.getRuntime().exec(commandLine);
</code></pre>
<p>I get the following output:</p>
<pre><code>Detecting
The handle is invalid.
</code></pre>
<p>when running it directly via the console (windows) there is no problem:</p>
<pre><code>Detecting
100%
Done.
100%
</code></pre>
<p>I'm running more applications in this form but have no problem .</p>
<p>Got this stack trace:</p>
<pre><code>Detecting at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.get_CursorTop()
at AutomaticImageOrientation.HelperClasses.General.WriteProgressToConsole(Int32 lastIndex, Int32 totalImages)
at AutomaticImageOrientation.MainManager.DetectImage(String[] files, String outputPath, String& globalErrorMessage, Dictionary`2& foundRotations)
</code></pre>
<p>The problem is when the .net app trying to write to the console What is the solution?</p>
<p>found the line that cause the problem:</p>
<pre><code>Console.CursorLeft = 0;
</code></pre>
<p>Do you know why?</p>
| [
{
"answer_id": 472257,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 0,
"selected": false,
"text": "Runtime r = Runtime.getRuntime();\nmStartProcess = r.exec(applicationName, null, fileToExecute);\n\nStreamLogger outputGobbler = new StreamLogger(mStartProcess.getInputStream());\noutputGobbler.start();\n\nint returnCode = mStartProcess.waitFor();\n\n\nclass StreamLogger extends Thread{\n\n private InputStream mInputStream;\n\n public StreamLogger(InputStream is) {\n this.mInputStream = is;\n }\n\n public void run() {\n try {\n InputStreamReader isr = new InputStreamReader(mInputStream);\n BufferedReader br = new BufferedReader(isr);\n String line = null;\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n }\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n\n}\n"
},
{
"answer_id": 18366631,
"author": "Korey",
"author_id": 138272,
"author_profile": "https://Stackoverflow.com/users/138272",
"pm_score": 1,
"selected": false,
"text": "//This causes the output to update on the same line, rather than \"spamming\" the output down the screen.\n//This is not compatible with redirected output, so try/catch is needed.\ntry\n{\n int lineLength = Console.WindowWidth - 1;\n if (message.Length > lineLength)\n {\n message = message.Substring(0, lineLength);\n }\n\n Console.CursorLeft = 0;\n Console.Write(message);\n}\ncatch \n{\n Console.WriteLine(message);\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,411 | <p>I've tried <a href="http://www.vim.org/scripts/script.php?script_id=159" rel="noreferrer">MiniBufExplorer</a>, but I usually end up with several windows showing it or close it altogether. What I'd like is something like <a href="http://www.vim.org/scripts/script.php?script_id=2050" rel="noreferrer">LustyJuggler</a> with incremental search, the way I switch between buffers in Emacs. Surely there is a script like this?</p>
| [
{
"answer_id": 327457,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 5,
"selected": false,
"text": ":ls :bn :bp :b <part-of-name>"
},
{
"answer_id": 327463,
"author": "Terminus",
"author_id": 7053,
"author_profile": "https://Stackoverflow.com/users/7053",
"pm_score": 3,
"selected": false,
"text": "imap <A-1> <Esc>:tabn 1<CR>i\nimap <A-2> <Esc>:tabn 2<CR>i\nimap <A-3> <Esc>:tabn 3<CR>i\nimap <A-4> <Esc>:tabn 4<CR>i\nimap <A-5> <Esc>:tabn 5<CR>i\nimap <A-6> <Esc>:tabn 6<CR>i\nimap <A-7> <Esc>:tabn 7<CR>i\nimap <A-8> <Esc>:tabn 8<CR>i\nimap <A-9> <Esc>:tabn 9<CR>i\n\nmap <A-1> :tabn 1<CR>\nmap <A-2> :tabn 2<CR>\nmap <A-3> :tabn 3<CR>\nmap <A-4> :tabn 4<CR>\nmap <A-5> :tabn 5<CR>\nmap <A-6> :tabn 6<CR>\nmap <A-7> :tabn 7<CR>\nmap <A-8> :tabn 8<CR>\nmap <A-9> :tabn 9<CR>\n"
},
{
"answer_id": 327484,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 6,
"selected": false,
"text": "gvim fuzzyfinder TextMate gvim fuzzyfinder\\_textmate mod/usob app/models/user\\_observer.rb fuzzyfinder\\_textmate fuzzyfinder.vim fuzzyfinder\\_textmate"
},
{
"answer_id": 329935,
"author": "Dave Ray",
"author_id": 40310,
"author_profile": "https://Stackoverflow.com/users/40310",
"pm_score": 5,
"selected": false,
"text": "\" Map ctrl-movement keys to window switching\nmap <C-k> <C-w><Up>\nmap <C-j> <C-w><Down>\nmap <C-l> <C-w><Right>\nmap <C-h> <C-w><Left>\n \" Switch to alternate file\nmap <C-Tab> :bnext<cr>\nmap <C-S-Tab> :bprevious<cr>\n"
},
{
"answer_id": 363034,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 2,
"selected": false,
"text": "map ;o :Sex <CR>\nmap <C-J> <C-W>j\nmap <C-K> <C-W>k\nmap <C-l> <C-W>l\nmap <C-h> <C-W>h\nmap ;] :tabnext<CR>\nmap ;[ :tabprev<CR>\nmap <C-t> :tabe +\"browse .\"<CR>\nmap <C-O> :NERDTreeToggle ~/curr/trunk/<CR>\n"
},
{
"answer_id": 3380656,
"author": "David Rivers",
"author_id": 224192,
"author_profile": "https://Stackoverflow.com/users/224192",
"pm_score": 6,
"selected": true,
"text": "\"\" Tab triggers buffer-name auto-completion\nset wildchar=<Tab> wildmenu wildmode=full\n\nlet mapleader = \",\"\n\nmap <Leader>t :CommandT<Return>\nmap <Leader>a :bprev<Return>\nmap <Leader>s :bnext<Return>\nmap <Leader>d :bd<Return>\nmap <Leader>f :b \n\n\"\" Show the buffer number in the status line.\nset laststatus=2 statusline=%02n:%<%f\\ %h%m%r%=%-14.(%l,%c%V%)\\ %P\n"
},
{
"answer_id": 8561689,
"author": "diegoviola",
"author_id": 776871,
"author_profile": "https://Stackoverflow.com/users/776871",
"pm_score": 2,
"selected": false,
"text": "nnoremap <Leader>l :ls<CR>:b<space>\n map <Leader>n :bn<CR>\nmap <Leader>p :bp<CR>\n"
},
{
"answer_id": 8562831,
"author": "KOlegA",
"author_id": 1031252,
"author_profile": "https://Stackoverflow.com/users/1031252",
"pm_score": 4,
"selected": false,
"text": "nmap <Leader>bb :ls<CR>:buffer<Space>\n"
},
{
"answer_id": 8788432,
"author": "puk",
"author_id": 654789,
"author_profile": "https://Stackoverflow.com/users/654789",
"pm_score": 2,
"selected": false,
"text": "<S-J> <S-K> :bp :bn <C-J> <C-K>"
},
{
"answer_id": 16661603,
"author": "Olivier Lalonde",
"author_id": 96855,
"author_profile": "https://Stackoverflow.com/users/96855",
"pm_score": 4,
"selected": false,
"text": ".vimrc map <C-J> :bnext<CR>\nmap <C-K> :bprev<CR>\nmap <C-L> :tabn<CR>\nmap <C-H> :tabp<CR>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204/"
] |
327,415 | <p>Using Windows key as Meta is very useful in Emacs, is there the way to do it in Vim?</p>
| [
{
"answer_id": 327469,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 3,
"selected": false,
"text": "#IfWinActive ahk_class GVIM\nRWin::Alt \nLWin::Alt \n#IfWinActive ; This puts subsequent remappings and hotkeys in effect for all windows.\n"
},
{
"answer_id": 2595589,
"author": "Yktula",
"author_id": 290128,
"author_profile": "https://Stackoverflow.com/users/290128",
"pm_score": 3,
"selected": false,
"text": "keysym Super_L = Escape ~/.Xmodmap xmodmap .Xmodmap echo \"keysym Super_L = Escape\" >> ~/.Xmodmap && xmodmap .Xmodmap xmodmap -e \"keysym Super_L = Escape\""
},
{
"answer_id": 11329061,
"author": "frp",
"author_id": 773606,
"author_profile": "https://Stackoverflow.com/users/773606",
"pm_score": 3,
"selected": false,
"text": ":nmap <T-F5> :q<cr> \n"
},
{
"answer_id": 22938137,
"author": "guest",
"author_id": 3511112,
"author_profile": "https://Stackoverflow.com/users/3511112",
"pm_score": 3,
"selected": false,
"text": "Win+q Ctrl+V Win+q ^X@sq ^X nnoremap ^X@sq :q<CR>\n Ctrl+v :help i_CTRL-V"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204/"
] |
327,417 | <p>How would I go about this?</p>
<p>I have a mostly static site, which is being hosted on a cheap web-host, which only allows FTP access to the hosting. The site is tracked in git. I am using OS X.</p>
<p>I would like to upload a new version of the site by simply doing <code>cap deploy</code></p>
| [
{
"answer_id": 327441,
"author": "Peter Coulton",
"author_id": 117,
"author_profile": "https://Stackoverflow.com/users/117",
"pm_score": 5,
"selected": true,
"text": "desc \"Sync\"\nnamespace :deploy do\n\n desc \"Sync remote by default\"\n task :default do\n remote.default\n end\n\n namespace :remote do\n\n desc \"Sync to remote server\"\n task :default do\n `rsync -avz \"/path/to/webapp\" \"#{remote_host}:#{remote_root}/path/to/webapp\"`\n end\n end\nend\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
327,429 | <p>I doing a function in Javascript like the VisualBasic DateDiff.</p>
<p>You give two dates and the returning time interval (Seconds, Minutes, Days, etc...)</p>
<pre><code>DateDiff(ByVal Interval As Microsoft.VisualBasic.DateInterval, _
ByVal Date1 As Date, ByVal Date2 As Date) as Long
</code></pre>
<p>So what's the best way to calculate the difference of Javascript Dates?</p>
| [
{
"answer_id": 327433,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "Date.getTime()\n var _MS_PER_DAY = 1000 * 60 * 60 * 24;\n\n// a and b are javascript Date objects\nfunction dateDiffInDays(a, b) {\n // Discard the time and time-zone information.\n var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());\n var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());\n\n return Math.floor((utc2 - utc1) / _MS_PER_DAY);\n}\n"
},
{
"answer_id": 327458,
"author": "Anand",
"author_id": 12649,
"author_profile": "https://Stackoverflow.com/users/12649",
"pm_score": 7,
"selected": true,
"text": "function DateDiff(var /*Date*/ date1, var /*Date*/ date2) {\n return date1.getTime() - date2.getTime();\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41385/"
] |
327,438 | <p>I'm writing a service that has five different methods that can take between 5 seconds and 5 minutes to run.</p>
<p>The service will schedule these different methods to run at different intervals.</p>
<p>I don't want any of the methods to run concurrently, so how do I have the methods check to see if another method is running and queue itself to run when it finishes?</p>
<p>Anthony</p>
| [
{
"answer_id": 327493,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "class ServiceClass\n{\n private object thisLock = new object();\n\n public Method1()\n {\n lock ( thisLock )\n {\n ...\n }\n }\n\n public Method2()\n {\n lock ( thisLock )\n {\n ...\n }\n }\n ...\n}\n"
},
{
"answer_id": 327494,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "[MethodImpl] [MethodImpl(MethodImplOptions.Synchronized)]\npublic void Foo() {...}\n\n[MethodImpl(MethodImplOptions.Synchronized)]\npublic void Bar() {...}\n this typeof(TheClass) private readonly object syncLock = new object(); // or static if needed\n\n...\npublic void Foo() {\n lock(syncLock) {\n ...\n }\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] |
327,448 | <p>I have found many tutorials about using Windows Server 2003 as a development machine, and very little information about Windows Server 2008 for the same purpose.</p>
<p>For a nicer experience, I have followed the steps from <a href="http://www.win2008workstation.com/wordpress/" rel="nofollow noreferrer">Convert your Windows Server 2008 to a Workstation</a>.</p>
<p>I am searching for the requirements and installation order for IIS 7 with IIS 6 compatibility mode, .NET Framework 3.5 SP1 (does it require the installation of <code>.NET Framework 3.0</code> feature, or can be installed directly), SQL Server 2005 SP2 (with Reporting services and Analysis Services), Visual Studio 2008 SP1.</p>
| [
{
"answer_id": 327451,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 4,
"selected": true,
"text": "SQL Server 2005 - installation order SQL Server 2005 - links"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19756/"
] |
327,454 | <p>I need to have some information about the Scoping issue in Javascript. I know that it spports lexical(static) scoping, but, does not it support dynamic scoping as well?
If you know anything about the scoping in Javascript, would you please share them with me ?</p>
<p>Thanks</p>
| [
{
"answer_id": 327485,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 4,
"selected": true,
"text": "var foo = \"old\";\nif (true) {var foo = \"new\";}\nalert (foo == \"new\")\n functions = [];\nfor(var i=0; i<10; i++) {\n (function(){\n var local_i = i;\n functions[local_i] = function() {return local_i;}\n })();\n}\nfunctions[2]() // returns 2 and not 10\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41777/"
] |
327,483 | <p>I'm trying to do the following in python:</p>
<p>In a file called foo.py:</p>
<pre><code># simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
</code></pre>
<p>And then in a file called bar.py:
import foo</p>
<pre><code>d = foo.data
d.fn(1,2,3)
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)</p>
</blockquote>
<p>This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.</p>
<p>So the question is:</p>
<p><strong><em>How can I store a function in a class object without the function becoming bound to that class?</em></strong></p>
| [
{
"answer_id": 327488,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 6,
"selected": true,
"text": "data.fn = staticmethod(myFunction)\n"
},
{
"answer_id": 327530,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "d = foo.data()\nd.fn = myFunction\n\nd.fn(1,2,3)\n"
},
{
"answer_id": 328700,
"author": "Thomi",
"author_id": 1304,
"author_profile": "https://Stackoverflow.com/users/1304",
"pm_score": 0,
"selected": false,
"text": "# this is my custom code - all plugins are called with a modified sys.path, so this\n# imports some magic python code that defines the functions used below.\nfrom specialPluginHelperModule import *\n\n# define the function that does all the work in this plugin:\ndef mySpecialFn(paramA, paramB, paramC):\n # do some work here with the parameters above:\n pass\n\n# set the above function:\nsetPluginFunction(mySpecialFn)\n setPluginFunction runpy"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] |
327,486 | <p>I need to stop the execution Is there any procedures for using terminate and suspend activity</p>
| [
{
"answer_id": 356864,
"author": "gbanfill",
"author_id": 45068,
"author_profile": "https://Stackoverflow.com/users/45068",
"pm_score": 2,
"selected": true,
"text": "WorkflowInstance instance = runtime.GetWorkflow(instanceId);\ninstance.Suspend(\"Paused for some good reason\");\n\n// do something here\n\ninstance.Resume();\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
327,487 | <p>i have problem i want to </p>
<p>select name_magazine from magazine</p>
<p>and i already import all library needed</p>
<p>and </p>
<blockquote>
<p>Query q = EntityManger.createQuery ("SELECT name_magazine FROM Magazine");</p>
<p>List results = (List) q.getResultList ();</p>
<p>For(Sting s : result)</p>
<p>System.out.println(s);</p>
</blockquote>
<p>but when i run this code it's error. can someone help me? Thx</p>
<p>this the error when i run the program</p>
<blockquote>
<p>Exception in thread "AWT-EventQueue-0"
java.lang.Error:
java.lang.reflect.InvocationTargetException
at org.jdesktop.application.ApplicationAction.actionFailed(ApplicationAction.java:859)
at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:665)
at org.jdesktop.application.ApplicationAction.actionPerformed(ApplicationAction.java:698)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1220)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1261)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:662)
... 29 more Caused by: java.lang.IllegalArgumentException: An
exception occured while creating a
query in EntityManager
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.createQuery(EntityManagerImpl.java:209)
at tugas_rpl.Tugas_RPLView.Iseng(Tugas_RPLView.java:734)
... 34 more Caused by: Exception [TOPLINK-8034] (Oracle
TopLink Essentials - 2.0.1 (Build
b09d-fcs (12/06/2007))):
oracle.toplink.essentials.exceptions.EJBQLException
Exception Description: Error compiling
the query [Select m.Name from
magazine m]. Unknown abstract schema type
[magazine].
at oracle.toplink.essentials.exceptions.EJBQLException.unknownAbstractSchemaType(EJBQLException.java:494)
at oracle.toplink.essentials.internal.parsing.ParseTreeContext.classForSchemaName(ParseTreeContext.java:163)
at oracle.toplink.essentials.internal.parsing.VariableNode.resolveClass(VariableNode.java:280)
at oracle.toplink.essentials.internal.parsing.DotNode.resolveMapping(DotNode.java:254)
at oracle.toplink.essentials.internal.parsing.DotNode.endsWithDirectToField(DotNode.java:213)
at oracle.toplink.essentials.internal.parsing.SelectNode.selectingDirectToField(SelectNode.java:440)
at oracle.toplink.essentials.internal.parsing.SelectNode.hasOneToOneSelected(SelectNode.java:265)
at oracle.toplink.essentials.internal.parsing.SelectNode.hasOneToOneSelected(SelectNode.java:222)
at oracle.toplink.essentials.internal.parsing.SelectGenerationContext.computeUseParallelExpressions(SelectGenerationContext.java:105)
at oracle.toplink.essentials.internal.parsing.SelectGenerationContext.(SelectGenerationContext.java:88)
at oracle.toplink.essentials.internal.parsing.ParseTree.buildContextForReadQuery(ParseTree.java:382)
at oracle.toplink.essentials.internal.parsing.ParseTree.buildContext(ParseTree.java:370)
at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.buildContext(EJBQLParseTree.java:68)
at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.populateQuery(EJBQLParseTree.java:107)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:219)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:189)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:153)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.(EJBQueryImpl.java:114)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.(EJBQueryImpl.java:99)
at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.(EJBQueryImpl.java:86)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.createQuery(EntityManagerImpl.java:204)
... 35 more</p>
</blockquote>
<p>I already try Vincent Ramdhanie,Guðmundur Bjarni suggestion</p>
<blockquote>
<p>Query q = entityManager.createQuery("Select m.name from magazine m");</p>
<p>List result = (List) q.getResultList();</p>
<p>For(Sting s : result)</p>
<p>System.out.print(s);</p>
</blockquote>
<p>but still error</p>
<p>this what library & variable i use</p>
<blockquote>
<p>private javax.persistence.EntityManager entityManager;</p>
<p>import org.jdesktop.application.Action;</p>
<p>import org.jdesktop.application.ResourceMap;</p>
<p>import org.jdesktop.application.SingleFrameApplication;</p>
<p>import org.jdesktop.application.FrameView;</p>
<p>import org.jdesktop.application.TaskMonitor;</p>
<p>import org.jdesktop.application.Task;</p>
<p>import java.awt.event.ActionEvent;</p>
<p>import java.awt.event.ActionListener;</p>
<p>import java.util.ArrayList;</p>
<p>import java.util.List;</p>
<p>import javax.swing.Timer;</p>
<p>import javax.swing.Icon;</p>
<p>import javax.swing.JDialog;</p>
<p>import javax.swing.JFrame;</p>
<p>import javax.swing.event.ListSelectionEvent;</p>
<p>import javax.swing.event.ListSelectionListener;</p>
<p>import org.jdesktop.beansbinding.AbstractBindingListener;</p>
<p>import org.jdesktop.beansbinding.Binding;</p>
<p>import org.jdesktop.beansbinding.PropertyStateEvent;</p>
<p>import javax.persistence.*;</p>
</blockquote>
| [
{
"answer_id": 327497,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": " select m from Magazine m\n"
},
{
"answer_id": 327504,
"author": "Guðmundur Bjarni",
"author_id": 27349,
"author_profile": "https://Stackoverflow.com/users/27349",
"pm_score": 1,
"selected": false,
"text": "@Entity\n@Table(name = \"magazines\")\npublic class Magazine {\n /*\n * Some more attributes\n */\n\n @Column(name = \"name_magazine\")\n private String name;\n\n /*\n * Constructors, getters and setters\n */\n}\n from Magazine m\n select m.name from Magazine m \n"
},
{
"answer_id": 327764,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "Error compiling the query [Select m.Jenis_Motor from motor m]. Unknown abstract schema type [motor].\n"
},
{
"answer_id": 48780411,
"author": "karan",
"author_id": 8818943,
"author_profile": "https://Stackoverflow.com/users/8818943",
"pm_score": 0,
"selected": false,
"text": "Query q = EntityManger.createQuery (\"SELECT name_magazine e FROM Magazine e\");\n <class>PackageName.className</class>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41780/"
] |
327,499 | <p>In standard ASP.net applications ASP.net offered some protection from XSS attacks with validateRequest throwing detect dangerous input errors if some one tried to. This functionality seems to have been taken out of MVC any idea why?</p>
| [
{
"answer_id": 708810,
"author": "Sruly",
"author_id": 72453,
"author_profile": "https://Stackoverflow.com/users/72453",
"pm_score": 3,
"selected": false,
"text": "[ValidateInput(true)]\npublic ActionResult Foo()\n{\n\n}\n public class MyModel\n{\n public Guid ID { get; set; }\n\n [AllowHtml]\n public string SomeStringValue { get; set; }\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
327,500 | <p>I have a file with n lines. (n above 100 millions)</p>
<p>I want to output a file with only 1 of 10 lines, I can't split the file in ten part and keep only one part, as it must be a little more random. later I have to do a statistical analysis I can't afford to create a strong bias in the data).</p>
<p>I was thinking of reading the file and for each record if the record number mod 10 then output it.</p>
<p>The constraints are:</p>
<ul>
<li><p>it's a windows (likely hardened) computer possibly XP Vista or Windows server 2003.</p></li>
<li><p>no development tools available</p></li>
<li><p>no network,usb,cd-rom. read no external communication.</p></li>
</ul>
<p>Therefore I was thinking of windows batch file (I can't assume powershell, and vbscript is likely to have been removed). And at the moment looking at the FOR /F command.
Still I am not an expert and I don't know how to achieve this.</p>
<p><em>Thank you Paul for your answer.
I reformat (with Hosam help) the answer to put it in a batch file:</em></p>
<pre><code>@echo off
setlocal
findstr/N . inputFile| findstr ^[0-9]*0: >temporaryFile
FOR /F "tokens=1,* delims=: " %%i in (temporaryfile) do echo %%j > outputFile
</code></pre>
<p><em>Thanks quux and Pax for the similar alternative solution. However after a quick test on a larger file Paul's answer is roughly 8 times faster. I guess the evaluation (in SET) is kind of slow, even if the logic seems brilliant.</em></p>
| [
{
"answer_id": 327510,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 4,
"selected": true,
"text": "findstr/N . path-to-log-file | findstr ^[0-9]*0:\n FOR /F \"tokens=1,2* delims=: \" %i in (file-with-linenumbers) do echo %j\n"
},
{
"answer_id": 327523,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "@echo off\nsetlocal\n\nset /a \"n = 0\"\nfor /f %%i in (lines32.txt) do call :fn %%i\nendlocal\ngoto :eof\n\n:fn\nset /a \"n = n + 1\"\nif not %n%==10 goto :eof\necho %1\nset /a \"n = 0\"\ngoto :eof\n"
},
{
"answer_id": 327535,
"author": "Hosam Aly",
"author_id": 41283,
"author_profile": "https://Stackoverflow.com/users/41283",
"pm_score": 1,
"selected": false,
"text": "findstr /n . yourLogFile.txt | findstr ^[0-9]*0: > numberedFile.txt\nfor /f \"tokens=1,2* delims=:\" %i in (numberedFile.txt) do echo %j > smallFile.txt\ndel numberedFile.txt\n"
},
{
"answer_id": 327542,
"author": "quux",
"author_id": 2383,
"author_profile": "https://Stackoverflow.com/users/2383",
"pm_score": 1,
"selected": false,
"text": "@ECHO OFF\nSETLOCAL\nSET lastdigit=7\nSET linecounter=0\nFOR /F \"tokens=*\" %%a IN (text.txt) DO CALL :picker %%a\nENDLOCAL\nGOTO :eof\n\n:picker\nset line=%*\nIF {%linecounter:~-1%} == {%lastdigit%} ECHO %linecounter% %line%\nSET /a linecounter=%linecounter% + 1\nGOTO :eof\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24334/"
] |
327,506 | <p>I've a HTML page with several Div's that will show the time difference between now and each given date.</p>
<pre><code><div class="dated" onEvent="calculateHTML(this, 'Sat Jun 09 2007 17:46:21')">
30 Minutes Ago</div>
</code></pre>
<p>I want that time difference to be dynamic (calculated to all elements when the page loads and also within a time interval)</p>
<p>So, my idea was to go to all div's of class "dated", calculate the time diference for each one and replace the correspondent innerHTML.</p>
<p>Is this the best aproach or should I try a different one?</p>
<p>Edit:
<br>One of the problems I've encountered was, where do I keep within the div, the date that will be used to generate the text?</p>
| [
{
"answer_id": 327515,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 2,
"selected": true,
"text": "function adjustDates() {\n var i;\n var elms = document.getElementsByTagName(\"div\");\n for (i = 0; i < elms.length; i++) {\n var e = elms[i];\n\n /* update timestamps with date */\n if (elementHasClass(e, \"dated\")) {\n var txt = YOUR_DIFFERENCE_CODE(e);\n e.replaceChild(document.createTextNode(txt), e.lastChild);\n }\n }\n}\n"
},
{
"answer_id": 327528,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function(){\n $(\".dated\").each(function (i) {\n //your code here--this refers to the current element\n });\n\n});\n $(document).ready(function(){\n $.timer(1000, function (timer) {\n $(\".dated\").each(function (i) {\n //your code here--this refers to the current element\n });\n\n });\n});\n"
},
{
"answer_id": 327588,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 2,
"selected": false,
"text": "<div class=\"dated\">\n <span style=\"display: none\">'Sat Jun 09 2007 17:46:21'</span>\n <p>30 minutes ago.</p>\n</div>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41385/"
] |
327,512 | <p>I've created a login submit form in HTML but for some reason user/password autocompletion does not work like I expect in firefox.</p>
<p>This is what happens in Firefox:</p>
<ul>
<li>I give username and password and click on the login button</li>
<li>Firefox prompts me if I would like to remember the password. I press 'remember' and login works. (I made sure I deleted all remembered passwords before running this test)</li>
<li>I log out and return to the login page. I would expect the username and password field to be prefilled but that is not the case (if FF has stored only one user/pw combi for a specific URL than it automatically prefills this combi in your form)</li>
</ul>
<p>Notice that I don't (want to) use cookies. I verified in FF password manager that username and password had actually been stored (they were)</p>
<p>Here's the code for this page:</p>
<pre><code><form name="login_form" id="login_form" autocomplete="ON" onsubmit="javascript:xajax_action_login(document.getElementById('user_name').value, document.getElementById('password').value); return false;">
<div class="login_line">
<div class="login_line_left">name</div>
<div id="user_name_id" class="login_line_right"><input size="16" maxlength="16" name="user_name" id="user_name" type="text"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left">password</div>
<div id="password_id" class="login_line_right"><input size="16" maxlength="16" name="password" id="password" type="password"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left"> </div>
<div class="login_line_right"><input class="button" value="login" type="submit">
</div> <!-- login_line -->
</form> <!-- login_form -->
</code></pre>
<p>What is wrong with my code? How can I get autocompletion to work in FF with my code?</p>
<p>Autocompletion does work correct with for instance gmail. Each time I visit the login page of gmail, the email and password fields are correctly prefilled. I don't use the 'remember me on this computer' checkbox so no cookies are used.</p>
<p>I would greatly appriciate your help.
Jasper</p>
<p><strong>Update</strong><br>
Autocomplete is enabled in firefox. I want to stay IE compatible.</p>
| [
{
"answer_id": 329949,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 0,
"selected": false,
"text": "autocomplete=\"ON\" <form> autocomplete=\"on\""
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40323/"
] |
327,513 | <p>I'm looking for a high performance Java library for fuzzy string search.</p>
<p>There are numerous algorithms to find similar strings, Levenshtein distance, Daitch-Mokotoff Soundex, n-grams etc.</p>
<p>What Java implementations exists? Pros and cons for them? I'm aware of Lucene, any other solution or Lucene is best?</p>
<p>I found these, does anyone have experience with them? </p>
<ul>
<li><a href="http://www.dcs.shef.ac.uk/~sam/simmetrics.html" rel="noreferrer">SimMetrics</a> </li>
<li><a href="http://ngramj.sourceforge.net/" rel="noreferrer">NGramJ</a> </li>
</ul>
| [
{
"answer_id": 33125667,
"author": "Henno Vermeulen",
"author_id": 593533,
"author_profile": "https://Stackoverflow.com/users/593533",
"pm_score": 4,
"selected": false,
"text": "public static List<Integer> find(String doc, String pattern, int k)\n StringUtils String.equals String.indexOf ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException BitapOnlineSearcher java.io.Reader"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41781/"
] |
327,525 | <p>I would like to show some links only to authenticated users in an asp.net mvc web application.</p>
<ul>
<li>I use the template for an asp.net mvc web application in Visual Studio 2008 that came with the beta release of asp.net mvc.</li>
<li>I use forms authentication.</li>
<li>I would like to add something like the following to an existing view:</li>
</ul>
<pre>
<a href="/Account/ChangePassword">Change password</a>
</pre>
<p>and only show the link to users who are logged in. </p>
<p>What is the simplest way to do that? I would like something as simple as security trimming of the web.sitemap that I have tried with asp.net web forms. (Can that be used with mvc? Or is it only for web forms?)</p>
| [
{
"answer_id": 327539,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": " <% if (HttpContext.Current.Request.IsAuthenticated) { %>\n <a href=\"/Account/ChangePassword\">Change password</a>\n <% } %>\n"
},
{
"answer_id": 327545,
"author": "Trevor de Koekkoek",
"author_id": 41783,
"author_profile": "https://Stackoverflow.com/users/41783",
"pm_score": 2,
"selected": false,
"text": "<%if (Page.User.Identity.IsAuthenticated){ %>\n <p>show change password link</p>\n<% }\n else \n { %>\n <p> show login link</p>\n<% } %>\n"
},
{
"answer_id": 327663,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<% if (Request.IsAuthenticated) { %>\n <a href=\"/Account/ChangePassword\">Change password</a>\n<% } %>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41094/"
] |
327,531 | <p>i made another post</p>
<p><a href="https://stackoverflow.com/questions/326885/a-loop-to-create-neighbor-nodes-in-3d-space">here</a> where I asked how to create the 26 neighbors of a cubic-voxel-node in 3-d space. I got a very good answer and implemented it. </p>
<p>To that I added some MIN MAX Position checking.</p>
<p>I would like to know if there is way, <strong>in relationship to the 3 for loops and 4 if used</strong>, to improve the execution time of this code. I have read in another post sth that when using while loops is faster but it was in a post not language specific. </p>
<p>Is this true? If yes, could u please help me to this in my code because i luck experience?
Is there a way to implement this recursively in a way that will make it faster?</p>
<p>here is my code:</p>
<pre><code>...
std::vector<Pos> Create26Neighbor(Pos somePos, double resol)
{
std::vector <Pos> vect1;
Pos m_MinPos(0.0,0.0,0.0);
Pos m_MaxPos(5.0,4.0,5.0);
for (double dz = somePos.m_pPos[2] - resol; dz <= somePos.m_pPos[2] + resol; dz+=resol)
{
if (dz>m_MinPos.m_pPos[2] && dz<m_MaxPos.m_pPos[2])
{
for (double dy = someCPos.m_pPos[1] - resol; dy <= someCPos.m_pPos[1] + resol; dy+=resol)
{
if (dy>m_MinPos.m_pPos[1] && dy<m_MaxPos.m_pPos[1])
{
for (double dx = somePos.m_pPos[0] - resol; dx <= somePos.m_pPos[0] + resol; dx+=resol)
{
if (dx>m_MinPos.m_pPos[0] && dx<m_MaxPos.m_pPos[0])
{
// all 27
if ((dx != somePos.m_pPos[0]) || (dy != somePos.m_pPos[1]) || (dz != somePos.m_pPos[2]))
{
Pos tempPos(dx,dy,dz);
vect1.push_back(tempPos);
}
}
}
}
}
}
}
return vect1;
}
....
</code></pre>
| [
{
"answer_id": 327547,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "std::vector<Pos> vect1;\nvect1.reserve(27);"
},
{
"answer_id": 327552,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 1,
"selected": false,
"text": "for (d_ = somPos._ - resol; d_ <= somPos_.+resol; d_+= resol)\n double dz = somePos.m_pPos[2] - resol; \nfor(z = 0; z < 3; z++, dz += resol)\n"
},
{
"answer_id": 327586,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 3,
"selected": false,
"text": "std::vector<Pos> Create26Neighbor(Pos somePos, double resol) \n{\n std::vector <Pos> vect1(27); // Initialize the vector with the correct size.\n Pos m_MinPos(0.0,0.0,0.0);\n Pos m_MaxPos(5.0,4.0,5.0);\n\n double minz = std::max(somePos.m_pPos[2] - resol, m_MinPos.m_pPos[2]);\n double maxz = std::min(somePos.m_pPos[2] + resol, m_MaxPos.m_pPos[2];\n int i = 0;\n for (double dz = min; dz <= max; dz+=resol)\n {\n double miny = std::max(somePos.m_pPos[1] - resol, m_MinPos.m_pPos[1]);\n double maxy = std::min(somePos.m_pPos[1] + resol, m_MaxPos.m_pPos[1];\n for (double dy = miny; dy <= maxy; dy+=resol)\n {\n double minx = std::max(somePos.m_pPos[0] - resol, m_MinPos.m_pPos[0]);\n double maxx = std::min(somePos.m_pPos[0] + resol, m_MaxPos.m_pPos[0];\n\n for (double dx = minx; dx <= maxx; dx+=resol)\n {\n ++i;\n // If we're not at the center, just use 'i' as index. Otherwise use i+1\n int idx = (dx != somePos.m_pPos[0] || dy != somePos.m_pPos[1] || dz != somePos.m_pPos[2]) ? i : i+1;\n vec1[idx] = Pos(dx, dy, dz); // Construct Pos on the spot, *might* save you a copy, compared to initilizing it, storing it as a local variable, and then copying it into the vector.\n }\n }\n }\n return vect1;\n}\n"
},
{
"answer_id": 327590,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "function generate26( x,y,z ){ \n return [ \n # Top \n # Left\n [x-1,y+1,z-1], \n [x-1,y+1,z],\n [x-1,y+1,z+1]\n ];\n}"
},
{
"answer_id": 327890,
"author": "Die in Sente",
"author_id": 40756,
"author_profile": "https://Stackoverflow.com/users/40756",
"pm_score": 1,
"selected": false,
"text": "case 1: {somePos[i] - resol}; // 1 value only\ncase 2: {somePos[i] - resol, somePos[i]} // 2 values\ncase 3: {somePos[i] - resol, somePos[i], somePos[i] + resol} // all 3\ncase 4: {somePos[i], somePos[i] + resol} // 2 values again\ncase 5: {somePos[i] + resol} // 1 value only\n enum eCase {\nCASE_NONE = 0,\nCASE_LOW1 = 1,\nCASE_LOW2 = 2,\nCASE_ALL3 = 3,\nCASE_HIGH2 = 4,\nCASE_HIGH1 = 5,\n};\n\neCase Xcase = /* a function of somePos[0], m_MinPos[0], m_MaxPos[0], and resol */\neCase Ycase = ...\neCase Zcase = ...\n\n#define MUNGE(_x,_y,_z) (((((_x)*6)+(_y))*6)+(_z))\nswitch (MUNGE(Xcase, Ycase, Zcase) {\n\ndefault:\n break; // all CASE_NONE's do nothing\ncase MUNGE (CASE_ALL3, CASE_ALL3, CASE_ALL3):\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] ));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] + resol));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] , somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] , somePos.m_pPos[2] ));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] , somePos.m_pPos[2] + resol));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] ));\n vect1.push_back( pos (somePos.m_pPos[0] - resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] + resol));\n\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] - resol, somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] - resol, somePos.m_pPos[2] ));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] - resol, somePos.m_pPos[2] + resol));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] , somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] , somePos.m_pPos[2] + resol));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] + resol, somePos.m_pPos[2] - resol));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] + resol, somePos.m_pPos[2] ));\n vect1.push_back( pos (somePos.m_pPos[0] , somePos.m_pPos[1] + resol, somePos.m_pPos[2] + resol));\n\n\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] - resol));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] ));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] - resol, somePos.m_pPos[2] + resol));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] , somePos.m_pPos[2] - resol));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] , somePos.m_pPos[2] ));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] , somePos.m_pPos[2] + resol));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] - resol));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] ));\nvect1.push_back( pos (somePos.m_pPos[0] + resol, somePos.m_pPos[1] + resol, somePos.m_pPos[2] + resol));\nbreak;\n"
},
{
"answer_id": 327930,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 1,
"selected": false,
"text": "std::vector<Pos> Create26Neighbor(Pos somePos, double resol) \n{\n std::vector<Pos> vect1(26);\n Pos m_MinPos(0.0,0.0,0.0);\n Pos m_MaxPos(5.0,4.0,5.0);\n\n double z = somePos.m_pPos[2] - resol;\n\n for(int dz = -1; dz <= 1; ++dz) {\n z += resol;\n if(z <= m_MinPos.m_pPos[2] || z >= m_MaxPos.m_pPos[2])\n continue;\n\n double y = somePos.m_pPos[1] - resol;\n\n for(int dy = -1; dy <= 1; ++dy) {\n y += resol;\n if(y <= m_MinPos.m_pPos[1] || y >= m_MaxPos.m_pPos[1])\n continue;\n\n double x = somePos.m_pPos[0] - resol;\n\n for(int dx = -1; dx <= 1; ++dx) {\n x += resol;\n\n if(dx == 0 && dy == 0 && dz == 0)\n continue;\n\n if(x <= m_MinPos.m_pPos[0] || x >= m_MaxPos.m_pPos[0])\n continue;\n\n vect1.push_back(Pos(x, y, z));\n }\n }\n }\n\n return vect1;\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41706/"
] |
327,534 | <p>I have a list of data that looks like the following:</p>
<pre><code>// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
</code></pre>
<p>... and I want to make this look like:</p>
<pre><code>0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
</code></pre>
<p>My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:</p>
<pre><code># where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
</code></pre>
<p>Now this causes IDLE to fail. However, if I do:</p>
<pre><code># code 2
d[t] = []
d[t].append(c)
</code></pre>
<p>... this works. </p>
<p>So the question is: why does code 2 work, but code 1 doesn't?</p>
<p>PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. </p>
| [
{
"answer_id": 327548,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": true,
"text": "d[t].append(c)\n d[t] d = {}\nt = 0\nd[t]\n d t d[t] = []\nd[t]\n d t setdefault d.setdefault(t,[]).append(c) defaultdict(list) {} d= collections.defaultdict(list)\nfor ts, x, y in someFileOrListOrQueryOrWhatever:\n d[ts].append( (x,y) )\n d= {}\n if t not in d:\n d[t] = list()\nd[t].append( c )\n d= {}\n d.setdefault(t,list()).append( c )\n setdefault import collections\nd = collections.defaultdict(list)\n d[t].append( c )\n defaultdict list"
},
{
"answer_id": 327558,
"author": "JuanDeLosMuertos",
"author_id": 39339,
"author_profile": "https://Stackoverflow.com/users/39339",
"pm_score": 1,
"selected": false,
"text": "dict=[] //it's not a dict, it's a list, the dictionary is dict={}\nelem=[1,2,3]\ndict.append(elem)\n print dict[0] // 0 is the index\n [1, 2, 3]\n"
},
{
"answer_id": 327575,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 4,
"selected": false,
"text": "d.setdefault(t, []).append(c)\n .setdefault t t .append c"
},
{
"answer_id": 332525,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env python\n\"\"\"\n$ cat data_shuffled.txt\n0,2,7\n1,4,7\n0,4,7\n1,9,0\n1,2,5\n0,6,7\n1,6,8\n0,9,5\n\"\"\"\nfrom itertools import groupby\nfrom operator import itemgetter\n\n# load the data and make sure it is sorted by the first column\nsortby_key = itemgetter(0)\ndata = sorted((map(int, line.split(',')) for line in open('data_shuffled.txt')),\n key=sortby_key)\n\n# group by the first column\ngrouped_data = []\nfor key, group in groupby(data, key=sortby_key):\n assert key == len(grouped_data) # assume the first column is 0,1, ...\n grouped_data.append([trio[1:] for trio in group])\n\n# print the data\nfor i, pairs in enumerate(grouped_data):\n print i, pairs\n 0 [[2, 7], [4, 7], [6, 7], [9, 5]]\n1 [[4, 7], [9, 0], [2, 5], [6, 8]]\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41121/"
] |
327,544 | <p>In my program I have one array with 25 double values 0.04
When I try to sum these values in a loop I get following results:</p>
<pre><code>0.0 + 0.04 = 0.04
0.04 + 0.04 = 0.08
0.08 + 0.04 = 0.12
0.12 + 0.04 = 0.16
0.16 + 0.04 = 0.2
0.2 + 0.04 = 0.24000000000000002
0.24000000000000002 + 0.04 = 0.28
0.28 + 0.04 = 0.32
0.32 + 0.04 = 0.36
0.36 + 0.04 = 0.39999999999999997
0.39999999999999997 + 0.04 = 0.43999999999999995
0.43999999999999995 + 0.04 = 0.4799999999999999
0.4799999999999999 + 0.04 = 0.5199999999999999
0.5199999999999999 + 0.04 = 0.5599999999999999
0.5599999999999999 + 0.04 = 0.6
0.6 + 0.04 = 0.64
0.64 + 0.04 = 0.68
0.68 + 0.04 = 0.7200000000000001
0.7200000000000001 + 0.04 = 0.7600000000000001
0.7600000000000001 + 0.04 = 0.8000000000000002
0.8000000000000002 + 0.04 = 0.8400000000000002
0.8400000000000002 + 0.04 = 0.8800000000000002
0.8800000000000002 + 0.04 = 0.9200000000000003
0.9200000000000003 + 0.04 = 0.9600000000000003
</code></pre>
<p>Why on earth could that happen?!</p>
| [
{
"answer_id": 327567,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "numeric"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35594/"
] |
327,555 | <p>There are important features of Emacs which are missing in Vim, such as the comint mode, and there are no scripts/plugins which can replace them.</p>
<p>There are also benefits of Vim over Emacs, such as modal editing and generally better default shortcuts. However, Viper mode gets me both. Vimpulse also enables visual mode.
Unfortunately, no mode can make Emacs work as fast as Vim.</p>
<p>So I mostly learned Vim-in-Emacs. What Vim features am I missing?</p>
| [
{
"answer_id": 330617,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "vimpulse cat diw di( di\" \"\" () :he"
},
{
"answer_id": 381901,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": ". C-."
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204/"
] |
327,562 | <p>I use codes below to see a result like picture 1, but a result like picture 2 is coming. What should be done to solve it?</p>
<p>aspx code:</p>
<pre><code><asp:datalist id="dtlUrun" runat="server" RepeatDirection="Horizontal">
<ItemTemplate>
<table class="dtlTable">
<tr>
<td class="dtlHeader"></td>
<td class="dtlHeader"><%#DataBinder.Eval(Container.DataItem, "DS_MAMUL")%></td>
</tr>
<asp:DataList ID="dtlBayi" Runat="server">
<ItemTemplate>
<tr>
<td class="dtlColumn"><%#DataBinder.Eval(Container.DataItem, "DS_BAYI")%></td>
<td class="dtlColumn"><%#DataBinder.Eval(Container.DataItem, "MT_MIKTAR")%></td>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
</ItemTemplate>
</asp:datalist>
</code></pre>
<p>Style:</p>
<pre><code> <style type="text/css">
.dtlTable {
BORDER-RIGHT: #000000 1px solid;
BORDER-TOP: #000000 1px solid;
BORDER-LEFT: #000000 1px solid;
BORDER-BOTTOM: #000000 1px solid;
BORDER-COLLAPSE: collapse;
BACKGROUND-COLOR: #fafafa;
border-spacing: 0px;
}
.dtlColumn {
PADDING-RIGHT: 0px;
PADDING-LEFT: 8px;
FONT-WEIGHT: normal;
FONT-SIZE: 0.7em;
PADDING-BOTTOM: 4px;
COLOR: #404040;
PADDING-TOP: 4px;
BORDER-BOTTOM: #6699cc 1px dotted;
FONT-FAMILY: Verdana, sans-serif, Arial;
BACKGROUND-COLOR: #fafafa;
TEXT-ALIGN: left;
}
.dtlHeader {
BORDER-RIGHT: #000000 1px solid;
BORDER-TOP: #000000 1px solid;
FONT-WEIGHT: bold;
FONT-SIZE: 12px;
BORDER-LEFT: #000000 1px solid;
COLOR: #404040;
BORDER-BOTTOM: #000000 1px solid;
FONT-FAMILY: Verdana;
BACKGROUND-COLOR: #99cccc;
}
</script>
</code></pre>
<p>vb Code:</p>
<pre><code>Private Sub bindGrid()
Dim objUrun As New caynet_class.cls_LU_MAMUL
Me.dtlUrun.DataSource = objUrun.GetBy_MAMUL_ARALIGI(Session("CAY_NEVILERI_SATIS_KRITER")("MAMUL_NO1"), Session("CAY_NEVILERI_SATIS_KRITER")("MAMUL_NO2"))
Me.dtlUrun.DataBind()
End Sub
Private Sub dtlUrun_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dtlUrun.ItemDataBound
If Not e.Item.ItemIndex = -1 Then
Dim mamulNo As Integer = CType(DataBinder.Eval(e.Item.DataItem, "MAMUL_NO"), Integer)
CType(e.Item.FindControl("dtlBayi"), DataList).DataSource = caynet_class.cls_RAPOR_SATIS.Get_Cay_Nevileri_Satis2(mamulNo)
CType(e.Item.FindControl("dtlBayi"), DataList).DataBind()
Session("dtlDurum") = False
End If
End Sub
</code></pre>
<p>Picture 1: <a href="http://img146.imageshack.us/my.php?image=89632085xz4.jpg" rel="nofollow noreferrer">http://img146.imageshack.us/my.php?image=89632085xz4.jpg</a></p>
<p>Picture2: <a href="http://img227.imageshack.us/my.php?image=15383944jq6.jpg" rel="nofollow noreferrer">http://img227.imageshack.us/my.php?image=15383944jq6.jpg</a></p>
| [
{
"answer_id": 327577,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<asp:dataList id=\"\" runat=\"server\">\n <headertemplate>\n <table>\n <tr>\n </headertemplate>\n <itemtemplate>\n <td>\n <!-- Your template here -->\n </td>\n </itemtemplate>\n <footertemplate>\n </tr></table>\n </footertemplate>\n</asp:datalist>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439507/"
] |
327,569 | <p>I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my application is a school assignment which will demonstrate walking a tree of objects and serializing to text using visitor pattern, so I'm not thinking in real world terms here. Basically all I need here is tags, attributes and text nodes.</p>
| [
{
"answer_id": 327600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "java.util.Scanner java.util.StringTokenizer the org.apache.commons.lang.text"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6254/"
] |
327,573 | <p>If I have a function that needs to work with a <code>shared_ptr</code>, wouldn't it be more efficient to pass it a reference to it (so to avoid copying the <code>shared_ptr</code> object)?
What are the possible bad side effects?
I envision two possible cases:</p>
<p>1) inside the function a copy is made of the argument, like in</p>
<pre><code>ClassA::take_copy_of_sp(boost::shared_ptr<foo> &sp)
{
...
m_sp_member=sp; //This will copy the object, incrementing refcount
...
}
</code></pre>
<p>2) inside the function the argument is only used, like in </p>
<pre><code>Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here
{
...
sp->do_something();
...
}
</code></pre>
<p>I can't see in both cases a good reason to pass the <code>boost::shared_ptr<foo></code> by value instead of by reference. Passing by value would only "temporarily" increment the reference count due to the copying, and then decrement it when exiting the function scope.
Am I overlooking something?</p>
<p>Just to clarify, after reading several answers: I perfectly agree on the premature-optimization concerns, and I always try to first-profile-then-work-on-the-hotspots. My question was more from a purely technical code-point-of-view, if you know what I mean.</p>
| [
{
"answer_id": 327581,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "void ClassA::take_copy_of_sp(boost::shared_ptr<foo> sp) {\n m_sp_member.swap(sp);\n}\n"
},
{
"answer_id": 327669,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "Class::only_work_with_sp(foo &sp)\n{ \n ... \n sp.do_something(); \n ... \n}\n only_work_with_sp(*sp);\n"
},
{
"answer_id": 327866,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 2,
"selected": false,
"text": "const & const &"
},
{
"answer_id": 328714,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 8,
"selected": true,
"text": "shared_ptr shared_ptr Class::only_work_with_sp(boost::shared_ptr<foo> sp)\n{\n // sp points to an object that cannot be destroyed during this function\n}\n shared_ptr Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here \n{ \n ... \n sp->do_something(); \n ... \n}\n sp->do_something() shared_ptr shared_ptr std::string shared_ptr void send_message(std::shared_ptr<std::string> msg)\n{\n std::cout << (*msg.get()) << std::endl;\n}\n std::shared_ptr<std::string> previous_message;\n void send_message(std::shared_ptr<std::string> msg)\n{\n previous_message = 0;\n std::cout << *msg << std::endl;\n previous_message = msg;\n}\n send_message(std::shared_ptr<std::string>(new std::string(\"Hi\")));\nsend_message(previous_message);\n Hi! send_message shared_ptr void send_message(std::shared_ptr<std::string> msg)\n void send_message(const std::shared_ptr<std::string> &msg)\n send_message void send_message(const std::shared_ptr<std::string> &msg)\n{\n if (msg == 0)\n return;\n msg send_message shared_ptr shared_ptr shared_ptr shared_ptr shared_ptr shared_ptr & std::string std::shared_ptr<std::string> previous_message = 0;\n previous_message.clear();\n shared_ptr"
},
{
"answer_id": 328926,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 4,
"selected": false,
"text": "shared_ptr const& shared_ptr boost::shared_ptr const& &"
},
{
"answer_id": 328992,
"author": "Drew Dormann",
"author_id": 16287,
"author_profile": "https://Stackoverflow.com/users/16287",
"pm_score": 1,
"selected": false,
"text": "Class::take_copy_of_sp(&sp)"
},
{
"answer_id": 2372009,
"author": "Kit10",
"author_id": 284573,
"author_profile": "https://Stackoverflow.com/users/284573",
"pm_score": 1,
"selected": false,
"text": "void FooTakesReference( boost::shared_ptr< int > & ptr )\n{\n ptr.reset(); // We reset, and so does sharedA, memory is deleted.\n}\n\nvoid FooTakesValue( boost::shared_ptr< int > ptr )\n{\n ptr.reset(); // Our temporary is reset, however sharedB hasn't.\n}\n\nvoid main()\n{\n boost::shared_ptr< int > sharedA( new int( 13 ) );\n boost::shared_ptr< int > sharedB( new int( 14 ) );\n\n FooTakesReference( sharedA );\n\n FooTakesValue( sharedB );\n}\n"
},
{
"answer_id": 4299887,
"author": "Sandy",
"author_id": 523293,
"author_profile": "https://Stackoverflow.com/users/523293",
"pm_score": 2,
"selected": false,
"text": "Class::only_work_with_sp( foo &sp ) //Again, no copy here \n{ \n ... \n sp.do_something(); \n ... \n}\n sp.do_something() sp delete this"
},
{
"answer_id": 17803841,
"author": "Dylan Chen",
"author_id": 1503248,
"author_profile": "https://Stackoverflow.com/users/1503248",
"pm_score": 0,
"selected": false,
"text": "struct A {\n shared_ptr<Message> msg;\n shared_ptr<Message> * ptr_msg;\n}\n void set(shared_ptr<Message> msg) {\n this->msg = msg; /// create a new shared_ptr, reference count will be added;\n} /// out of method, new created shared_ptr will be deleted, of course, reference count also be reduced;\n void set(shared_ptr<Message>& msg) {\n this->msg = msg; /// reference count will be added, because reference is just an alias.\n }\n void set(shared_ptr<Message>* msg) {\n this->ptr_msg = msg; /// reference count will not be added;\n}\n"
},
{
"answer_id": 26049446,
"author": "Malvineous",
"author_id": 308237,
"author_profile": "https://Stackoverflow.com/users/308237",
"pm_score": 2,
"selected": false,
"text": "test() #include <boost/shared_ptr.hpp>\n\nclass Base { };\nclass Derived: public Base { };\n\n// ONLY instances of Base can be passed by reference. If you have a shared_ptr\n// to a derived type, you have to cast it manually. If you remove the reference\n// and pass the shared_ptr by value, then the cast is implicit so you don't have\n// to worry about it.\nvoid test(boost::shared_ptr<Base>& b)\n{\n return;\n}\n\nint main(void)\n{\n boost::shared_ptr<Derived> d(new Derived);\n test(d);\n\n // If you want the above call to work with references, you will have to manually cast\n // pointers like this, EVERY time you call the function. Since you are creating a new\n // shared pointer, you lose the benefit of passing by reference.\n boost::shared_ptr<Base> b = boost::dynamic_pointer_cast<Base>(d);\n test(b);\n\n return 0;\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41789/"
] |
327,576 | <p>How do you plot bar charts in gnuplot with text labels?</p>
| [
{
"answer_id": 11551808,
"author": "Brad",
"author_id": 5464,
"author_profile": "https://Stackoverflow.com/users/5464",
"pm_score": 7,
"selected": false,
"text": "set boxwidth 0.5\nset style fill solid\nplot \"data.dat\" using 1:3:xtic(2) with boxes\n 0 label 100\n1 label2 450\n2 \"bar label\" 75\n set style line 1 lc rgb \"red\"\nset style line 2 lc rgb \"blue\"\n\nset style fill solid\nset boxwidth 0.5\n\nplot \"data.dat\" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \\\n \"data.dat\" every ::1::2 using 1:3:xtic(2) with boxes ls 2\n 0 5\n0.5 6\n\n\n1.5 3\n2 7\n\n\n3 8\n3.5 1\n set xtics (\"label\" 0.25, \"label2\" 1.75, \"bar label\" 3.25,)\n\nset boxwidth 0.5\nset style fill solid\n\nplot 'data.dat' every 2 using 1:2 with boxes ls 1,\\\n 'data.dat' every 2::1 using 1:2 with boxes ls 2\n plot 'data.dat' using 1:2:0 with boxes lc variable\n mycolor(x) = ((x*11244898) + 2851770)\nplot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable\n"
},
{
"answer_id": 36488276,
"author": "Marco Rosas",
"author_id": 2491898,
"author_profile": "https://Stackoverflow.com/users/2491898",
"pm_score": 4,
"selected": false,
"text": "set term png\nset output \"graph.png\"\nset boxwidth 0.5\nset style fill solid\nplot \"data.dat\" using 1:3:xtic(2) with boxes\n set term png set output \"graph.png\" plot \"data.dat\" using 1:3:xtic(2) with boxes\n \"data.dat\" 1:3 xtic() xtic(2) 0 label 100\n1 label2 450\n2 \"bar label\" 75\n gnuplot commands.txt"
},
{
"answer_id": 54370250,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "set style data histograms\n set style fill solid\n set boxwidth 0.5\n plot \"file1.dat\" using 5 title \"Total1\" lt rgb \"#406090\",\\\n \"file2.dat\" using 5 title \"Total2\" lt rgb \"#40FF00\"\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40849/"
] |
327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| [
{
"answer_id": 327601,
"author": "Gonzalo Quero",
"author_id": 40996,
"author_profile": "https://Stackoverflow.com/users/40996",
"pm_score": 2,
"selected": false,
"text": "n = chosenOption()\nif(n == 0):\n doSomething()\nelif(n == 1):\n doAnyOtherThing()\nelse:\n doDefaultThing()\n"
},
{
"answer_id": 327612,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 3,
"selected": false,
"text": "actions = {1: doSomething, 2: doSomethingElse}\nactions.get(n, doDefaultThing)()\n"
},
{
"answer_id": 327741,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 5,
"selected": true,
"text": "def action1():\n pass # put a function here\n\ndef action2():\n pass # blah blah\n\ndef action3():\n pass # and so on\n\ndef no_such_action():\n pass # print a message indicating there's no such action\n\ndef main():\n actions = {\"foo\": action1, \"bar\": action2, \"baz\": action3}\n while True:\n print_menu()\n selection = raw_input(\"Your selection: \")\n if \"quit\" == selection:\n return\n toDo = actions.get(selection, no_such_action)\n toDo()\n\nif __name__ == \"__main__\":\n main()\n cmd"
},
{
"answer_id": 9634208,
"author": "Gerry",
"author_id": 109561,
"author_profile": "https://Stackoverflow.com/users/109561",
"pm_score": 0,
"selected": false,
"text": "import menu\n\nmessage = \"Your question goes here\"\noptions = {\n 'f': ['[F]irst Option Name', 'First value'],\n 's': ['[S]econd Option Name', 'Second value'],\n 't': ['[T]hird Option Name', 'Third value']\n}\n\nselection = menu.getSelection(message, options)\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41795/"
] |
327,609 | <p>I have a working linker script. I want to add another data section whose contents is pulled directly from a file (ld shouldn't parse it and extract the sections and so on). How can I do that?</p>
<pre><code>OUTPUT_FORMAT("elf32-i386")
ENTRY(start)
SECTIONS
{
.text 0x100000 : {
*(.multiboot)
*(.text)
*(.code)
*(.rodata*)
}
.data : {
*(.data)
}
.bss : {
*(.bss)
}
kernel_end = .;
roottask_start = .;
.data : {
HERE I WANT TO INCLUDE THE ENTIRE CONTENTS OF ANOTHER (BINARY) FILE
}
roottask_end = .;
}
</code></pre>
| [
{
"answer_id": 328137,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 5,
"selected": false,
"text": "objcopy objcopy _binary_objfile_start _binary_objfile_end _binary_objfile_size --rename-section"
},
{
"answer_id": 8517643,
"author": "aimxhaisse",
"author_id": 1099473,
"author_profile": "https://Stackoverflow.com/users/1099473",
"pm_score": 3,
"selected": false,
"text": "BYTE INCLUDE hexdump cat ramelfs | hexdump -v -e '\"BYTE(0x\" 1/1 \"%02X\" \")\\n\"' > ramelfs.ld\n SECTIONS {\n .text : {\n\n /* ... */\n\n kramelfs = .;\n INCLUDE \"ramelfs.ld\" ;\n kramelfs_end = .;\n\n /* ... */\n }\n}\n"
},
{
"answer_id": 18467409,
"author": "lmctl",
"author_id": 2712593,
"author_profile": "https://Stackoverflow.com/users/2712593",
"pm_score": 4,
"selected": false,
"text": ".section .rawdata\n.incbin \"blob1.raw\"\n .data : {\n\n *(.rawdata*)\n\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434760/"
] |
327,617 | <p>I'm trying to scrape a price from a web page using PHP and Regexes. The price will be in the format £123.12 or $123.12 (i.e., pounds or dollars).</p>
<p>I'm loading up the contents using libcurl. The output of which is then going into <code>preg_match_all</code>. So it looks a bit like this:</p>
<pre><code>$contents = curl_exec($curl);
preg_match_all('/(?:\$|£)[0-9]+(?:\.[0-9]{2})?/', $contents, $matches);
</code></pre>
<p>So far so simple. The problem is, PHP isn't matching anything at all - even when there are prices on the page. I've narrowed it down to there being a problem with the '£' character - PHP doesn't seem to like it.</p>
<p>I think this might be a charset issue. But whatever I do, I can't seem to get PHP to match it! Anyone have any ideas?</p>
<p>(Edit: I should note if I try using the <a href="http://www.spaweditor.com/scripts/regex/index.php" rel="nofollow noreferrer">Regex Test Tool</a> using the same regex and page content, it works fine)</p>
| [
{
"answer_id": 327621,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": true,
"text": "preg_match_all('/(\\$|\\£)[0-9]+(\\.[0-9]{2})/', $contents, $matches);\n"
},
{
"answer_id": 327624,
"author": "Eimantas",
"author_id": 41761,
"author_profile": "https://Stackoverflow.com/users/41761",
"pm_score": 0,
"selected": false,
"text": "'/(?:\\$|£)\\d+(?:\\.\\d{2})?/'"
},
{
"answer_id": 327627,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 0,
"selected": false,
"text": "'#(?:\\$|\\£|\\€)(\\d+(?:\\.\\d+)?)#'\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,642 | <p>Is it possible to pump monochrome (graphical data with 1 bit image depth) texture into OpenGL?</p>
<p>I'm currently using this:</p>
<pre><code>glTexImage2D( GL_TEXTURE_2D, 0, 1, game->width, game->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, game->culture[game->phase] );
</code></pre>
<p>I'm pumping it with square array of 8 bit unsigned integers in GL_LUMINANCE mode (one 8 bit channel represents brightness of all 3 channels and full alpha), but it is IMO vastly ineffective, because the onlu values in the array are 0x00 and 0xFF.</p>
<p>Can I (and how) use simple one-bit per pixel array of booleans instead somehow? The excessive array size slows down any other operations on the array :(</p>
| [
{
"answer_id": 15706596,
"author": "Zac",
"author_id": 971443,
"author_profile": "https://Stackoverflow.com/users/971443",
"pm_score": 4,
"selected": false,
"text": "static GLubyte smiley[] = /* 16x16 smiley face */\n{\n 0x03, 0xc0, /* **** */\n 0x0f, 0xf0, /* ******** */\n 0x1e, 0x78, /* **** **** */\n 0x39, 0x9c, /* *** ** *** */\n 0x77, 0xee, /* *** ****** *** */\n 0x6f, 0xf6, /* ** ******** ** */\n 0xff, 0xff, /* **************** */\n 0xff, 0xff, /* **************** */\n 0xff, 0xff, /* **************** */\n 0xff, 0xff, /* **************** */\n 0x73, 0xce, /* *** **** *** */\n 0x73, 0xce, /* *** **** *** */\n 0x3f, 0xfc, /* ************ */\n 0x1f, 0xf8, /* ********** */\n 0x0f, 0xf0, /* ******** */\n 0x03, 0xc0 /* **** */\n};\n\nfloat index[] = {0.0, 1.0};\n\nglPixelStorei(GL_UNPACK_ALIGNMENT,1);\n\nglPixelMapfv(GL_PIXEL_MAP_I_TO_R, 2, index);\nglPixelMapfv(GL_PIXEL_MAP_I_TO_G, 2, index);\nglPixelMapfv(GL_PIXEL_MAP_I_TO_B, 2, index);\nglPixelMapfv(GL_PIXEL_MAP_I_TO_A, 2, index);\n\nglTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,16,16,0,GL_COLOR_INDEX,GL_BITMAP,smiley);\n\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38256/"
] |
327,643 | <p>I see the "More Action" drop-down box in gmail inbox page.
It has levels and some disabled item in the list.</p>
<p>How to do that in HTML+CSS?</p>
<p>Thank you</p>
| [
{
"answer_id": 327703,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 3,
"selected": true,
"text": "<select> <select name=\"foo\">\n <optgroup label=\"Odds\">\n <option value=\"1\">1</option>\n <option value=\"3\">3</option>\n <option value=\"5\">5</option>\n </optgroup>\n <optgroup label=\"Evens\">\n <option value=\"2\">2</option>\n <option value=\"4\">4</option>\n <option value=\"6\" disabled=\"disabled\">6</option>\n </optgroup>\n</select>\n"
},
{
"answer_id": 5614556,
"author": "Fernando",
"author_id": 522555,
"author_profile": "https://Stackoverflow.com/users/522555",
"pm_score": 2,
"selected": false,
"text": ".shortasc { background: url(\"/css/asc.gif\") no-repeat 50% 50%;cursor:pointer;}\n.shortdesc { background: url(\"/css/desc.gif\") no-repeat 50% 50%;cursor:pointer;}\n.hide{ display:none;}\n.toggle-menu .title {\ntext-align:left;\n}\n\n.toggle-menu div.more{\n position: absolute;\n border:#999999 1px solid;\n background-color:#FFFFFF;\n\n}\n.toggle-menu div.more ul{margin:0; padding:2px; text-align:left;}\n.toggle-menu div.more ul li{list-style:none; padding:2px; border:#CCCCCC 1px solid;}\n <span class=\"toggle-menu\">\n<span class=\"title\" onclick=\"$(this).win('togglewin');\">titulo del menu</span><span class=\"orden shortasc\"> </span>\n<div class=\"more hide\">\n<ul>\n<li>Enlace 1</li>\n<li>Enlace 2</li>\n<li>and so on</li>\n</ul>\n</div>\n</span>\n (function($) {\nvar methods={\n//... your functions\ntogglewin:function(){\n var p = $(this).position();\n var parent = (this).closest('.toggle-menu');\n if(parent.find('.more').is(':visible')){\n parent.find('.orden').removeClass('shortdesc').addClass('shortasc'); \n parent.find('.more').slideUp();\n }else{\n parent.find('.orden').removeClass('shortasc').addClass('shortdesc');\n parent.find('.more').slideDown().offset( { top:p.top+12,left:p.left } );\n }\n return this;\n}\n};\n\n$.fn.win = function(method) { \n if ( methods[method] ) {\n return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));\n } else if ( typeof method === 'object' || ! method ) {\n return methods.init.apply( this, arguments );\n } else {\n $.error( 'Method ' + method + ' inexistente en jQuery.win' );\n } \n}\n\n})(jQuery);\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41803/"
] |
327,645 | <p>I am migrating a 1.1 winforms app to 2.0. what are the main things i should immediately change because of generics. Here what i have so far:</p>
<ol>
<li>Replace all hashtables with generic dictionaries</li>
<li>Replace all arraylists with List<></li>
<li>Replace all CollectionBase derive classes with : List<></li>
</ol>
<p>Any others that should be done immediately?</p>
<p>thks,
ak</p>
| [
{
"answer_id": 327646,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "IEnumerable IEnumerable<T> import System.Collections System.Collections.Generic object IComparable"
},
{
"answer_id": 327720,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": false,
"text": "Hashtable ht = new Hashtable();\nht.Add(1, \"one\");\nstring s1 = ht[1; // s1=\"one\"\nstring s2 = ht[2]; // s2=null\n\nvar dic = new Dictionary<int, string>();\ndic.Add(1, \"one\");\nstring s1 = dic[1]; // s1=\"one\"\nstring s2 = dic[2]; // throws KeyNotFoundException\n string s = null;\nif (dic.TryGetValue(k, out s))\n{\n // if we're here, k was found in the dictionary\n}\n"
},
{
"answer_id": 328450,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 0,
"selected": false,
"text": "List<T> CollectionBase Collection<T>"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
327,654 | <p>Hashtables have a syncroot property but generic dictionaries don't. If I have code that does this:</p>
<pre><code>lock (hashtable.Syncroot)
{
....
}
</code></pre>
<p>How do I replicate this if I am removing the hashtable and changing to generic dictionaries?</p>
| [
{
"answer_id": 327667,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 3,
"selected": false,
"text": "var dictionary = new Dictionary<int, string>();\n\nlock(((ICollection) dictionary).SyncRoot)\n{\n // ...\n}\n"
},
{
"answer_id": 327738,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "// used as you would have used SyncRoot before\nobject _syncLock = new object();\nDictionary<string, int> numberMapper = new Dictionary<string, int>();\n\n// in some method...\nlock (_syncLock)\n{\n // use the dictionary here.\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
327,656 | <p>I am trying to specify an alternative jre (my default is 1.6 and i need to run with jdk 1.4.2) in Eclipse, for an application that i shall launch from eclipse. I am not sure if I am doing the right thing in the following code:</p>
<pre><code>Path jreContainerPath = new Path("/usr/lib/jvm/j2sdk1.4.2_18/");
IVMInstall jre = JavaRuntime.getVMInstall(jreContainerPath);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants. ATTR_JRE_CONTAINER_PATH, jre.getName());
</code></pre>
<p>However, the IVMInstall jre is null. I think I am not specifying the container path right, but I am not sure. And I must do it in the program. I would gladly appreciate any help on this. Thanks in advance. </p>
| [
{
"answer_id": 328296,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "getVMInstall JREContainerInitializer .resolveVM(jreContainerPath) getExecutionEnvironmentId() getVMName() JREContainerInitializer"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23486/"
] |
327,658 | <p>I'm trying to write a VB.Net program that saves 1-2 million 5-field records (plus an indexed ID) to an MSAccess table every day. The saving process currently takes 13-20 hours, which obviously can't be right.</p>
<p>Its a flat table with minimal indexing, currently only 156MB. Except for one double field, the fields are small strings, dates, or longs. The disk itself is a 15,000 SATA which is used only for this file. The computer and the program are not doing anything else during the save routine. The save routine is a simple FOR-NEXT loop that issues a short and simple INSERT statement for each record in the dataset.</p>
<p>Anyone got an ideas on what I need to change to get this to work better?</p>
| [
{
"answer_id": 327773,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "Set cn = CreateObject(\"ADODB.Connection\")\nstrFile=\"C:\\ltd.mdb\"\nstrCon=\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" _\n& strFile & \";\" \n\ncn.Open strCon\n\nstrSQL=\"INSERT INTO tableX ( Name1,Name2 ) \" _\n& \"SELECT Name1,Name2 \" _\n& \"FROM [ltd.txt] IN '' [Text;Database=c:\\docs\\;HDR=YES;]\"\n\ncn.Execute strSQL\n"
},
{
"answer_id": 327783,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Data.OleDb;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n String jetConnection = \"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\\\jetsample.mdb;\";\n\n ADOX.CatalogClass cat = new ADOX.CatalogClass();\n cat.Create(jetConnection);\n\n using(OleDbConnection conn = new OleDbConnection(jetConnection))\n {\n conn.Open();\n using(OleDbCommand cmd = new OleDbCommand(\"CREATE TABLE test ([ID] INTEGER, [TestDouble] DOUBLE, [TestText] TEXT, [TestDate] DATE, [TestInt] INTEGER)\",conn))\n {\n cmd.CommandType = CommandType.Text;\n cmd.ExecuteNonQuery();\n }\n\n using (OleDbCommand cmd = new OleDbCommand(\"INSERT INTO [Test] VALUES (@id, @testDouble, @testText, @testDate, @testInt)\", conn))\n {\n OleDbParameter id = cmd.Parameters.Add(\"@id\", OleDbType.Integer);\n OleDbParameter testDouble = cmd.Parameters.Add(\"@testDouble\", OleDbType.Double);\n OleDbParameter testText = cmd.Parameters.Add(\"@testText\", OleDbType.VarWChar);\n OleDbParameter testDate = cmd.Parameters.Add(\"@testDate\", OleDbType.Date);\n OleDbParameter testInt = cmd.Parameters.Add(\"@testInt\", OleDbType.Integer);\n\n DateTime start = DateTime.Now;\n for (int index = 1; index <= 2000000; index++)\n {\n if (index % 1000 == 0)\n {\n System.Diagnostics.Debug.WriteLine(((TimeSpan)(DateTime.Now - start)).Milliseconds);\n start = DateTime.Now;\n }\n\n id.Value = index;\n testDouble.Value = index;\n testText.Value = String.Format(\"{0} DBL\", index);\n testDate.Value = DateTime.Now.AddMilliseconds(index);\n testInt.Value = index;\n\n cmd.ExecuteNonQuery();\n }\n }\n }\n\n }\n }\n}\n"
},
{
"answer_id": 327816,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " Me.connSPY.ConnectionString = \"Jet OLEDB:Global Partial Bulk Ops=2;\" & _\n \"Jet OLEDB:Registry Path=;Jet OLEDB:\" & _\n \"Database Locking Mode=0;\" & _\n \"Data Source=\"\"E:\\SPIRE.mdb\"\";\" & _\n \"Mode=Share Deny None;\" & _\n \"Jet OLEDB:Engine Type=5;\" & _\n \"Provider=\"\"Microsoft.Jet.OLEDB.4.0\"\";\" & _\n \"Jet OLEDB:System database=;\" & _\n \"Jet OLEDB:SFP=False\" & _\n \";persist security info=False;\" & _\n \"Extended Properties=;\" & _\n \"Jet OLEDB:Compact Without Replica Repair=False;\" & _\n \"Jet OLEDB:Encrypt Database=False;\" & _\n \"Jet OLEDB:Create System Database=False;\" & _\n \"Jet OLEDB:Don't Copy Locale on Compact=False;\" & _\n \"User ID=Admin;\" & _\n \"Jet OLEDB:Global Bulk Transactions=1\"\n"
},
{
"answer_id": 328183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO Ticks (Symbol, TickDate, TickTime, TickPRice, TickVolume) \nVALUES ('SPY', #11/28/2008#, #09:30:00#, 88.63, 200);\n\nINSERT INTO Ticks (Symbol, TickDate, TickTime, TickPRice, TickVolume) \nVALUES ('SPY', #11/28/2008#, #09:30:00#, 88.62, 400);\n\nINSERT INTO Ticks (Symbol, TickDate, TickTime, TickPRice, TickVolume) \nVALUES ('SPY', #11/28/2008#, #09:30:00#, 88.62, 100);\n\nINSERT INTO Ticks (Symbol, TickDate, TickTime, TickPRice, TickVolume) \nVALUES ('SPY', #11/28/2008#, #09:30:00#, 88.62, 300);\n\nINSERT INTO Ticks (Symbol, TickDate, TickTime, TickPRice, TickVolume) \nVALUES ('SPY', #11/28/2008#, #09:30:00#, 88.62, 127);\n"
},
{
"answer_id": 8828565,
"author": "Phase9",
"author_id": 662931,
"author_profile": "https://Stackoverflow.com/users/662931",
"pm_score": 0,
"selected": false,
"text": "private void PopulateMDB(string ExportPath, int iID)\n{\n\n string cnnStr = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + ExportPath;\n OleDbConnection oConn = new OleDbConnection(cnnStr);\n string q = @\"INSERT \n INTO PensionData ([ID]\n ,[Recipient Name]\n ,[Gross Amt]\n ,[Retirement Date]\n ,[Plan])\n\n select id as [ID]\n ,name as [Recipient Name]\n ,gross_amt as [Gross Amt]\n ,eff_dt as [Retirement Date]\n ,pln as [Plan]\n FROM [ODBC;Driver=SQL Server;SERVER=euddbms.d;DATABASE=DBName;UID=;PWD=;].tableName\n WHERE id = \" + iID;\n\n oConn.Open();\n\n try\n {\n OleDbCommand oCmd = new OleDbCommand(q, oConn);\n\n oCmd.ExecuteNonQuery();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n finally\n {\n oConn.Close();\n oConn = null;\n }\n\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,664 | <p>Tried to map it from Preferences -> Settings -> Keyboard, but the "key" combo box has only "forward delete" but no "delete". My keyboard on the other hand has only "delete" and no "forward delete"!</p>
<p>Is there some other way to do it except from the preferences?</p>
| [
{
"answer_id": 327676,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 10,
"selected": true,
"text": "Terminal Preferences Profiles Keyboard Use option key as meta key"
},
{
"answer_id": 30753231,
"author": "Stephane Gasparini",
"author_id": 4994224,
"author_profile": "https://Stackoverflow.com/users/4994224",
"pm_score": 5,
"selected": false,
"text": "⌃W / _ ^W rm /dira/dirb/file1\n rm /dira/dirb/\n rm\n"
},
{
"answer_id": 58966776,
"author": "Curtis M",
"author_id": 9424474,
"author_profile": "https://Stackoverflow.com/users/9424474",
"pm_score": 5,
"selected": false,
"text": "!! !blah !blah:p !$ !$:p !* _find somefile.txt / !* _find somefile.txt !*:p !*"
},
{
"answer_id": 59513080,
"author": "Anthony Artemiev",
"author_id": 1950056,
"author_profile": "https://Stackoverflow.com/users/1950056",
"pm_score": 2,
"selected": false,
"text": "Natural Text Editing alt + delete fn + alt + delete"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] |
327,673 | <p>I need to convert several million dates stored as wide strings into boost dates</p>
<p>The following code works. However, it generates a horrible compiler warning and does not seem efficient.</p>
<p>Is there a better way?</p>
<pre><code>#include "boost/date_time/gregorian/gregorian.hpp"
using namespace boost::gregorian;
#include <string>
using namespace std;
wstring ws( L"2008/01/01" );
string temp(ws.length(), '\0');
copy(ws.begin(), ws.end(), temp.begin());
date d1( from_simple_string( temp ) );
cout << d1;
</code></pre>
<hr>
<p>The better way turns out to be to use the standard C++ library <em>locale</em>, which is a collection of <em>facets</em>. A facet is a service which allows the stream operators to handle a particular choice for date or time representation or just about anything else. All the choices about diferent things, each handled by its own facet, are gathered together in a locale.</p>
<p>This solution was pointed out to me by <a href="https://stackoverflow.com/users/34509/litb">litb</a> who gave me enough help to use facets in my production code, making it terser and faster. Thanks.</p>
<p>There is an <a href="http://www.cantrip.org/locale.html" rel="nofollow noreferrer">excellent tutorial</a> on locales and facets by Nathan Myers who designed facets. He has a light style which makes his tutorial easy to read, though this is advanced stuff and your brain may hurt after the first read through - mine did. I suggest you go there now. For anyone who just wants the practicalities of converting wide character strings to boost dates, the rest of this post describes the minimum necessary to make it work.</p>
<hr>
<p>litb first offered the following simple solution that removes the compiler warning. ( The solution was edited before I got around to accepting it. ) This looks like it does the same thing, converting wide characters one by one, but it avoids mucking around with temp strings and therefore is much clearer, I think. I really like that the compiler warning is gone.</p>
<pre><code>#include "boost/date_time/gregorian/gregorian.hpp"
using namespace boost::gregorian;
#include <string>
using namespace std;
wstring ws( L"2008/01/01" );
date d1( from_simple_string( string( ws.begin(), ws.end() ) );
cout << d1;
</code></pre>
<hr>
<p>litb went on to suggest using "facets", which I had never heard of before. They seem to do the job, producing incredibly terse code inside the loop, at the cost of a prologue where the locale is set up.</p>
<pre><code>wstring ws( L"2008/01/01" );
// construct a locale to collect all the particulars of the 'greek' style
locale greek_locale;
// construct a facet to handle greek dates - wide characters in 2008/Dec/31 format
wdate_input_facet greek_date_facet(L"%Y/%m/%d");
// add facet to locale
greek_locale = locale( greek_locale, &greek_date_facet );
// construct stringstream to use greek locale
std::wstringstream greek_ss;
greek_ss.imbue( greek_locale );
date d2;
greek_ss << ws;
greek_ss >> d2;
cout << d2;
</code></pre>
<p>This, it turns out, is also more efficient:</p>
<pre><code>clock_t start, finish;
double duration;
start = clock();
for( int k = 0; k < 100000; k++ ) {
string temp(ws.length(), '\0');
copy(ws.begin(), ws.end(), temp.begin());
date d1( from_simple_string( temp ) );
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "1st method: " << duration << endl;
start = clock();
for( int k = 0; k < 100000; k++ ) {
date d1( from_simple_string( string( ws.begin(), ws.end() ) ) );
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "2nd method: " << duration << endl;
start = clock();
for( int k = 0; k < 100000; k++ ) {
greek_ss << ws;
greek_ss >> d2;
ss.clear();
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "3rd method: " << duration << endl;
</code></pre>
<p>Produces the following output:</p>
<pre>
1st method: 2.453
2nd method: 2.422
3rd method: 1.968
</pre>
<p>OK, this is now in the production code and passing regression tests. It looks like this:</p>
<pre><code> // .. construct greek locale and stringstream
// ... loop over input extracting date strings
// convert range to boost dates
date d1;
greek_ss<< sd1; greek_ss >> d1;
if( greek_ss.fail() ) {
// input is garbled
wcout << L"do not understand " << sl << endl;
exit(1);
}
greek_ss.clear();
// finish processing and end loop
</code></pre>
<p>I have one final question about this. Adding the facet to the locale seems to require two invocations of the locale copy constructor</p>
<pre><code> // add facet to locale
greek_locale = locale( greek_locale, &greek_date_facet );
</code></pre>
<p>Why is there not an add( facet* ) method? ( _Addfac() is complex, undocumented and deprecated )</p>
| [
{
"answer_id": 327680,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "date_time #include <boost/date_time/gregorian/gregorian.hpp>\n#include <iostream>\n#include <sstream>\n#include <locale>\n\nint main() {\n using namespace boost::gregorian;\n\n std::wstringstream ss;\n wdate_input_facet * fac = new wdate_input_facet(L\"%Y-%m-%d\");\n ss.imbue(std::locale(std::locale::classic(), fac));\n\n date d;\n ss << L\"2004-01-01 2005-01-01 2006-06-06\";\n while(ss >> d) {\n std::cout << d << std::endl;\n }\n}\n boost::date_time::date_input_facet std::locale::facet std::locale std::has_facet<Facet>(some_locale) std::use_facet<Facet>(some_locale).some_member... operator>> // assume src is a stream having the wdate_input_facet in its locale. \n// wdate_input_facet is a boost::date_time::date_input_facet<date,wchar_t> typedef.\n\ndate d;\n\n// iterate over characters of src\nstd::istreambuf_iterator<wchar_t> b(src), e;\n\n// use the facet to parse the date\nstd::use_facet<wdate_input_facet>(src.getloc()).get(b, e, src, d);\n"
},
{
"answer_id": 327736,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 1,
"selected": false,
"text": "using boost::gregorian::date;\nusing boost::gregorian::from_stream;\n\nstd::wstring ws( L\"2008/01/01\" );\ndate d1(from_stream(ws.begin(), ws.end()));\nstd::cout << d1; // prints \"2008-Jan-01\"\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582/"
] |
327,678 | <p>Given the following code,</p>
<pre><code>Choices choices = new Choices();
choices.Add(new GrammarBuilder(new SemanticResultValue("product", "<product/>")));
GrammarBuilder builder = new GrammarBuilder();
builder.Append(new SemanticResultKey("options", choices.ToGrammarBuilder()));
Grammar grammar = new Grammar(builder) { Name = Constants.GrammarNameLanguage};
grammar.Priority = priority;
_recognition.LoadGrammar(grammar);
</code></pre>
<p>How can I add additional words to the loaded grammar? I know this can be achieved both in native code and using the SpeechLib interop, but I prefer to use the managed library.</p>
<p><strong>Update:</strong> What I want to achieve, is not having to load an entire grammar repeatedly because of individual changes. For small grammars I got good results by calling</p>
<pre><code>_recognition.RequestRecognizerUpdate()
</code></pre>
<p>and then doing the unload of the old grammar and loading of a rebuilt grammar in the event:</p>
<pre><code>void Recognition_RecognizerUpdateReached(object sender, RecognizerUpdateReachedEventArgs e)
</code></pre>
<p>For large grammars this becomes too expensive.</p>
| [
{
"answer_id": 327680,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "date_time #include <boost/date_time/gregorian/gregorian.hpp>\n#include <iostream>\n#include <sstream>\n#include <locale>\n\nint main() {\n using namespace boost::gregorian;\n\n std::wstringstream ss;\n wdate_input_facet * fac = new wdate_input_facet(L\"%Y-%m-%d\");\n ss.imbue(std::locale(std::locale::classic(), fac));\n\n date d;\n ss << L\"2004-01-01 2005-01-01 2006-06-06\";\n while(ss >> d) {\n std::cout << d << std::endl;\n }\n}\n boost::date_time::date_input_facet std::locale::facet std::locale std::has_facet<Facet>(some_locale) std::use_facet<Facet>(some_locale).some_member... operator>> // assume src is a stream having the wdate_input_facet in its locale. \n// wdate_input_facet is a boost::date_time::date_input_facet<date,wchar_t> typedef.\n\ndate d;\n\n// iterate over characters of src\nstd::istreambuf_iterator<wchar_t> b(src), e;\n\n// use the facet to parse the date\nstd::use_facet<wdate_input_facet>(src.getloc()).get(b, e, src, d);\n"
},
{
"answer_id": 327736,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 1,
"selected": false,
"text": "using boost::gregorian::date;\nusing boost::gregorian::from_stream;\n\nstd::wstring ws( L\"2008/01/01\" );\ndate d1(from_stream(ws.begin(), ws.end()));\nstd::cout << d1; // prints \"2008-Jan-01\"\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32498/"
] |
327,681 | <p>I am using jquery and the getJSON method and I am wondering if there is a way to display a message saying loading before it loads my content. i know with the jquery ajax calls there is the before submit callbacks where you can have something but the getJSON only has like three options.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 327695,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": true,
"text": ".ajax \n showLoadingAnimation(); \n $.getJSON( ..... function(){\n dontShowLoadingAnimation(); \n }); "
},
{
"answer_id": 327758,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": false,
"text": "<div id=\"loading\" style=\"display:none\">\n <img src=\"/images/ajax-loader.gif\" alt=\"Loader\" /> Loading...\n</div>\n<script type=\"text/javascript\">\n $().ready(function() {\n $(\"#loading\").bind(\"ajaxSend\", function() {\n $(this).show();\n }).bind(\"ajaxComplete\", function() {\n $(this).hide();\n });\n });\n</script>\n #loading\n {\n position:fixed; \n _position:absolute;\n top: 0;\n left:47%; \n padding:2px 5px;\n z-index: 5000;\n background-color:#CF4342;\n color:#fff;\n }\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,682 | <p>I am loading JSON data to my page and using <code>appendTo()</code> but I am trying to fade in my results, any ideas?</p>
<pre><code>$("#posts").fadeIn();
$(content).appendTo("#posts");
</code></pre>
<p>I saw that there is a difference between <code>append</code> and <code>appendTo</code>, on the documents.</p>
<p>I tried this as well:</p>
<pre><code>$("#posts").append(content).fadeIn();
</code></pre>
<p><strong><em>I got it, the above did the trick!</em></strong></p>
<p>But I get <code>"undefined"</code> as one of my JSON values.</p>
| [
{
"answer_id": 327694,
"author": "Kevin Gorski",
"author_id": 35806,
"author_profile": "https://Stackoverflow.com/users/35806",
"pm_score": 8,
"selected": true,
"text": "// Create the DOM elements\n$(content)\n// Sets the style of the elements to \"display:none\"\n .hide()\n// Appends the hidden elements to the \"posts\" element\n .appendTo('#posts')\n// Fades the new content into view\n .fadeIn();\n"
},
{
"answer_id": 327699,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "\n commmand(); \n animation(); \n command(); \n\nThis is because the animation uses set timeout and other similar magic to do its job and settimeout is non-blocking.\n\nThis is why we have callback methods on animations to run when the animation is done ( to avoid changing something which doesn't exist yet ) \n\n command(); \n animation( ... function(){ \n command(); \n });\n"
},
{
"answer_id": 327721,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 3,
"selected": false,
"text": "<div id=\"posts\">\n <span id=\"post1\">Something here</span>\n</div>\n var counter=0;\n\n$.get(\"http://www.something/dir\",\n function(data){\n $('#posts').append('<span style=\"display:none\" id=\"post' + counter + \">\" + data + \"</span>\" ) ;\n $('#post' + counter).fadeIn();\n counter += 1;\n });\n"
},
{
"answer_id": 2299892,
"author": "Firas",
"author_id": 181385,
"author_profile": "https://Stackoverflow.com/users/181385",
"pm_score": 2,
"selected": false,
"text": "$('#content').prepend('<p>Hello!</p>');\n$('#content').children(':first').fadeOut().fadeIn();\n"
},
{
"answer_id": 6723957,
"author": "Michael Martin",
"author_id": 795115,
"author_profile": "https://Stackoverflow.com/users/795115",
"pm_score": 2,
"selected": false,
"text": ".new {display:none} \n $('#content').append('<p class='new'>Hello!</p>');\n$('#content').children('.new').fadeIn();\n$('#content').children.removeClass('new');\n$('#content').children('.new').hide();\n"
},
{
"answer_id": 8619527,
"author": "Sam",
"author_id": 1113854,
"author_profile": "https://Stackoverflow.com/users/1113854",
"pm_score": 1,
"selected": false,
"text": "jNode = $(\"<div>first</div><div>second</div>\");\njNode.hide();\n$('#content').append(jNode);\njNode.fadeIn();\n"
},
{
"answer_id": 11745011,
"author": "slboat",
"author_id": 1481503,
"author_profile": "https://Stackoverflow.com/users/1481503",
"pm_score": 0,
"selected": false,
"text": "$(\"dt\").append(tvlst.ddhtml);\n$(\"dd:last\").fadeIn(700);\n"
},
{
"answer_id": 12768178,
"author": "Ball_cs",
"author_id": 1726564,
"author_profile": "https://Stackoverflow.com/users/1726564",
"pm_score": 2,
"selected": false,
"text": "$(output_string.html).fadeIn().appendTo(\"#list\");\n"
},
{
"answer_id": 49664173,
"author": "Emanuel Silva",
"author_id": 4551834,
"author_profile": "https://Stackoverflow.com/users/4551834",
"pm_score": 0,
"selected": false,
"text": "$(\"div\").append(\"content-to-add\").hide().fadeIn();\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,685 | <p>I would like to inject binary data into an object in JavaScript. Is there a way to do this? </p>
<p>i.e.</p>
<pre><code>var binObj = new BinaryObject('101010100101011');
</code></pre>
<p>Something to that effect. Any help would be great.</p>
| [
{
"answer_id": 327688,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": false,
"text": "var bin = parseInt('10101010', 2);"
},
{
"answer_id": 4411163,
"author": "Frithjof",
"author_id": 538104,
"author_profile": "https://Stackoverflow.com/users/538104",
"pm_score": 2,
"selected": false,
"text": "pow squareroot AlertFormatedBin();\nfunction AlertFormatedBin()\n{\n var vals = decToBinArr(31,8);\n var i;\n\n var s = \"\";\n var mod = vals.length % 4;\n for(i= 0; i <mod;i++)\n {\n s+=vals[i];\n }\n if(i>0)\n s+=\" \";\n var j = i;\n for(i;i<vals.length;i++)\n {\n s+=vals[i];\n if(i-j != 0 && (i+1-j)%4 == 0)\n {\n s+=\" \";\n }\n }\n alert(s);\n}\n\nfunction decToBinArr(dec, minSize)\n{\n var mod = dec%2;\n var r = new Array();\n if(dec > 1)\n {\n dec-=mod;\n var bd = squareRootRoundedDown(dec);\n if(minSize && minSize-1 > bd)\n bd = minSize-1;\n else\n var i;\n for(i = bd; i>0;i--)\n {\n var nxt = pow(2,i);\n if(dec >= nxt)\n {\n r[i] = 1;\n dec-=nxt;\n }\n else\n {\n r[i] = 0;\n }\n }\n }\n r[0]= mod;\n r.reverse();\n return r;\n}\n\nfunction squareRootRoundedDown(dec)\n{\n if(dec<2)\n return 0;\n var x = 2;\n var i;\n for(i= 1;true;i++)\n {\n if(x>=dec)\n {\n i = x == dec ? i : i-1;\n break;\n }\n x= x*2;\n }\n return i;\n}\n\nfunction pow(b,exp)\n{\n if(exp == 0)\n return 0;\n var i = 1;\n var r= b;\n for(i = 1; i < exp;i++)\n r=r*b;\n return r;\n}\n"
},
{
"answer_id": 4815486,
"author": "Vjeux",
"author_id": 232122,
"author_profile": "https://Stackoverflow.com/users/232122",
"pm_score": 4,
"selected": false,
"text": "xhr.overrideMimeType('text/plain; charset=x-user-defined');\n data.charCodeAt(pos) & 0xff;\n xhr.responseType = \"arraybuffer\";\n xhr.mozResponseArrayBuffer // Firefox\nxhr.response // Chrome\n"
},
{
"answer_id": 6027328,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 1,
"selected": false,
"text": "unescape(\"%uFFFF%uFFFF%uFFFF\");\n"
},
{
"answer_id": 58478643,
"author": "scoutchorton",
"author_id": 5055162,
"author_profile": "https://Stackoverflow.com/users/5055162",
"pm_score": 1,
"selected": false,
"text": "0b 1010 var binNum = 0b1010 //Stores as an integer, which would be 10\n 0x var binNum = 0x1010 //Stores as an integer, which would be 4112\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,700 | <p>I'd like to create an application that would run on Google's appengine.</p>
<p>However, this application needs to be able to generate PDFs dynamically.</p>
<p>How could I do this?</p>
| [
{
"answer_id": 327747,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 6,
"selected": true,
"text": "reportlab sys.path"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
327,718 | <p>How to list physical disks in Windows?
In order to obtain a list of <code>"\\\\.\PhysicalDrive0"</code> available.</p>
| [
{
"answer_id": 327724,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": false,
"text": "wmic diskdrive list\n wmic diskdrive list brief \n system(\"wmic diskdrive list\");\n Get-WmiObject Win32_DiskDrive\n"
},
{
"answer_id": 350304,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 4,
"selected": false,
"text": "Device Name Size Type Partition Type\n------------------------------ --------- --------- --------------------\n\\\\.\\PhysicalDrive0 40.0 GB Fixed\n\\\\.\\PhysicalDrive1 80.0 GB Fixed\n\\Device\\Harddisk0\\Partition0 40.0 GB Fixed\n\\Device\\Harddisk0\\Partition1 40.0 GB Fixed NTFS\n\\Device\\Harddisk1\\Partition0 80.0 GB Fixed\n\\Device\\Harddisk1\\Partition1 80.0 GB Fixed NTFS\n\\\\.\\C: 80.0 GB Fixed NTFS\n\\\\.\\D: 2.1 GB Fixed FAT32\n\\\\.\\E: 40.0 GB Fixed NTFS\n"
},
{
"answer_id": 356676,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 1,
"selected": false,
"text": "function VolumeNameToDeviceName(const VolName: String): String;\nvar\n s: String;\n TargetPath: Array[0..MAX_PATH] of WideChar;\n bSucceeded: Boolean;\nbegin\n Result := ”;\n // VolumeName has a format like this: \\\\?\\Volume{c4ee0265-bada-11dd-9cd5-806e6f6e6963}\\\n // We need to strip this to Volume{c4ee0265-bada-11dd-9cd5-806e6f6e6963}\n s := Copy(VolName, 5, Length(VolName) - 5);\n\n bSucceeded := QueryDosDeviceW(PWideChar(WideString(s)), TargetPath, MAX_PATH) <> 0;\n if bSucceeded then\n begin\n Result := TargetPath;\n end\n else begin\n // raise exception\n end;\n\nend;\n"
},
{
"answer_id": 9339697,
"author": "unixman83",
"author_id": 504239,
"author_profile": "https://Stackoverflow.com/users/504239",
"pm_score": -1,
"selected": false,
"text": "CreateFile CreateFile(\"\\\\.\\C:\") INVALID_HANDLE_VALUE DeviceIoControl"
},
{
"answer_id": 10228046,
"author": "anni",
"author_id": 541864,
"author_profile": "https://Stackoverflow.com/users/541864",
"pm_score": 4,
"selected": false,
"text": "CreateFile() \\\\.\\Physicaldiskx GetLastError()"
},
{
"answer_id": 11683906,
"author": "Grodriguez",
"author_id": 450398,
"author_profile": "https://Stackoverflow.com/users/450398",
"pm_score": 6,
"selected": false,
"text": "GetLogicalDrives \"\\\\.\\X:\" DeviceIoControl dwIoControlCode IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS HANDLE hHandle;\nVOLUME_DISK_EXTENTS diskExtents;\nDWORD dwSize;\n[...]\n\niRes = DeviceIoControl(\n hHandle,\n IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,\n NULL,\n 0,\n (LPVOID) &diskExtents,\n (DWORD) sizeof(diskExtents),\n (LPDWORD) &dwSize,\n NULL);\n VOLUME_DISK_EXTENTS diskExtents.Extents[0].DiskNumber"
},
{
"answer_id": 17224469,
"author": "user2506992",
"author_id": 2506992,
"author_profile": "https://Stackoverflow.com/users/2506992",
"pm_score": 3,
"selected": false,
"text": "wmic volume list brief\n"
},
{
"answer_id": 18183115,
"author": "arun",
"author_id": 1852355,
"author_profile": "https://Stackoverflow.com/users/1852355",
"pm_score": 5,
"selected": false,
"text": "GUID_DEVINTERFACE_DISK IOCTL_STORAGE_GET_DEVICE_NUMBER \"\\\\.\\PHYSICALDRIVE%d\" STORAGE_DEVICE_NUMBER.DeviceNumber SetupDiGetClassDevs #include <Windows.h>\n#include <Setupapi.h>\n#include <Ntddstor.h>\n\n#pragma comment( lib, \"setupapi.lib\" )\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#define START_ERROR_CHK() \\\n DWORD error = ERROR_SUCCESS; \\\n DWORD failedLine; \\\n string failedApi;\n\n#define CHK( expr, api ) \\\n if ( !( expr ) ) { \\\n error = GetLastError( ); \\\n failedLine = __LINE__; \\\n failedApi = ( api ); \\\n goto Error_Exit; \\\n }\n\n#define END_ERROR_CHK() \\\n error = ERROR_SUCCESS; \\\n Error_Exit: \\\n if ( ERROR_SUCCESS != error ) { \\\n cout << failedApi << \" failed at \" << failedLine << \" : Error Code - \" << error << endl; \\\n }\n\nint main( int argc, char **argv ) {\n\n HDEVINFO diskClassDevices;\n GUID diskClassDeviceInterfaceGuid = GUID_DEVINTERFACE_DISK;\n SP_DEVICE_INTERFACE_DATA deviceInterfaceData;\n PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData;\n DWORD requiredSize;\n DWORD deviceIndex;\n\n HANDLE disk = INVALID_HANDLE_VALUE;\n STORAGE_DEVICE_NUMBER diskNumber;\n DWORD bytesReturned;\n\n START_ERROR_CHK();\n\n //\n // Get the handle to the device information set for installed\n // disk class devices. Returns only devices that are currently\n // present in the system and have an enabled disk device\n // interface.\n //\n diskClassDevices = SetupDiGetClassDevs( &diskClassDeviceInterfaceGuid,\n NULL,\n NULL,\n DIGCF_PRESENT |\n DIGCF_DEVICEINTERFACE );\n CHK( INVALID_HANDLE_VALUE != diskClassDevices,\n \"SetupDiGetClassDevs\" );\n\n ZeroMemory( &deviceInterfaceData, sizeof( SP_DEVICE_INTERFACE_DATA ) );\n deviceInterfaceData.cbSize = sizeof( SP_DEVICE_INTERFACE_DATA );\n deviceIndex = 0;\n\n while ( SetupDiEnumDeviceInterfaces( diskClassDevices,\n NULL,\n &diskClassDeviceInterfaceGuid,\n deviceIndex,\n &deviceInterfaceData ) ) {\n\n ++deviceIndex;\n\n SetupDiGetDeviceInterfaceDetail( diskClassDevices,\n &deviceInterfaceData,\n NULL,\n 0,\n &requiredSize,\n NULL );\n CHK( ERROR_INSUFFICIENT_BUFFER == GetLastError( ),\n \"SetupDiGetDeviceInterfaceDetail - 1\" );\n\n deviceInterfaceDetailData = ( PSP_DEVICE_INTERFACE_DETAIL_DATA ) malloc( requiredSize );\n CHK( NULL != deviceInterfaceDetailData,\n \"malloc\" );\n\n ZeroMemory( deviceInterfaceDetailData, requiredSize );\n deviceInterfaceDetailData->cbSize = sizeof( SP_DEVICE_INTERFACE_DETAIL_DATA );\n\n CHK( SetupDiGetDeviceInterfaceDetail( diskClassDevices,\n &deviceInterfaceData,\n deviceInterfaceDetailData,\n requiredSize,\n NULL,\n NULL ),\n \"SetupDiGetDeviceInterfaceDetail - 2\" );\n\n disk = CreateFile( deviceInterfaceDetailData->DevicePath,\n GENERIC_READ,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL );\n CHK( INVALID_HANDLE_VALUE != disk,\n \"CreateFile\" );\n\n CHK( DeviceIoControl( disk,\n IOCTL_STORAGE_GET_DEVICE_NUMBER,\n NULL,\n 0,\n &diskNumber,\n sizeof( STORAGE_DEVICE_NUMBER ),\n &bytesReturned,\n NULL ),\n \"IOCTL_STORAGE_GET_DEVICE_NUMBER\" );\n\n CloseHandle( disk );\n disk = INVALID_HANDLE_VALUE;\n\n cout << deviceInterfaceDetailData->DevicePath << endl;\n cout << \"\\\\\\\\?\\\\PhysicalDrive\" << diskNumber.DeviceNumber << endl;\n cout << endl;\n }\n CHK( ERROR_NO_MORE_ITEMS == GetLastError( ),\n \"SetupDiEnumDeviceInterfaces\" );\n\n END_ERROR_CHK();\n\nExit:\n\n if ( INVALID_HANDLE_VALUE != diskClassDevices ) {\n SetupDiDestroyDeviceInfoList( diskClassDevices );\n }\n\n if ( INVALID_HANDLE_VALUE != disk ) {\n CloseHandle( disk );\n }\n\n return error;\n}\n"
},
{
"answer_id": 28550731,
"author": "polkovnikov.ph",
"author_id": 1872046,
"author_profile": "https://Stackoverflow.com/users/1872046",
"pm_score": 4,
"selected": false,
"text": "#include <windows.h>\n#include <iostream>\n#include <bitset>\n#include <vector>\nusing namespace std;\n\ntypedef struct _DISK_EXTENT {\n DWORD DiskNumber;\n LARGE_INTEGER StartingOffset;\n LARGE_INTEGER ExtentLength;\n} DISK_EXTENT, *PDISK_EXTENT;\n\ntypedef struct _VOLUME_DISK_EXTENTS {\n DWORD NumberOfDiskExtents;\n DISK_EXTENT Extents[ANYSIZE_ARRAY];\n} VOLUME_DISK_EXTENTS, *PVOLUME_DISK_EXTENTS;\n\n#define CTL_CODE(DeviceType, Function, Method, Access) \\\n (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))\n#define IOCTL_VOLUME_BASE ((DWORD)'V')\n#define METHOD_BUFFERED 0\n#define FILE_ANY_ACCESS 0x00000000\n#define IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)\n\nint main() {\n bitset<32> drives(GetLogicalDrives());\n vector<char> goodDrives;\n for (char c = 'A'; c <= 'Z'; ++c) {\n if (drives[c - 'A']) {\n if (GetDriveType((c + string(\":\\\\\")).c_str()) == DRIVE_FIXED) {\n goodDrives.push_back(c);\n }\n }\n }\n for (auto & drive : goodDrives) {\n string s = string(\"\\\\\\\\.\\\\\") + drive + \":\";\n HANDLE h = CreateFileA(\n s.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,\n OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS, NULL\n );\n if (h == INVALID_HANDLE_VALUE) {\n cerr << \"Drive \" << drive << \":\\\\ cannot be opened\";\n continue;\n }\n DWORD bytesReturned;\n VOLUME_DISK_EXTENTS vde;\n if (!DeviceIoControl(\n h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,\n NULL, 0, &vde, sizeof(vde), &bytesReturned, NULL\n )) {\n cerr << \"Drive \" << drive << \":\\\\ cannot be mapped into physical drive\";\n continue;\n }\n cout << \"Drive \" << drive << \":\\\\ is on the following physical drives: \";\n for (int i = 0; i < vde.NumberOfDiskExtents; ++i) {\n cout << vde.Extents[i].DiskNumber << ' ';\n }\n cout << endl;\n }\n}\n DeviceIoControl"
},
{
"answer_id": 48743083,
"author": "Just Shadow",
"author_id": 5935112,
"author_profile": "https://Stackoverflow.com/users/5935112",
"pm_score": 2,
"selected": false,
"text": "queryAndPrintResult(L\"SELECT * FROM Win32_DiskDrive\", L\"Name\");\n"
},
{
"answer_id": 65152369,
"author": "otto_",
"author_id": 9924879,
"author_profile": "https://Stackoverflow.com/users/9924879",
"pm_score": 2,
"selected": false,
"text": "powershell \"get-physicaldisk\"\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] |
327,722 | <p>I'm trying to get NAnt 0.86b1 running with VS2008 SP1 and x64 XP.</p>
<p>I have a basic build file (below) which gives the error
Solution format of file 'Solution.sln' is not supported.</p>
<p>
</p>
<pre><code><property name="nant.settings.currentframework" value="net-3.5" />
<target name="build" description="Full Rebuild" depends="clean,compile" />
<target name="clean" description="Cleans outputs">
<delete dir="bin" failonerror="false" />
<delete dir="obj" failonerror="false" />
</target>
<target name="compile" description="Compiles solution">
<solution configuration="debug" solutionfile="Solution.sln" />
</target>
</code></pre>
<p></p>
<p>Has anyone else experienced this problem? I can't find anything useful out there about this.</p>
| [
{
"answer_id": 327740,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 3,
"selected": false,
"text": "<solution <msbuild> <msbuild>"
},
{
"answer_id": 426455,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " <target name=\"build\" description=\"Compiles using the AutomatedDebug Configuration\">\n <!-- <loadtasks assembly=\"C:\\Dev\\nant-0.86-beta1\\bin\\NAnt.Contrib.Tasks.dll\" /> -->\n <msbuild project=\"${Solution.Filename}\">\n <property name=\"Configuration\" value=\"Release\"/>\n </msbuild>\n </target>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34632/"
] |
327,732 | <p>We are working on an inquiry management system using J2EE. We're looking at a feature, allowing users to send inquiries to particular mail-id and entering into the database. Catch is to automatically allocate it to some categories. </p>
| [
{
"answer_id": 327740,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 3,
"selected": false,
"text": "<solution <msbuild> <msbuild>"
},
{
"answer_id": 426455,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " <target name=\"build\" description=\"Compiles using the AutomatedDebug Configuration\">\n <!-- <loadtasks assembly=\"C:\\Dev\\nant-0.86-beta1\\bin\\NAnt.Contrib.Tasks.dll\" /> -->\n <msbuild project=\"${Solution.Filename}\">\n <property name=\"Configuration\" value=\"Release\"/>\n </msbuild>\n </target>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31590/"
] |
327,745 | <p><strong>I am very, very new to MYSQL.I tried to create a table named "option".</strong>
<strong>My SQL Query is :</strong></p>
<p>create table option( </p>
<p>id int not null primary key auto_increment,</p>
<p>choice varchar(30)</p>
<p>)</p>
<p><strong>While executing this query it shows the following error</strong></p>
<p>Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option(
id int not null primary key auto_increment,
choice varchar(30)
)' at line 1
(0 ms taken)</p>
<p><strong>If I try with the table name as "choice" it is working.</strong></p>
<p><strong>can we have the table name as "option" in mysql?</strong> </p>
<p>thanks</p>
| [
{
"answer_id": 327752,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": false,
"text": "`option`\n"
},
{
"answer_id": 327753,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": " CREATE TABLE `option` (\n ...\n )\n"
},
{
"answer_id": 327757,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 0,
"selected": false,
"text": "create table `option` (\n...\n)\n"
},
{
"answer_id": 33330214,
"author": "Ketan Patil",
"author_id": 5429123,
"author_profile": "https://Stackoverflow.com/users/5429123",
"pm_score": 0,
"selected": false,
"text": "`option`\n option"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40945/"
] |
327,772 | <p>I have a Java object which is able to configure itself given an XML configuration description (it takes other descriptions as well, but I'm interested in the XML at the moment). I'm wondering if I can embed the XML description directly into a Spring application context description. I'm imagining something like:</p>
<pre><code><bean id="myXMLConfiguredBean" class="com.example.Foo">
<constructor-arg type="xml">
<myconfig xmlns="http://example.com/foo/config">
<bar>42</bar>
</myconfig>
</constructor-arg>
</bean>
</code></pre>
<p>but I have no idea if that - or something like it - is possible. I realise I could embed myconfig in a CDATA section, but that seems a bit ugly.</p>
| [
{
"answer_id": 328190,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": true,
"text": "<constructor-arg> <xsd:element name=\"constructor-arg\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element ref=\"description\" minOccurs=\"0\" />\n <xsd:choice minOccurs=\"0\" maxOccurs=\"1\">\n <xsd:element ref=\"bean\" />\n <xsd:element ref=\"ref\" />\n <xsd:element ref=\"idref\" />\n <xsd:element ref=\"value\" />\n <xsd:element ref=\"null\" />\n <xsd:element ref=\"list\" />\n <xsd:element ref=\"set\" />\n <xsd:element ref=\"map\" />\n <xsd:element ref=\"props\" />\n <!-- Any XML -->\n <xsd:any namespace=\"##other\" processContents=\"strict\" />\n </xsd:choice>\n </xsd:sequence>\n ...\n </xsd:complexType>\n</xsd:element>\n processContents xsi:type"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6716/"
] |
327,776 | <p>Imagine I have a file with </p>
<pre><code>Xpto,50,30,60
Xpto,a,v,c
Xpto,1,9,0
Xpto,30,30,60
</code></pre>
<p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p>
| [
{
"answer_id": 327825,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 3,
"selected": false,
"text": "os.popen(\"tail -10 \" +\n filepath).readlines() tail"
},
{
"answer_id": 327980,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 1,
"selected": false,
"text": "f.seek( pos ,2)"
},
{
"answer_id": 10180739,
"author": "Ben",
"author_id": 1322906,
"author_profile": "https://Stackoverflow.com/users/1322906",
"pm_score": 0,
"selected": false,
"text": "i=0\nwhile(1):\n f.seek(i, 2)\n c = f.read(1)\n if(c=='\\n'):\n break\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41795/"
] |
327,777 | <p>I am fairly beginner level at shell scripts and following are the details..</p>
<p>Am looking for the best way to fire sql queries and and carry out some logic based on that data. I've used the following snippet..</p>
<p>shellvariable=<code>sqlplus $user/$passwd <<END
select count(1) from table1;
end
EOF</code></p>
<p>if[$shellvariable -ne 0] then
<>
fi</p>
<p>Is there a better way to carry out the same..</p>
| [
{
"answer_id": 328617,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 3,
"selected": true,
"text": "alertlog=$(sqlplus -S \\/ as sysdba 2> /dev/null <<EOF\nSET NEWPAGE 0\nSET SPACE 0\nSET LINESIZE 80\nSET PAGESIZE 0\nSET ECHO OFF\nSET FEEDBACK OFF\nSET VERIFY OFF\nSET HEADING OFF\nSELECT value \nFROM v\\$parameter \nWHERE name = 'background_dump_dest';\nEOF\n)\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31590/"
] |
327,787 | <p>I'm creating a user-based website. For each user, I'll need a few MySQL tables to store different types of information (that is, userInfo, quotesSubmitted, and ratesSubmitted). Is it a better idea to:</p>
<p>a) Create one database for the site (that is, "mySite") and then hundreds or thousands of tables inside this (that is, "userInfo_bob", "quotessubmitted_bob", "userInfo_shelly", and"quotesSubmitted_shelly")</p>
<p>or</p>
<p>b) Create hundreds or thousands of databases (that is, "Bob", "Shelly", etc.) and only a couple tables per database (that is, Inside of "Bob": userInfo, quotesSubmitted, ratesSubmitted, etc.)</p>
<p><strong>Should I use one database, and many tables in that database, or many databases and few tables per database?</strong></p>
<hr>
<p>Edit:</p>
<p>The problem is that I need to keep track of who has rated what. That means if a user has rated 300 quotes, I need to be able to know exactly which quotes the user has rated.</p>
<p>Maybe I should do this?</p>
<p>One table for quotes. One table to list users. One table to document ALL ratings that have been made (that is, Three columns: User, Quote, rating). That seems reasonable. Is there any problem with that?</p>
| [
{
"answer_id": 327798,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE user (\n user INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ...\n);\n\nCREATE TABLE quote (\n quote INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n user INT(10) UNSIGNED NOT NULL,\n ...\n);\n\nCREATE TABLE rate (\n rate INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n user INT(10) UNSIGNED NOT NULL,\n ...\n );\n JOIN SELECT"
},
{
"answer_id": 327889,
"author": "Ivan Vučica",
"author_id": 39974,
"author_profile": "https://Stackoverflow.com/users/39974",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE quotesSubmtited (\n userid INTEGER, \n submittime DATETIME, \n quote INTEGER,\n quotedata INTEGER, \n PRIMARY KEY (userid, submittime),\n FOREIGN KEY quote REFERENCES quotesList (quoteId),\n FOREIGN KEY userid REFERENCES userList (userId)\n);\n\nCREATE INDEX idx1 ON quotesSubmitted (quote);\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] |
327,793 | <p>I have a J2EE-based system which is running currently on Apache Tomcat. We are in discussions to move our production servers to the Glassfish server.</p>
<p>Can someone share their experiences with either of them?</p>
| [
{
"answer_id": 327810,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "grizzly"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31590/"
] |
327,807 | <p>I have a model that looks like this:</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
</code></pre>
<p>I want select count (just the count) of items for each category, so in SQL it would be as simple as this:</p>
<pre><code>select category_id, count(id) from item group by category_id
</code></pre>
<p>Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the <em>count( )</em> method in Django, however I don't see how <em>group by</em> would fit there.</p>
| [
{
"answer_id": 327987,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 6,
"selected": false,
"text": "query_set = Item.objects.extra(select={'count': 'count(1)'}, \n order_by=['-count']).values('count', 'category')\nquery_set.query.group_by = ['category_id']\n"
},
{
"answer_id": 328040,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "counts= [ (c, Item.filter( category=c.id ).count()) for c in Category.objects.all() ]\n counts = defaultdict(int)\nfor i in Item.objects.all():\n counts[i.category] += 1\n"
},
{
"answer_id": 1317837,
"author": "michael",
"author_id": 161109,
"author_profile": "https://Stackoverflow.com/users/161109",
"pm_score": 8,
"selected": true,
"text": "from django.db.models import Count\ntheanswer = Item.objects.values('category').annotate(Count('category'))\n"
},
{
"answer_id": 1341667,
"author": "Daniel",
"author_id": 164268,
"author_profile": "https://Stackoverflow.com/users/164268",
"pm_score": 6,
"selected": false,
"text": "from django.db.models import Count\ntheanswer = Item.objects.values('category').annotate(Count('category'))\n from django.db.models import Count category__count category Item.objects.values('category').annotate(Count('category')).order_by()\n ...annotate(mycount = Count('category'))...\n mycount"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26592/"
] |
327,829 | <p>I have a button control style and I want to change the padding from whatever the data-bound version is to adjust for a glyph that needs a 2 pixel offset. I'll use SimpleButton from SimpleStyles.xaml as an example (... shows where the trigger code was removed for conciseness):</p>
<pre><code><Style x:Key="SimpleButton" TargetType="{x:Type Button}" BasedOn="{x:Null}">
<Setter Property="FocusVisualStyle" Value="{DynamicResource SimpleButtonFocusVisual}"/>
<Setter Property="Background" Value="{DynamicResource NormalBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource NormalBorderBrush}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<!-- We use Grid as a root because it is easy to add more elements to customize the button -->
<Grid x:Name="Grid">
<Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"/>
<!-- Content Presenter is where the text content etc is placed by the control. The bindings are useful so that the control can be parameterized without editing the template -->
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
...
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>What I want to do is add some extra margin where Padding="{TemplateBinding Padding}". Something like Padding="{TemplateBinding Padding} + 2,0,0,0".</p>
<p>Is there a XAML syntax to that? If not, is there a best approach when doing this in code (Decorator?) ?</p>
| [
{
"answer_id": 327997,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 2,
"selected": false,
"text": "<Ellipse Fill=\"Blue\" Height=\"50\"\n Width=\"{Binding RelativeSource={RelativeSource Self}, \n Path=Height, Converter={StaticResource MyConverter}}\" />\n <Ellipse Fill=\"Blue\" Height=\"50\"\n Width=\"{blendables:EvalBinding [{Self}.Height]/2}\" />\n"
},
{
"answer_id": 329152,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "ExpressionConverter"
},
{
"answer_id": 329180,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 4,
"selected": true,
"text": "<Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Button}\">\n <Grid x:Name=\"Grid\">\n <Grid.Resources>\n <local:ThicknessAdditionConverter x:Key=\"AdditiveThickness\" />\n </Grid.Resources>\n <Border x:Name=\"Border\">\n <Border.Padding>\n <Binding Path=\"Padding\" RelativeSource=\"{RelativeSource TemplatedParent}\"\n Converter=\"{StaticResource AdditiveThickness}\">\n <Binding.ConverterParameter>\n <Thickness>2,0,0,0</Thickness>\n </Binding.ConverterParameter>\n </Binding>\n </Border.Padding>\n </Border>\n ...\n</Setter.Value> \n public class ThicknessAdditionConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null) return new Thickness(0, 0, 0, 0);\n if (!(value is Thickness)) throw new ArgumentException(\"Value not a thickness\", \"value\");\n if (!(parameter is Thickness)) throw new ArgumentException(\"Parameter not a thickness\", \"parameter\");\n\n var thickness = new Thickness(0, 0, 0, 0);\n var t1 = (Thickness)value;\n var t2 = (Thickness)parameter;\n\n thickness.Left = t1.Left + t2.Left;\n thickness.Top = t1.Top + t2.Top;\n thickness.Right = t1.Right + t2.Right;\n thickness.Bottom = t1.Bottom + t2.Bottom;\n\n return thickness;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"
},
{
"answer_id": 15620101,
"author": "cederlof",
"author_id": 198953,
"author_profile": "https://Stackoverflow.com/users/198953",
"pm_score": 1,
"selected": false,
"text": "ConverterParameter=((@VALUE-15)*.2)\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30505/"
] |
327,836 | <p>I have a multi file C program. I'd like the user to be able to specify different debugging levels at run time.</p>
<p>What is the best way to implement this?</p>
<p>I was thinking of having a debug(level, "message") type function exported and used everywhere. Any better/other ideas?</p>
| [
{
"answer_id": 327870,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "-d -D nn -D input=3,macros=5,rules=1 /*\n** Usage: TRACE((level, fmt, ...))\n** \"level\" is the debugging level which must be operational for the output\n** to appear. \"fmt\" is a printf format string. \"...\" is whatever extra\n** arguments fmt requires (possibly nothing).\n** The non-debug macro means that the code is validated but never called.\n** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.\n*/\n#ifdef DEBUG\n#define TRACE(x) db_print x\n#else\n#define TRACE(x) do { if (0) db_print x; } while (0)\n#endif /* DEBUG */\n\n#ifndef lint\n#ifdef DEBUG\n/* This string can't be made extern - multiple definition in general */\nstatic const char jlss_id_debug_enabled[] = \"@(#)*** DEBUG ***\";\n#endif /* DEBUG */\n#ifdef MAIN_PROGRAM\nconst char jlss_id_debug_h[] = \"@(#)$Id: debug.h,v 3.6 2008/02/11 06:46:37 jleffler Exp $\";\n#endif /* MAIN_PROGRAM */\n#endif /* lint */\n\n#include <stdio.h>\n\nextern int db_getdebug(void);\nextern int db_newindent(void);\nextern int db_oldindent(void);\nextern int db_setdebug(int level);\nextern int db_setindent(int i);\nextern void db_print(int level, const char *fmt,...);\nextern void db_setfilename(const char *fn);\nextern void db_setfileptr(FILE *fp);\nextern FILE *db_getfileptr(void);\n\n/* Semi-private function */\nextern const char *db_indent(void);\n\n/**************************************\\\n** MULTIPLE DEBUGGING SUBSYSTEMS CODE **\n\\**************************************/\n\n/*\n** Usage: MDTRACE((subsys, level, fmt, ...))\n** \"subsys\" is the debugging system to which this statement belongs.\n** The significance of the subsystems is determined by the programmer,\n** except that the functions such as db_print refer to subsystem 0.\n** \"level\" is the debugging level which must be operational for the\n** output to appear. \"fmt\" is a printf format string. \"...\" is\n** whatever extra arguments fmt requires (possibly nothing).\n** The non-debug macro means that the code is validated but never called.\n*/\n#ifdef DEBUG\n#define MDTRACE(x) db_mdprint x\n#else\n#define MDTRACE(x) do { if (0) db_mdprint x; } while (0)\n#endif /* DEBUG */\n\nextern int db_mdgetdebug(int subsys);\nextern int db_mdparsearg(char *arg);\nextern int db_mdsetdebug(int subsys, int level);\nextern void db_mdprint(int subsys, int level, const char *fmt,...);\nextern void db_mdsubsysnames(char const * const *names);\n"
},
{
"answer_id": 328660,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 4,
"selected": false,
"text": "#define LOG_FATAL (1)\n#define LOG_ERR (2)\n#define LOG_WARN (3)\n#define LOG_INFO (4)\n#define LOG_DBG (5)\n\n#define LOG(level, ...) do { \\\n if (level <= debug_level) { \\\n fprintf(dbgstream,\"%s:%d:\", __FILE__, __LINE__); \\\n fprintf(dbgstream, __VA_ARGS__); \\\n fprintf(dbgstream, \"\\n\"); \\\n fflush(dbgstream); \\\n } \\\n } while (0)\nextern FILE *dbgstream;\nextern int debug_level;\n LOG(LOG_ERR, \"I/O error %s occured while opening file %s\", strerror(errno), filename); dbgstream stderr debug_level fprintf LOG __FILE__ __LINE__ __VA_ARGS_ fflush()"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,838 | <p>I have a Button style and can't seem to property databind the border's CornerRadius property to the template. This is a dependency property, so it should be data bindable. I wonder if I'm missing the right XAML syntax to use?</p>
<pre><code><Style TargetType="{x:Type Button}" BasedOn="{x:Null}">
<Setter Property="FocusVisualStyle" Value="{DynamicResource MyButtonFocusVisual}"/>
<Setter Property="Background" Value="{DynamicResource MyButtonBackgroundBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource MyButtonForegroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource MyButtonBorderBrush}"/>
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="FontFamily" Value="Segoe UI"/>
<Setter Property="FontSize" Value="14" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<!-- We use Grid as a root because it is easy to add more elements to customize the button -->
<Grid x:Name="Grid">
<Border x:Name="Border" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>Both and CornerRadius="{TemplateBinding CornerRadius}" give me the error "CornerRadius is not recognized or is not accessible". </p>
| [
{
"answer_id": 329150,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": true,
"text": "CornerRadius Button"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30505/"
] |
327,843 | <p>A simple problem: If i use escape characters for a property such as</p>
<pre><code><mx:Image id="img" toolTip="\\foo{\\bar}"
</code></pre>
<p>It wont validate toolTip and therefore not compile.</p>
<p>What is the solution ?</p>
| [
{
"answer_id": 340460,
"author": "Jérémy Reynaud",
"author_id": 43051,
"author_profile": "https://Stackoverflow.com/users/43051",
"pm_score": 2,
"selected": false,
"text": "<mx:Image id=\"img\" source=\"foo.jpg\" width=\"50\" height=\"50\">\n<mx:toolTip>\n <![CDATA[\\foo{\\bar} or any usually forbidden characters as <, >, &, \"'\"...]]>\n</mx:toolTip></mx:Image>\n"
},
{
"answer_id": 11456171,
"author": "Alex",
"author_id": 1222914,
"author_profile": "https://Stackoverflow.com/users/1222914",
"pm_score": 1,
"selected": false,
"text": "<mx:Image id=\"img\" toolTip=\"\foo{\bar}\"/>"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32032/"
] |
327,857 | <p>I have a list of input words separated by comma. I want to sort these words by alphabetical and length. How can I do this without using the built-in sorting functions?</p>
| [
{
"answer_id": 327891,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 2,
"selected": false,
"text": "public static void Main(string[] args)\n{\n string [] strList = \"a,b,c,d,e,f,a,a,b\".Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);\n\n foreach(string s in strList.Sort())\n Console.WriteLine(s);\n}\n\npublic static string [] Sort(this string [] strList)\n{\n return strList.OrderBy(i => i).ToArray();\n}\n OrderBy"
},
{
"answer_id": 327934,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 5,
"selected": true,
"text": "int CompareStrings(String a, String b) {\n if (a < b)\n return -1;\n else if (a > b)\n return 1;\n else\n return 0;\n}\n 1 4 8 10 \n 2 5 7 9\n------------ becomes ------------> \n1 2 4 5 7 8 9 10\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,880 | <p>Is there anyway to get the THotkey component in delphi to support the windows key?</p>
<p>Or does anyone know of a component that can do this?</p>
<p>Thanks heaps!</p>
| [
{
"answer_id": 343710,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 2,
"selected": false,
"text": " TMyCustomHotKey = class(TWinControl)\n public\n WinKey: boolean;\n procedure WMPaint(var Message: TWMPaint); message WM_PAINT;\n constructor Create(AOwner: TComponent); override;\n end;\n\n TMyHotKey = class(TMyCustomHotKey)\n procedure TMyCustomHotKey.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);\n var\n a : integer;\n lbl : string;\n tmphot : tshortcut;\n begin\n\n a:= 0;\n if GetAsyncKeyState(VK_LWIN) <> 0 then a:= 1;\n if GetAsyncKeyState(VK_RWIN) <> 0 then a:= 1;\n\n if a=1 then begin\n winkey := true;\n end else\n begin\n winkey := false;\n end;\n rePaint();\n}\n\n\nprocedure TMyCustomHotKey.WMPaint(var Message: TWMPaint);\nvar\n PS: TPaintStruct;\n DC: HDC;\n Canvas: TCanvas;\n i: Integer;\n X, Y: Integer;\n OldColor: TColor;\n Size: TSize;\n Max: Integer;\n s, Palabra, PrevWord: string;\n OldPen, DrawPen: HPEN;\n tmphot : tshortcut;\n Key: Word;\n Shift: TShiftState;\n\n lbl ,res: string;\n keyboardState: TKeyboardState;\nasciiResult: Integer;\n\nbegin\n\n DC := Message.DC;\n if DC = 0 then DC := BeginPaint(Handle, PS);\n\n Canvas := TCanvas.Create;\n try\n\n OldColor := Font.Color;\n Canvas.Handle := DC;\n Canvas.Font.Name := Font.Name;\n Canvas.Font.Size := Font.Size;\n with Canvas do\n begin\n\n Brush.Color := Self.Color;\n FillRect(Self.ClientRect);\n Font.Color := OldColor;\n\n tmphot := gethotkey;\n ShortCutToKey(tmphot, Key, Shift);\n\n res := GetCharFromVKey(key);\n\n\n if (winkey = false) and (key = 0 ) and (tmphot = 0)then\n BEGIN lbl := 'Enter hotkey [CTRL/ALT/WIN] + Key' ;\n TextOut(1 ,1,lbl) ;\n END\n else begin\n\n if winkey then lbl := 'Win +' else lbl := '';\n if ssAlt in Shift then lbl := lbl+ 'Alt + ';\n if ssShift in Shift then lbl := lbl+ 'Shift + ';\n if (not winkey) and (ssCtrl in Shift) then lbl := lbl+ 'Ctrl + ';\n lbl := lbl+ res;\n\n end;\n\n TextOut(1 ,1,lbl);\n\n\n\n end;\n\n finally\n if Message.DC = 0 then EndPaint(Handle, PS);\n end;\n Canvas.Free;\n SETCARETPOS(1,1);\n\nend;\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41837/"
] |
327,885 | <p>In <a href="http://www.asp.net/mvc/" rel="noreferrer">ASP.NET MVC</a>, the <code>ActionResult</code> class, which is the base for all results returned by action methods from a controller, is defined as an abstract class with the single method (© Microsoft):</p>
<pre><code>public abstract void ExecuteResult(ControllerContext context);
</code></pre>
<p>Can you think of any specific reasons for this design? Specifically, it seems a bit weird to me, that</p>
<ul>
<li>there is no <code>IActionResult</code> interface,</li>
<li>and that the class would not be required at all, if there was such an interface.</li>
</ul>
<p>After all, if this was an interface instead of that abstract class, there would be no need to extend a base class in order to create a new <code>ActionResult</code> - one would just have to implement <code>IActionResult</code> properly. In a world, err language, without multiple inheritance, this advantage would seem quite important to me.</p>
| [
{
"answer_id": 10819629,
"author": "fargs",
"author_id": 1426411,
"author_profile": "https://Stackoverflow.com/users/1426411",
"pm_score": 1,
"selected": false,
"text": "public ActionResult Get(){\n var customer = new Customer();\n return View(customer);\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11963/"
] |
327,893 | <p>I have a structure:</p>
<pre><code>struct pkt_
{
double x;
double y;
double alfa;
double r_kw;
};
typedef struct pkt_ pkt;
</code></pre>
<p>A table of these structures:</p>
<pre><code>pkt *tab_pkt;
tab_pkt = malloc(ilosc_pkt * sizeof(pkt));
</code></pre>
<p>What I want to do is to sort <code>tab_pkt</code> by <code>tab_pkt.alfa</code> and <code>tab_pkt.r</code>:</p>
<pre><code>qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);
</code></pre>
<p>Where porownaj is a compare function, but how to write it? Here is my "sketch" of it:</p>
<pre><code>int porownaj(const void *pkt_a, const void *pkt_b)
{
if (pkt_a.alfa > pkt_b.alfa && pkt_a.r_kw > pkt_b.r_kw) return 1;
if (pkt_a.alfa == pkt_b.alfa && pkt_a.r_kw == pkt_b.r_kw) return 0;
if (pkt_a.alfa < pkt_b.alfa && pkt_a.r_kw < pkt_b.r_kw) return -1;
}
</code></pre>
| [
{
"answer_id": 327925,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "porownaj(&pkt_a, &pkt_b) == -porownaj(&pkt_b, &pkt_a)\n pkt_a->alfa > pkt_b->alfa && pkt_a->r_kw <= pkt_b->r_kw\npkt_a->alfa < pkt_b->alfa && pkt_a->r_kw >= pkt_b->r_kw\npkt_a->alfa == pkt_b->alfa && pkt_a->r_kw != pkt_b->r_kw\n int porownaj(const void *vp1, const void *vp2)\n{\n const pkt *pkt_a = (const pkt *)vp1;\n const pkt *pkt_b = (const pkt *)vp2;\n\n if (pkt_a->alfa > pkt_b->alfa && pkt_a->r_kw > pkt_b->r_kw) return 1;\n if (pkt_a->alfa == pkt_b->alfa && pkt_a->r_kw == pkt_b->r_kw) return 0;\n if (pkt_a->alfa < pkt_b->alfa && pkt_a->r_kw < pkt_b->r_kw) return -1;\n return 0;\n }\n"
},
{
"answer_id": 327929,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "int porownaj(const void *p_a, const void *p_b)\n{\n /* Need to store arguments in appropriate type before using */\n const pkt *pkt_a = p_a;\n const pkt *pkt_b = p_b;\n\n /* Return 1 or -1 if alfa members are not equal */\n if (pkt_a->alfa > pkt_b->alfa) return 1;\n if (pkt_a->alfa < pkt_b->alfa) return -1;\n\n /* If alfa members are equal return 1 or -1 if r_kw members not equal */\n if (pkt_a->r_kw > pkt_b->r_kw) return 1;\n if (pkt_a->r_kw < pkt_b->r_kw) return -1;\n\n /* Return 0 if both members are equal in both structures */\n return 0;\n}\n return pkt_a->r_kw - pkt_b->r_kw;\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41839/"
] |
327,895 | <p>Currently I have to uninstall the old version of my service before I install the new version. I am pretty sure this has something to do with it not being smart enough to update or remove the old service entries before adding the new ones.</p>
<p>Is there a way to have the installer skip registering the service if it already exists? (I can assume the installation folder and service name do not change between versions.)</p>
<p>Also, is there a way to automatically stop the service when uninstalling?</p>
<hr />
<h3>Edit:</h3>
<p>I am using MSI packages and the Visual Studio setup project.</p>
| [
{
"answer_id": 328032,
"author": "David Pokluda",
"author_id": 223,
"author_profile": "https://Stackoverflow.com/users/223",
"pm_score": 3,
"selected": false,
"text": "sc stop {name of your service}\nsc start {name of your service}\n"
},
{
"answer_id": 328211,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "<Component Id='c_WSService' Guid='*'>\n <File Id='f_WSService' Name='WSService.exe' Vital='yes' Source='..\\wssvr\\release\\wsservice.exe' KeyPath=\"yes\" />\n <ServiceInstall Id='WSService.exe' Name='WSService' DisplayName='[product name]' Type='ownProcess'\n Interactive='no' Start='auto' Vital='yes' ErrorControl='normal'\n Description='Provides local and remote access to [product name] search facilities.' />\n <ServiceControl Id='WSService.exe' Name='WSService' Start='install' Stop='both' Remove='uninstall' Wait='yes' />\n</Component>\n"
},
{
"answer_id": 14279169,
"author": "edhubbell",
"author_id": 1054938,
"author_profile": "https://Stackoverflow.com/users/1054938",
"pm_score": 0,
"selected": false,
"text": "ProjectInstaller.vb msi RunCommandCom 'This works. It leaves the MSI in a state that tells you to reboot the PC, but you really don't need to.\n\nPrivate Sub ProjectInstaller_BeforeInstall(sender As Object, e As System.Configuration.Install.InstallEventArgs) Handles Me.BeforeInstall\n\n Dim sEchoMessage As String = String.Empty\n sEchoMessage &= \" & ECHO ****************** Please be patient *******************************\"\n sEchoMessage &= \" & ECHO Pausing to stop and delete the previous version of the following service:\"\n sEchoMessage &= \" & ECHO \" & ServiceInstaller1.ServiceName\n sEchoMessage &= \" & ECHO -------------------------------------------------------------------------------\"\n sEchoMessage &= \" & ECHO After install is complete, you may see a message that says you need to reboot.\"\n sEchoMessage &= \" & ECHO You may IGNORE this message - The service will be installed and running.\"\n sEchoMessage &= \" & ECHO There is NO Reboot required.\"\n sEchoMessage &= \" & ECHO *******************************************************************************\"\n\n RunCommandCom(\"sc stop \" & ServiceInstaller1.ServiceName & \" & sc delete \" & ServiceInstaller1.ServiceName & sEchoMessage, 15000)\n\nEnd Sub\n\nPrivate Sub RunCommandCom(command As String, mSecSleepAfterExecution As Integer)\n\n Using p As Process = New Process()\n Dim pi As ProcessStartInfo = New ProcessStartInfo()\n pi.Arguments = \" /K \" + command\n pi.FileName = \"cmd.exe\"\n p.StartInfo = pi\n p.Start()\n System.Threading.Thread.Sleep(mSecSleepAfterExecution)\n p.CloseMainWindow()\n End Using\n\nEnd Sub\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5274/"
] |
327,896 | <p>I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.</p>
<p>Can anyone point me to some example code that does this?</p>
| [
{
"answer_id": 327908,
"author": "chirag",
"author_id": 40596,
"author_profile": "https://Stackoverflow.com/users/40596",
"pm_score": 0,
"selected": false,
"text": "aalines(...)\n pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect\n\narc(...)\n pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect\n draw a partial section of an ellipse\n\ncircle(...)\n pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect\n draw a circle around a point\n\nellipse(...)\n pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect\n draw a round shape inside a rectangle\n\nline(...)\n pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect\n draw a straight line segment\n\nlines(...)\n pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect\n draw multiple contiguous line segments\n\npolygon(...)\n pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect\n draw a shape with any number of sides\n\nrect(...)\n pygame.draw.rect(Surface, color, Rect, width=0): return Rect\n draw a rectangle shape\n"
},
{
"answer_id": 328002,
"author": "Martin Vilcans",
"author_id": 2711383,
"author_profile": "https://Stackoverflow.com/users/2711383",
"pm_score": 3,
"selected": true,
"text": "# load the image\nimage = pygame.image.load(\"some_image.png\")\n\n# draw a yellow line on the image\npygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100))\n # initialize pygame and screen\nimport pygame\npygame.init()\nscreen = pygame.display.set_mode((720, 576))\n\n# Draw the image to the screen\nscreen.blit(image, (0, 0))\n\n# Draw a line on top of the image on the screen\npygame.draw.line(screen, (255, 255, 255), (0, 0), (50, 50))\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
] |
327,904 | <p>In the application I'm writing, one of the methods allows for the numbers the user entered to be turned into letters.</p>
<p>For example, the user will be entering grades (as doubles) and the program will decide (when the criteria is met) to return the letter associated with the number. Initially, I had it written like this:</p>
<pre><code>public void GetGrade(double scores)
Console.Write("Score of {0} earns: ", score);
if (score >= 95.0)
Console.WriteLine("A+");
else if (score >= 90.0)
Console.WriteLine("A");
else if (score >= 85.0)
Console.WriteLine("B+");
else if (score >= 80.0)
Console.WriteLine("B");
else if (score >= 75.0)
Console.WriteLine("C+");
else if (score >= 70.0)
Console.WriteLine("C");
else if (score >= 65.0)
Console.WriteLine("D+");
else if (score >= 60.0)
Console.WriteLine("D");
else
Console.WriteLine("F");
</code></pre>
<p>But it needs to be written with a RETURN in mind.
So, I think it should be public string <code>GetGrade(double scores)</code>
And since it's in an array I would need:</p>
<pre><code>foreach(double score in scoress)
{
THE CODE I POSTED ABOVE
}
</code></pre>
<p>Except I'd change all the <code>console.writeline</code>s to return.
However, when I do that I get a syntax error telling me:</p>
<blockquote>
<p>A local variable named score cannot be declared in this scope because it would give a different meaning to 'score', which is already used in parent or current scope to denote something else.</p>
</blockquote>
<p>So, I gather that I cannot use <code>score</code> because the header already contains <code>score</code>.
How do I go about getting this to work the way I want it to?</p>
| [
{
"answer_id": 327923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public string ToGrade(double score)\n{\n if (score >= 95.0)\n return \"A+\";\n else if (score >= 90.0)\n return \"A\";\n /* snip */\n else\n return \"YOU GET NOTHING! YOU LOSE! GOOD DAY SIR!\";\n}\n public static string[] ToGrade(double[] grades)\n{\n // sanity checks go here\n string[] result = new string[grades.Length];\n for(int i = 0; i < grades.Length; i++)\n result[i] = ToGrade(grades[i]);\n return result;\n}\n"
},
{
"answer_id": 327926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Foreach (double s in scores){...}\n scores"
},
{
"answer_id": 327931,
"author": "Din",
"author_id": 41214,
"author_profile": "https://Stackoverflow.com/users/41214",
"pm_score": 0,
"selected": false,
"text": "var list = [\n [95.0, \"A+\"],\n [90.0, \"A\"],\n [85.0, \"B+\"],\n [80.0, \"B\"],\n [75.0, \"C+\"],\n [70.0, \"C\"],\n [65.0, \"D+\"],\n [60.0, \"D\"]\n];\n\n for (var i in list)\n if (score >= list[0])\n return list[1];\n return \"F\";\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29756/"
] |
327,913 | <p>Ok, i have simple scenario:</p>
<p>have two pages:
login and welcome pages.
im using FormsAuthentication with my own table that has four columns: ID, UserName, Password, FullName</p>
<p>When pressed login im setting my username like:</p>
<pre><code>FormsAuthentication.SetAuthCookie(userName, rememberMe ?? false);
</code></pre>
<p>on the welcome page i cant use:</p>
<pre><code>Page.User.Identity.Name
</code></pre>
<p>to provide to user which user currently logged, BUT i dont user username like at all examples in <a href="http://asp.net" rel="nofollow noreferrer">http://asp.net</a> web site i want to user FullName field</p>
<p>i think that always go to db and request fullname when page loads its crazy and dont like to user Sessions or Simple Cookie mayby FormsAuth provider has custom fields for this</p>
| [
{
"answer_id": 328270,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": true,
"text": "FormsAuth.SetAuthCookie(userName, rememberme);\n\n// get the full name (ex \"John Doe\") from the datbase here during login\nstring fullName = \"John Doe\";\n\nResponse.Cookies[\"FullName\"].Value = fullName;\nResponse.Cookies[\"FullName\"].expires = DateTime.Now.AddDays(30);\n string fullName = HttpContext.Current.Request.Cookies[\"FullName\"].Value\n"
},
{
"answer_id": 56189530,
"author": "andkorsh",
"author_id": 2803237,
"author_profile": "https://Stackoverflow.com/users/2803237",
"pm_score": 1,
"selected": false,
"text": "var authCookieKey = FormsAuthentication.FormsCookieName;\nvar responseCookies = HttpContext.Current.Response.Cookies;\nvar requestCookies = HttpContext.Current.Request.Cookies;\n\nvar aspxAuthCookieInResponse = responseCookies.AllKeys.Contains(authCookieKey) ? responseCookies[authCookieKey] : null;\nvar aspxAuthCookieInRequest = requestCookies.AllKeys.Contains(authCookieKey) ? requestCookies[authCookieKey] : null;\n\n// Take ASPXAUTH cookie from either response or request.\nvar cookie = aspxAuthCookieInResponse ?? aspxAuthCookieInRequest;\nvar authTicket = FormsAuthentication.Decrypt(cookie.Value); // Todo: Check for nulls.\n\n// Using the name!\nvar userName = authTicket.Name;\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246271/"
] |
327,916 | <p>I was shocked to find out today that C# does not support dynamic sized arrays. How then does a <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="noreferrer">VB.NET</a> developer used to using <a href="http://msdn.microsoft.com/en-us/library/w8k3cys2.aspx" rel="noreferrer">ReDim Preserve</a> deal with this in C#?</p>
<p>At the beginning of the function I am not sure of the upper bound of the array. This depends on the rows returned from the database. </p>
| [
{
"answer_id": 327937,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 3,
"selected": false,
"text": "x = (int[]) Utils.CopyArray((Array) x, new int[10]);\n"
},
{
"answer_id": 327958,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "Array.Resize<T> using System;\n\nclass Foo\n{\n static void Main()\n {\n string[] x = new string[10];\n string[] y = x;\n\n Array.Resize(ref x, 20);\n Console.WriteLine(x.Length); // Prints out 20\n Console.WriteLine(y.Length); // Still prints out 10\n }\n}\n Imports System\n\nClass Foo\n Shared Sub Main()\n Dim x(9) as String\n Dim y as String() = x\n\n Redim Preserve x(19)\n Console.WriteLine(x.Length)\n Console.WriteLine(y.Length)\n End Sub\nEnd Class\n List<T>"
},
{
"answer_id": 13437260,
"author": "Hameer Abbasi",
"author_id": 774273,
"author_profile": "https://Stackoverflow.com/users/774273",
"pm_score": 2,
"selected": false,
"text": "x int[,] temp = new int[newRows, newCols];\nint minRows = Math.Min(newRows, x.GetUpperBound(0) + 1);\nint minCols = Math.Min(newCols, x.GetUpperBound(1) + 1);\nfor (int i = 0; i < minRows ; ++i)\n for (int j = 0; j < minCols; ++j)\n temp[i, j] = x[i, j];\nx = temp;\n"
},
{
"answer_id": 20665685,
"author": "Tete1805",
"author_id": 3116415,
"author_profile": "https://Stackoverflow.com/users/3116415",
"pm_score": 2,
"selected": false,
"text": "static T[] Redim<T>(T[] arr, bool preserved)\n{\n int arrLength = arr.Length;\n T[] arrRedimed = new T[arrLength + 1];\n if (preserved)\n {\n for (int i = 0; i < arrLength; i++)\n {\n arrRedimed[i] = arr[i];\n }\n }\n return arrRedimed;\n}\n static T[] Redim<T>(T[] arr, bool preserved, int nbRows)\n{\n T[] arrRedimed = new T[nbRows];\n if (preserved)\n {\n for (int i = 0; i < arr.Length; i++)\n {\n arrRedimed[i] = arr[i];\n }\n }\n return arrRedimed;\n}\n static T[,] Redim<T>(T[,] arr, bool preserved)\n{\n int Ubound0 = arr.GetUpperBound(0);\n int Ubound1 = arr.GetUpperBound(1);\n T[,] arrRedimed = new T[Ubound0 + 1, Ubound1];\n if (preserved)\n {\n for (int j = 0; j < Ubound1; j++)\n {\n for (int i = 0; i < Ubound0; i++)\n {\n arrRedimed[i, j] = arr[i, j];\n }\n }\n }\n return arrRedimed;\n}\n int[] myArr = new int[10];\nmyArr = Redim<int>(myArr, true);\n int[] myArr = new int[10];\nmyArr = Redim(myArr, true);\n"
},
{
"answer_id": 33665613,
"author": "AllDayPiano",
"author_id": 1451100,
"author_profile": "https://Stackoverflow.com/users/1451100",
"pm_score": 1,
"selected": false,
"text": "//from Applied Microsoft.NET framework Programming - Jeffrey Richter\npublic static Array RedimPreserve(Array origArray, Int32 desiredSize)\n {\n System.Type t = origArray.GetType().GetElementType();\n Array newArray = Array.CreateInstance(t, desiredSize);\n Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize));\n return newArray;\n }\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41543/"
] |
327,955 | <p>Since I started learning <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Objective_Caml" rel="noreferrer">OCaml</a> last year, I've read a huge number of articles which insist that design patterns (especially in Java) are workarounds for the missing features in imperative languages. One article I found <a href="http://www.defmacro.org/ramblings/fp.html" rel="noreferrer">makes a fairly strong claim</a>:</p>
<blockquote>
<p>Most people I've met have read
<a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">the Design Patterns book</a> by the Gang of
Four (GoF). Any self respecting programmer
will tell you that the book is
language agnostic and the patterns
apply to software engineering in
general, regardless of which language
you use. This is a noble claim.
Unfortunately it is far removed from
the truth.</p>
<p>Functional languages are extremely
expressive. <strong>In a functional language
one does not need design patterns
because the language is likely so high
level, you end up programming in
concepts that eliminate design
patterns all together.</strong></p>
</blockquote>
<p>The main features of functional programming (FP) include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.</p>
<p>Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml every day, and there are no striking differences between the patterns I use in these languages vs. the patterns I use when I write in Java.</p>
<p>Is there any truth to the claim that functional programming eliminates the need for OOP design patterns? If so, could you post or link to an example of a typical OOP design pattern and its functional equivalent?</p>
| [
{
"answer_id": 328048,
"author": "Germán",
"author_id": 17138,
"author_profile": "https://Stackoverflow.com/users/17138",
"pm_score": 3,
"selected": false,
"text": "for(int i = 0; i < myList.size(); i++) { doWhatever(myList.get(i)); }\n"
},
{
"answer_id": 405476,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "while(*from++ = *to++);"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40516/"
] |
327,982 | <p>Is it possible to write connect and open a SQL Compact 3.5 database from within MS Access 2003? I want to be able to use MS Access 2003 to manipulate data in a SQL Compact 3.5 database. If it is possible, then what statements would be used to open the database?</p>
| [
{
"answer_id": 330376,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 1,
"selected": false,
"text": "public sub connectionTest\nDim activeConnection as ADODB.connection, _\n activeRecordset as ADODB.recordset\n\nSet activeConnection = New ADODB.connection\nactiveConnection.connectionString = myCOnnectionString\nactiveConnection.open\n\nset activeRecordset = New ADODB.recordset\n'this will open a read-only recordset'\nactiveRecordset.open _\n \"SELECT * FROM myTableName\", _\n activeConnection, _\n adOpenStatic, _\n adLockReadOnly\n\nif activeRecordset.EOF and activeRecordset.BOF then\n debug.print \"No records in this table\"\nelse\n activeRecordset.moveFirst\n do while not activeRecordset.EOF\n debug.print activerecordset.fields(\"myFieldName\").value\n activeRecordset.moveNext\n loop\nendif\n\nactiveRecordset.close\nset activeRecordset = nothing\nactiveConnection.close\nset activeConnection = nothing\n\nend sub\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
327,984 | <p>Say I have an interface like this:</p>
<pre><code>public interface ISomeInterface
{
...
}
</code></pre>
<p>I also have a couple of classes implementing this interface;</p>
<pre><code>public class SomeClass : ISomeInterface
{
...
}
</code></pre>
<p>Now I have a WPF ListBox listing items of ISomeInterface, using a custom DataTemplate.</p>
<p>The databinding engine will apparently not (that I have been able to figure out) allow me to bind to interface properties - it sees that the object is a SomeClass object, and data only shows up if SomeClass should happen to have the bound property available as a non-interface property. </p>
<p>How can I tell the DataTemplate to act as if every object is an ISomeInterface, and not a SomeClass etc.?</p>
<p>Thanks!</p>
| [
{
"answer_id": 327993,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 4,
"selected": false,
"text": "public abstract class SomeClassBase\n{\n\n}\n\npublic class SomeClass : SomeClassBase\n{\n\n}\n\n<DataTemplate DataType=\"{x:Type local:SomeClassBase}\">\n <!-- ... -->\n</DataTemplate>\n"
},
{
"answer_id": 1414697,
"author": "Pieter Breed",
"author_id": 24172,
"author_profile": "https://Stackoverflow.com/users/24172",
"pm_score": 3,
"selected": false,
"text": "<DataTemplate DataType=\"{x:Type documents:ISpecificOutcome}\"\n x:Key=\"SpecificOutcomesTemplate\">\n <Label Content=\"{Binding Name}\"\n ToolTip=\"{Binding Description}\" />\n</DataTemplate>\n <ListBox ItemsSource=\"{Binding Path=SpecificOutcomes}\"\n ItemTemplate=\"{StaticResource SpecificOutcomesTemplate}\"\n >\n</ListBox>\n"
},
{
"answer_id": 1827579,
"author": "dummyboy",
"author_id": 222273,
"author_profile": "https://Stackoverflow.com/users/222273",
"pm_score": 7,
"selected": true,
"text": "{Binding Path=MyValue}\n {Binding Path=(mynamespacealias:IMyInterface.MyValue)}\n"
},
{
"answer_id": 6068621,
"author": "MikeKulls",
"author_id": 701485,
"author_profile": "https://Stackoverflow.com/users/701485",
"pm_score": 3,
"selected": false,
"text": "<Image Width=\"120\" Height=\"120\" HorizontalAlignment=\"Center\" Source=\"{Binding Path=(starbug:IPhotoItem.PhotoSmall)}\" Name=\"mainImage\"></Image>\n <Label Content=\"{Binding}\" HorizontalAlignment=\"Center\" MouseDoubleClick=\"Label_MouseDoubleClick\">\n <Label.ContentTemplate>\n <DataTemplate>\n <StackPanel>\n <Image Source=\"{Binding Path=(starbug:IPhotoItem.PhotoSmall)}\" Width=\"120\" Height=\"120\" Stretch=\"Uniform\" ></Image>\n </StackPanel>\n </DataTemplate>\n </Label.ContentTemplate>\n</Label>\n"
},
{
"answer_id": 18798743,
"author": "Mohammad Dehghan",
"author_id": 1174942,
"author_profile": "https://Stackoverflow.com/users/1174942",
"pm_score": 4,
"selected": false,
"text": "IMyInterface1 IMyInterface2 DataTemplate ItemTemplateSelector ItemsControl DataTemplate SelectTemplate DataTemplate"
},
{
"answer_id": 41709031,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 3,
"selected": false,
"text": " <TextBlock>\n <TextBlock.Text>\n <Binding Path=\"Packages[0].(myNamespace:IShippingPackage.ShippingMethod).CarrierServiceCode\"/>\n </TextBlock.Text>\n </TextBlock>\n Binding <TextBlock Text=\"{Binding Path=Packages[0].(myNamespace:IShippingPackage.ShippingMethod).CarrierServiceCode}\"/>\n <StackPanel DataContext={Binding Path=Packages[0].(myNamespace:IShippingPackage.ShippingMethod)}\">\n <TextBlock Text=\"{Binding CarrierName}\"/>\n <TextBlock Text=\"{Binding CarrierServiceCode}\"/>\n </StackPanel>\n )} Path=\"(myNameSpace:IShippingPackage.ShippingMethod)}\" Path= Path= Text=\"{Binding FirstName}\"\n Text=\"{Binding Path=FirstName}\"\n Path= System.ArgumentNullException: Key cannot be null.\nParameter name: key\n at System.Collections.Specialized.ListDictionary.get_Item(Object key)\n at System.Collections.Specialized.HybridDictionary.get_Item(Object key)\n at System.ComponentModel.PropertyChangedEventManager.RemoveListener(INotifyPropertyChanged source, String propertyName, IWeakEventListener listener, EventHandler`1 handler)\n at System.ComponentModel.PropertyChangedEventManager.RemoveHandler(INotifyPropertyChanged source, EventHandler`1 handler, String propertyName)\n at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)\n at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)\n <TextBlock Text=\"{Binding Packages[0].(myNamespace:IShippingPackage.ShippingMethod).CarrierServiceCode}\"/>\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122/"
] |
327,985 | <p>The last line of my file is:</p>
<blockquote>
<p>29-dez,40,</p>
</blockquote>
<p>How can I modify that line so that it reads:</p>
<blockquote>
<p>29-Dez,40,90,100,50</p>
</blockquote>
<p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p>
<p>I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.</p>
| [
{
"answer_id": 328007,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 3,
"selected": false,
"text": "f = open(\"foo.file\", \"wb\")\nf.seek(-len(os.linesep), os.SEEK_END) \nf.write(\"new text at end of last line\" + os.linesep)\nf.close() \n"
},
{
"answer_id": 328196,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/python\n\nMYFILE=\"file.txt\"\n\n# read the file into a list of lines\nlines = open(MYFILE, 'r').readlines()\n\n# now edit the last line of the list of lines\nnew_last_line = (lines[-1].rstrip() + \",90,100,50\")\nlines[-1] = new_last_line\n\n# now write the modified list back out to the file\nopen(MYFILE, 'w').writelines(lines)\n"
},
{
"answer_id": 339388,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "import os\nfrom mmap import mmap\n\ndef insert_import(filename, text):\n if len(text) < 1:\n return\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(filename))\n origSize = m.size()\n m.resize(origSize + len(text))\n pos = 0\n while True:\n l = m.readline()\n if l.startswith(('import', 'from')):\n continue\n else:\n pos = m.tell() - len(l)\n break\n m[pos+len(text):] = m[pos:origSize]\n m[pos:pos+len(text)] = text\n m.close()\n f.close()\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41795/"
] |
327,986 | <p>I still have a large number of floppies. On some of them there probably is source code I don't want to lose. I also don't want to take look at each one individually, as that's going to take a lot of time. What software would be best for copying all data to a hard disk, preferably while creating an index at the same time?</p>
<p>I would also be interested in imaging mac floppies, but it doesn't have to be on the same machine.</p>
<p>[responses]<br>
The goal is to finally get rid of all those boxes with floppies. I was asking about images as xcopy doesn't copy all (hidden?) sectors, does it? Is xxcopy better?</p>
<p>I don't want to type a name for each floppy. </p>
<p>Disk Utility on the mac probably needs a bit too much keyboard or mouse action, but might be appescriptable</p>
| [
{
"answer_id": 328016,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 4,
"selected": true,
"text": "#!/bin/bash\n\nfloppydev='/dev/sdb'\nsavepath='/srv/floppy_imgs'\nwhile true\ndo\n echo \"Press a key to create an image of the next floppy\"\n read -n 1\n\n dd if=$floppydev of=/dev/null count=1 2> /dev/null\n errlvl=$?\n #if the disk isn't in the drive then wait\n while [ $errlvl -ne 0 ]\n do\n sleep 1\n dd if=$floppydev of=/dev/null count=1 2> /dev/null\n errlvl=$?\n done\n\n filename=$(date +'img-%Y%m%d-%H%M%S.flp')\n\n if [ ! -f $savepath/$filename ]\n then\n echo \"creating image as $filename\"\n dd if=$floppydev of=$savepath/$filename\n errlvl=$?\n\n if [ $errlvl -ne 0 ]\n then\n echo 'the image copy failed!'\n rm -i $savepath/$filename\n else\n mlabel -s -i $savepath/$filename ::\n md5sum $savepath/$filename > $savepath/$filename.md5\n echo \"copy complete\"\n echo \" \"\n fi\n fi\n\ndone\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/327986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35306/"
] |
328,005 | <p>If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function</p>
<p>For example:</p>
<pre><code>void DoSqlStuff()
{
SqlConnection sqlConn = new SqlConnection(...);
SqlCommand cmd = new SqlCommand(...);
SqlDataReader sqlData= null;
sqlConn,Open();
sqlData = cmd.ExecutReader();
while(sqlData.Read())
{
...
}
}
</code></pre>
<p>Is it optional, recommended or mandatory to close SqlConn and SqlData?</p>
<p>Thanks.</p>
| [
{
"answer_id": 328011,
"author": "Kevin Tighe",
"author_id": 39461,
"author_profile": "https://Stackoverflow.com/users/39461",
"pm_score": 6,
"selected": true,
"text": "using (SqlConnection cn = new SqlConnection(connectionString))\n{ \n SqlCommand cm = new SqlCommand(commandString, cn)\n cn.Open();\n cm.ExecuteNonQuery(); \n}\n"
},
{
"answer_id": 328499,
"author": "cweston",
"author_id": 37966,
"author_profile": "https://Stackoverflow.com/users/37966",
"pm_score": 1,
"selected": false,
"text": "using SqlConnection conn = null;\ntry\n{\n //create connection\n\n SqlCommand cmd = null;\n try\n {\n //create command\n\n SqlDataReader reader = null;\n try \n {\n //create reader\n }\n finally\n {\n reader.Dispose();\n }\n }\n finally\n {\n cmd.Dispose();\n }\n}\nfinally \n{\n conn.Dispose();\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37955/"
] |
328,017 | <p>How can I programatically get the path to MSBuild from a machine where my .exe is running?</p>
<p>I can get the .NET version from the Environment but is there a way of getting the correct folder for a .NET version?</p>
| [
{
"answer_id": 328133,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 8,
"selected": true,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\2.0\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\3.5\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0\n reg.exe query \"HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0\" /v MSBuildToolsPath\n dir HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\\n"
},
{
"answer_id": 350513,
"author": "Paulo Santos",
"author_id": 44375,
"author_profile": "https://Stackoverflow.com/users/44375",
"pm_score": 3,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\2.0\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\3.5\n %ProgramFiles%\\MSBuild\n"
},
{
"answer_id": 13478773,
"author": "AllenSanborn",
"author_id": 92364,
"author_profile": "https://Stackoverflow.com/users/92364",
"pm_score": 5,
"selected": false,
"text": "# valid versions are [2.0, 3.5, 4.0]\n$dotNetVersion = \"4.0\"\n$regKey = \"HKLM:\\software\\Microsoft\\MSBuild\\ToolsVersions\\$dotNetVersion\"\n$regProperty = \"MSBuildToolsPath\"\n\n$msbuildExe = join-path -path (Get-ItemProperty $regKey).$regProperty -childpath \"msbuild.exe\"\n\n&$msbuildExe\n"
},
{
"answer_id": 13752506,
"author": "yoyo",
"author_id": 503688,
"author_profile": "https://Stackoverflow.com/users/503688",
"pm_score": 5,
"selected": false,
"text": "set msbuild.exe=\nfor /D %%D in (%SYSTEMROOT%\\Microsoft.NET\\Framework\\v4*) do set msbuild.exe=%%D\\MSBuild.exe\n if not defined msbuild.exe echo error: can't find MSBuild.exe & goto :eof\nif not exist \"%msbuild.exe%\" echo error: %msbuild.exe%: not found & goto :eof\n"
},
{
"answer_id": 15446618,
"author": "Nikolay Botev",
"author_id": 649257,
"author_profile": "https://Stackoverflow.com/users/649257",
"pm_score": 7,
"selected": false,
"text": "reg.exe query \"HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0\" /v MSBuildToolsPath\n"
},
{
"answer_id": 20431996,
"author": "JJS",
"author_id": 26877,
"author_profile": "https://Stackoverflow.com/users/26877",
"pm_score": 4,
"selected": false,
"text": "@echo off\n\nreg.exe query \"HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0\" /v MSBuildToolsPath > nul 2>&1\nif ERRORLEVEL 1 goto MissingMSBuildRegistry\n\nfor /f \"skip=2 tokens=2,*\" %%A in ('reg.exe query \"HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0\" /v MSBuildToolsPath') do SET \"MSBUILDDIR=%%B\"\n\nIF NOT EXIST \"%MSBUILDDIR%\" goto MissingMSBuildToolsPath\nIF NOT EXIST \"%MSBUILDDIR%msbuild.exe\" goto MissingMSBuildExe\n\nexit /b 0\n\ngoto:eof\n::ERRORS\n::---------------------\n:MissingMSBuildRegistry\necho Cannot obtain path to MSBuild tools from registry\ngoto:eof\n:MissingMSBuildToolsPath\necho The MSBuild tools path from the registry '%MSBUILDDIR%' does not exist\ngoto:eof\n:MissingMSBuildExe\necho The MSBuild executable could not be found at '%MSBUILDDIR%'\ngoto:eof\n @echo off\ncall msbuildpath.bat\n\"%MSBUILDDIR%msbuild.exe\" foo.csproj /p:Configuration=Release\n build.cmd Release Foo.csproj\n @echo off\nsetlocal\nif \"%PROCESSOR_ARCHITECTURE%\"==\"x86\" set PROGRAMS=%ProgramFiles%\nif defined ProgramFiles(x86) set PROGRAMS=%ProgramFiles(x86)%\nfor %%e in (Community Professional Enterprise) do (\n if exist \"%PROGRAMS%\\Microsoft Visual Studio\\2017\\%%e\\MSBuild\\15.0\\Bin\\MSBuild.exe\" (\n set \"MSBUILD=%PROGRAMS%\\Microsoft Visual Studio\\2017\\%%e\\MSBuild\\15.0\\Bin\\MSBuild.exe\"\n )\n)\nif exist \"%MSBUILD%\" goto :restore\nset MSBUILD=\nfor %%i in (MSBuild.exe) do set MSBUILD=%%~dpnx$PATH:i\nif not defined MSBUILD goto :nomsbuild\nset MSBUILD_VERSION_MAJOR=\nset MSBUILD_VERSION_MINOR=\nfor /f \"delims=. tokens=1,2,3,4\" %%m in ('msbuild /version /nologo') do (\n set MSBUILD_VERSION_MAJOR=%%m\n set MSBUILD_VERSION_MINOR=%%n\n)\nif not defined MSBUILD_VERSION_MAJOR goto :nomsbuild\nif not defined MSBUILD_VERSION_MINOR goto :nomsbuild\nif %MSBUILD_VERSION_MAJOR% lss 15 goto :nomsbuild\nif %MSBUILD_VERSION_MINOR% lss 1 goto :nomsbuild\n:restore\nfor %%i in (NuGet.exe) do set nuget=%%~dpnx$PATH:i\nif \"%nuget%\"==\"\" (\n echo WARNING! NuGet executable not found in PATH so build may fail!\n echo For more on NuGet, see https://github.com/nuget/home\n)\npushd \"%~dp0\"\nnuget restore ^\n && call :build Debug %* ^\n && call :build Release %*\npopd\ngoto :EOF\n\n:build\nsetlocal\n\"%MSBUILD%\" /p:Configuration=%1 /v:m %2 %3 %4 %5 %6 %7 %8 %9\ngoto :EOF\n\n:nomsbuild\necho Microsoft Build version 15.1 (or later) does not appear to be\necho installed on this machine, which is required to build the solution.\nexit /b 1\n"
},
{
"answer_id": 31404176,
"author": "MovGP0",
"author_id": 601990,
"author_profile": "https://Stackoverflow.com/users/601990",
"pm_score": 2,
"selected": false,
"text": "dir HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\\n"
},
{
"answer_id": 32370545,
"author": "hdev",
"author_id": 1776231,
"author_profile": "https://Stackoverflow.com/users/1776231",
"pm_score": 5,
"selected": false,
"text": "MSBuildToolsPath Resolve-Path HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\* | \nGet-ItemProperty -Name MSBuildToolsPath\n MSBuildToolsPath : C:\\Program Files (x86)\\MSBuild\\12.0\\bin\\amd64\\\nPSPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\12.0\nPSParentPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\nPSChildName : 12.0\nPSDrive : HKLM\nPSProvider : Microsoft.PowerShell.Core\\Registry\n\nMSBuildToolsPath : C:\\Program Files (x86)\\MSBuild\\14.0\\bin\\amd64\\\nPSPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0\nPSParentPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\nPSChildName : 14.0\nPSDrive : HKLM\nPSProvider : Microsoft.PowerShell.Core\\Registry\n\nMSBuildToolsPath : C:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727\\\nPSPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\2.0\nPSParentPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\nPSChildName : 2.0\nPSDrive : HKLM\nPSProvider : Microsoft.PowerShell.Core\\Registry\n\nMSBuildToolsPath : C:\\Windows\\Microsoft.NET\\Framework64\\v3.5\\\nPSPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\3.5\nPSParentPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\nPSChildName : 3.5\nPSDrive : HKLM\nPSProvider : Microsoft.PowerShell.Core\\Registry\n\nMSBuildToolsPath : C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\\nPSPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0\nPSParentPath : Microsoft.PowerShell.Core\\Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\nPSChildName : 4.0\nPSDrive : HKLM\nPSProvider : Microsoft.PowerShell.Core\\Registry\n Resolve-Path \"C:\\Program Files (x86)\\MSBuild\\*\\Bin\\amd64\\MSBuild.exe\"\nResolve-Path \"C:\\Program Files (x86)\\MSBuild\\*\\Bin\\MSBuild.exe\"\n Path\n----\nC:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\amd64\\MSBuild.exe\nC:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\amd64\\MSBuild.exe\nC:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\MSBuild.exe\nC:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe\n"
},
{
"answer_id": 32480723,
"author": "draganicimw",
"author_id": 3876532,
"author_profile": "https://Stackoverflow.com/users/3876532",
"pm_score": 2,
"selected": false,
"text": "cmd> where MSBuild\nSample result: C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\n"
},
{
"answer_id": 43623213,
"author": "Raman Zhylich",
"author_id": 1095822,
"author_profile": "https://Stackoverflow.com/users/1095822",
"pm_score": 3,
"selected": false,
"text": "function Get-MSBuild-Path {\n\n $vs14key = \"HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\14.0\"\n $vs15key = \"HKLM:\\SOFTWARE\\wow6432node\\Microsoft\\VisualStudio\\SxS\\VS7\"\n\n $msbuildPath = \"\"\n\n if (Test-Path $vs14key) {\n $key = Get-ItemProperty $vs14key\n $subkey = $key.MSBuildToolsPath\n if ($subkey) {\n $msbuildPath = Join-Path $subkey \"msbuild.exe\"\n }\n }\n\n if (Test-Path $vs15key) {\n $key = Get-ItemProperty $vs15key\n $subkey = $key.\"15.0\"\n if ($subkey) {\n $msbuildPath = Join-Path $subkey \"MSBuild\\15.0\\bin\\amd64\\msbuild.exe\"\n }\n }\n\n return $msbuildPath\n\n}\n"
},
{
"answer_id": 45764269,
"author": "cowlinator",
"author_id": 1698736,
"author_profile": "https://Stackoverflow.com/users/1698736",
"pm_score": 3,
"selected": false,
"text": "C:\\windows\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe (v2.0.50727.8745 32-bit)\nC:\\windows\\Microsoft.NET\\Framework64\\v2.0.50727\\MSBuild.exe (v2.0.50727.8745 64-bit)\nC:\\Windows\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe (v3.5.30729.8763 32-bit)\nC:\\Windows\\Microsoft.NET\\Framework64\\v3.5\\MSBuild.exe (v3.5.30729.8763 64-bit)\nC:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe (v4.7.2053.0 32-bit)\nC:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\MSBuild.exe (v4.7.2053.0 64-bit)\nC:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\MSBuild.exe (v12.0.21005.1 32-bit)\nC:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\amd64\\MSBuild.exe (v12.0.21005.1 64-bit)\nC:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe (v14.0.25420.1 32-bit)\nC:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\amd64\\MSBuild.exe (v14.0.25420.1 64-bit)\nC:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\MSBuild\\15.0\\Bin\\MSBuild.exe (v15.1.1012+g251a9aec17 32-bit)\nC:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\MSBuild\\15.0\\Bin\\amd64\\MSBuild.exe (v15.1.1012+g251a9aec17 64-bit)\nC:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\{LicenceName}\\MSBuild\\Bin\\MSBuild.exe (v15.1.1012.6693 32-bit)\nC:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\{LicenceName}\\MSBuild\\Bin\\amd64\\MSBuild.exe (v15.1.1012.6693 64-bit)\n"
},
{
"answer_id": 47942899,
"author": "Roi Danton",
"author_id": 4566599,
"author_profile": "https://Stackoverflow.com/users/4566599",
"pm_score": 2,
"selected": false,
"text": "set regKey=HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\SxS\\VS7\nset regValue=15.0\nfor /f \"skip=2 tokens=3,*\" %%A in ('reg.exe query %regKey% /v %regValue% 2^>nul') do (\n set vs17path=%%A %%B\n)\nset msbuild15path = %vs17path%\\MSBuild\\15.0\\Bin\\MSBuild.exe\n"
},
{
"answer_id": 53094005,
"author": "SeriousM",
"author_id": 660428,
"author_profile": "https://Stackoverflow.com/users/660428",
"pm_score": 3,
"selected": false,
"text": "(Resolve-Path ([io.path]::combine(${env:ProgramFiles(x86)}, 'Microsoft Visual Studio', '*', '*', 'MSBuild', '*' , 'bin' , 'msbuild.exe'))).Path C:\\Program Files (x86)\\Microsoft Visual Studio\\*\\*\\MSBuild\\*\\bin\\msbuild.exe"
},
{
"answer_id": 53296236,
"author": "Ernstjan Freriks",
"author_id": 3883467,
"author_profile": "https://Stackoverflow.com/users/3883467",
"pm_score": 0,
"selected": false,
"text": "FOR /F \"tokens=* USEBACKQ\" %%F IN (`where /r \"%PROGRAMFILES(x86)%\\Microsoft Visual \nStudio\\2017\" msbuild.exe ^| findstr /v /i \"amd64\"`) DO (SET msbuildpath=%%F)\n"
},
{
"answer_id": 53319707,
"author": "Ian Kemp",
"author_id": 70345,
"author_profile": "https://Stackoverflow.com/users/70345",
"pm_score": 6,
"selected": false,
"text": "&\"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\Installer\\vswhere.exe\" -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\\**\\Bin\\MSBuild.exe \"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\" -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\\**\\Bin\\MSBuild.exe &\"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\Installer\\vswhere.exe\" -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\\IDE\\CommonExtensions\\Microsoft\\TestWindow\\vstest.console.exe \"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\" -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\\IDE\\CommonExtensions\\Microsoft\\TestWindow\\vstest.console.exe -prerelease -products * vswhere vswhere %ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe -find vswhere %ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe vswhere.exe vswhere"
},
{
"answer_id": 54299916,
"author": "Shamork.Fu",
"author_id": 6873036,
"author_profile": "https://Stackoverflow.com/users/6873036",
"pm_score": 0,
"selected": false,
"text": "@echo off\nsetlocal\nif \"%PROCESSOR_ARCHITECTURE%\"==\"x86\" set PROGRAMS=%ProgramFiles%\nif defined ProgramFiles(x86) set PROGRAMS=%ProgramFiles(x86)%\nfor %%e in (Community Professional Enterprise) do (\n if exist \"%PROGRAMS%\\Microsoft Visual Studio\\2017\\%%e\\MSBuild\\15.0\\Bin\\MSBuild.exe\" (\n set \"MSBUILD=%PROGRAMS%\\Microsoft Visual Studio\\2017\\%%e\\MSBuild\\15.0\\Bin\\MSBuild.exe\"\n )\n)\nif exist \"%MSBUILD%\" goto :build\n\nfor /f \"usebackq tokens=1* delims=: \" %%i in (`\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\" -latest -requires Microsoft.Component.MSBuild`) do (\n if /i \"%%i\"==\"installationPath\" set InstallDir=%%j\n)\n\nif exist \"%InstallDir%\\MSBuild\\15.0\\Bin\\MSBuild.exe\" (\n set \"MSBUILD=%InstallDir%\\MSBuild\\15.0\\Bin\\MSBuild.exe\"\n)\nif exist \"%MSBUILD%\" goto :build\nset MSBUILD=\nfor %%i in (MSBuild.exe) do set MSBUILD=%%~dpnx$PATH:i\nif not defined MSBUILD goto :nomsbuild\nset MSBUILD_VERSION_MAJOR=\nset MSBUILD_VERSION_MINOR=\nfor /f \"delims=. tokens=1,2,3,4\" %%m in ('msbuild /version /nologo') do (\n set MSBUILD_VERSION_MAJOR=%%m\n set MSBUILD_VERSION_MINOR=%%n\n)\necho %MSBUILD_VERSION_MAJOR% %MSBUILD_VERSION_MINOR%\nif not defined MSBUILD_VERSION_MAJOR goto :nomsbuild\nif not defined MSBUILD_VERSION_MINOR goto :nomsbuild\nif %MSBUILD_VERSION_MAJOR% lss 15 goto :nomsbuild\nif %MSBUILD_VERSION_MINOR% lss 1 goto :nomsbuild\n:restore\nfor %%i in (NuGet.exe) do set nuget=%%~dpnx$PATH:i\nif \"%nuget%\"==\"\" (\n echo WARNING! NuGet executable not found in PATH so build may fail!\n echo For more on NuGet, see https://github.com/nuget/home\n)\npushd \"%~dp0\"\npopd\ngoto :EOF\n\n:build\nsetlocal\n\"%MSBUILD%\" -restore -maxcpucount %1 /p:Configuration=%2 /v:m %3 %4 %5 %6 %7 %8 %9\ngoto :EOF\n\n:nomsbuild\necho Microsoft Build version 15.1 (or later) does not appear to be\necho installed on this machine, which is required to build the solution.\nexit /b 1\n"
},
{
"answer_id": 56455986,
"author": "Stas BZ",
"author_id": 3540044,
"author_profile": "https://Stackoverflow.com/users/3540044",
"pm_score": 0,
"selected": false,
"text": "function Get-MsBuild-Path\n{\n $msbuildPathes = $null\n $ptrSize = [System.IntPtr]::Size\n switch ($ptrSize) {\n 4 {\n $msbuildPathes =\n @(Resolve-Path \"${Env:ProgramFiles(x86)}\\Microsoft Visual Studio\\*\\*\\MSBuild\\*\\Bin\\msbuild.exe\" -ErrorAction SilentlyContinue) +\n @(Resolve-Path \"${Env:ProgramFiles(x86)}\\MSBuild\\*\\Bin\\MSBuild.exe\" -ErrorAction SilentlyContinue) +\n @(Resolve-Path \"${Env:windir}\\Microsoft.NET\\Framework\\*\\MSBuild.exe\" -ErrorAction SilentlyContinue)\n }\n 8 {\n $msbuildPathes =\n @(Resolve-Path \"${Env:ProgramFiles(x86)}\\Microsoft Visual Studio\\*\\*\\MSBuild\\*\\Bin\\amd64\\msbuild.exe\" -ErrorAction SilentlyContinue) +\n @(Resolve-Path \"${Env:ProgramFiles(x86)}\\MSBuild\\*\\Bin\\amd64\\MSBuild.exe\" -ErrorAction SilentlyContinue) +\n @(Resolve-Path \"${Env:windir}\\Microsoft.NET\\Framework64\\*\\MSBuild.exe\" -ErrorAction SilentlyContinue)\n }\n default {\n throw ($msgs.error_unknown_pointersize -f $ptrSize)\n }\n }\n\n $latestMSBuildPath = $null\n $latestVersion = $null\n foreach ($msbuildFile in $msbuildPathes)\n {\n $msbuildPath = $msbuildFile.Path\n $versionOutput = & $msbuildPath -version\n $fileVersion = (New-Object System.Version($versionOutput[$versionOutput.Length - 1]))\n if (!$latestVersion -or $latestVersion -lt $fileVersion)\n {\n $latestVersion = $fileVersion\n $latestMSBuildPath = $msbuildPath\n }\n }\n\n Write-Host \"MSBuild version detected: $latestVersion\" -Foreground Yellow\n Write-Host \"MSBuild path: $latestMSBuildPath\" -Foreground Yellow\n\n return $latestMSBuildPath;\n}\n"
},
{
"answer_id": 56474589,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 1,
"selected": false,
"text": "function Find-MsBuild {\n Write-Host \"Using VSWhere to find msbuild...\"\n $path = & $vswhere -latest -requires Microsoft.Component.MSBuild -find MSBuild\\**\\Bin\\MSBuild.exe | select-object -first 1\n\n if (!$path) {\n Write-Host \"No results from VSWhere, using registry key query to find msbuild (note this will find pre-VS2017 versions)...\"\n $path = Resolve-Path HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\* |\n Get-ItemProperty -Name MSBuildToolsPath |\n sort -Property @{ Expression={ [double]::Parse($_.PSChildName) }; Descending=$true } |\n select -exp MSBuildToolsPath -First 1 |\n Join-Path -ChildPath \"msbuild.exe\"\n }\n\n if (!$path) {\n throw \"Unable to find path to msbuild.exe\"\n }\n\n if (!(Test-Path $path)) {\n throw \"Found path to msbuild as $path, but file does not exist there\"\n }\n\n Write-Host \"Using MSBuild at $path...\"\n return $path\n}\n"
},
{
"answer_id": 57214958,
"author": "Martin Brandl",
"author_id": 1163423,
"author_profile": "https://Stackoverflow.com/users/1163423",
"pm_score": 2,
"selected": false,
"text": "Get-ChildItem 'HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' | \n Get-ItemProperty -Name MSBuildToolsPath | \n Sort-Object PSChildName | \n Select-Object -ExpandProperty MSBuildToolsPath -first 1\n"
},
{
"answer_id": 57930729,
"author": "Mariano Desanze",
"author_id": 146513,
"author_profile": "https://Stackoverflow.com/users/146513",
"pm_score": 1,
"selected": false,
"text": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Professional\\MSBuild\\15.0\\Bin\\MSBuild.exe\n C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe\n Function GetMsBuildPath {\n\n Function GetMsBuildPathFromVswhere {\n # Based on https://github.com/microsoft/vswhere/wiki/Find-MSBuild/62adac8eb22431fa91d94e03503d76d48a74939c\n $vswhere = \"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\n $path = & $vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath\n if ($path) {\n $tool = join-path $path 'MSBuild\\Current\\Bin\\MSBuild.exe'\n if (test-path $tool) {\n return $tool\n }\n $tool = join-path $path 'MSBuild\\15.0\\Bin\\MSBuild.exe'\n if (test-path $tool) {\n return $tool\n }\n }\n }\n\n Function GetMsBuildPathFromRegistry {\n # Based on Martin Brandl's answer: https://stackoverflow.com/a/57214958/146513\n $msBuildDir = Get-ChildItem 'HKLM:\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' |\n Get-ItemProperty -Name MSBuildToolsPath |\n Sort-Object PSChildName |\n Select-Object -ExpandProperty MSBuildToolsPath -last 1\n $msBuildPath = join-path $msBuildDir 'msbuild.exe'\n if (test-path $msBuildPath) {\n return $msBuildPath\n }\n }\n\n $msBuildPath = GetMsBuildPathFromVswhere\n if (-Not $msBuildPath) {\n $msBuildPath = GetMsBuildPathFromRegistry\n }\n return $msBuildPath\n}\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11755/"
] |
328,020 | <p>I am trying to input data from a .txt file into a scheme structure. Each element is separated by a tab in the data file and each structure set is on a new line. I want to be able to read in the data from one line into a structure and make a list of each structure set in the file. Any suggestions?</p>
| [
{
"answer_id": 331048,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 2,
"selected": false,
"text": "(require (planet neil/csv:1:2/csv))\n (require (planet \"csv.ss\" (\"neil\" \"csv.plt\" 1 (= 1))))\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,023 | <p>I've noticed on bank websites, etc, my user IDs aren't saved (they don't appear in a dropdown like other commonly entered stuff does) and there's no prompt for it to remember your password. How is this done? How do the sites notify the browser that they are in 'special' or else exceptions? Just curious.</p>
| [
{
"answer_id": 328029,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "<input type=\"password\" autocomplete=\"off\" />\n"
},
{
"answer_id": 32861451,
"author": "Shyam Sharma",
"author_id": 2424613,
"author_profile": "https://Stackoverflow.com/users/2424613",
"pm_score": 0,
"selected": false,
"text": " $(document).ready(function () { $('input[autocomplete=\"off\"]').each(function () {\n\n var input = this;\n var name = $(input).attr('name');\n var id = $(input).attr('id');\n\n $(input).removeAttr('name');\n $(input).removeAttr('id');\n\n setTimeout(function () {\n\n $(input).attr('name', name);\n $(input).attr('id', id);\n }, 1);\n });\n });\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37014/"
] |
328,025 | <p>I have an enum </p>
<pre><code>public enum FileExtentions {
mp3,
mpeg
}
</code></pre>
<p>And I have a FileInfo of which I want to check if the extension is in the previous enum.
I was hoping I could do a </p>
<pre><code>FileExtensions.Any(e=>e.ToString().Equals(file.Extension));
</code></pre>
<p>But that would have been too awesome.
Any ideas?</p>
| [
{
"answer_id": 328031,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 3,
"selected": false,
"text": "Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals(\".\"+file.Extension))\n"
},
{
"answer_id": 328034,
"author": "Jeff Donnici",
"author_id": 821,
"author_profile": "https://Stackoverflow.com/users/821",
"pm_score": 0,
"selected": false,
"text": "string extension = Enum.GetName(typeof(FileExtensions), FileExtensions.mp3);\n\nif (extension == file.Extension)\n // do something here\n"
},
{
"answer_id": 328198,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 1,
"selected": false,
"text": "public static bool HasExtension(this FileInfo file)\n{\n var ext = file.Extension.StartsWith(\".\") ? file.Extension.Substring(1) \n : file.Extension;\n\n return Enum.GetNames(typeof(FileExtensions))\n .Any(f => f.Equals(ext));\n}\n bool hasExtension = file.HasExtension();\n"
},
{
"answer_id": 328275,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "Any Equals Contains bool result = Enum.GetNames(typeof(FileExtensions)).Contains(\"mp3\");\n"
},
{
"answer_id": 328304,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "Enum.IsDefined(typeof(FileExtension), file.Extension.Substring(1).ToLower())\n IEnumerable<string> GetNames(this Type t) {\n if (!t.IsEnum) throw new ArgumentException();\n\n return Enum.GetNames(t);\n}\n\ntypeof(FileExtensions).GetNames().Any(e=>e.ToString().Equals(file.Extension));\n bool IsDefined(this Type t, string name) {\n if (!t.IsEnum) throw new ArgumentException();\n\n return Enum.IsDefined(t, name);\n}\n\ntypeof(FileExtension).IsDefined(file.Extension);\n"
},
{
"answer_id": 13525470,
"author": "Срба",
"author_id": 1548022,
"author_profile": "https://Stackoverflow.com/users/1548022",
"pm_score": 0,
"selected": false,
"text": "if (Enum.IsDefined(typeof(FileExtentions), file.Extension))\n"
},
{
"answer_id": 58894132,
"author": "Ali Karaca",
"author_id": 1417214,
"author_profile": "https://Stackoverflow.com/users/1417214",
"pm_score": 0,
"selected": false,
"text": "Enum.IsDefined(Type, Object)\n Enum.IsDefined(typeof(FileExtentions), FileInfo)\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
328,041 | <p>I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.</p>
<p>The existing C application works fine but I want to have a single script I can maintain for all platforms. At the same time, I do not want to lose a lot of performance but am willing to lose some.</p>
<p>Startup cost of the script is very important. This script can be called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important.</p>
<p>So basically I'm looking for the best scripting languages that is:</p>
<ul>
<li>Cross platform.</li>
<li>Capable of XML parsing and HTTP Posts.</li>
<li>Low memory and low startup time.</li>
</ul>
<p>Possible choices include but are not limited to: bash/ksh + curl, Perl, Python and Ruby. What would you recommend for this type of a scenario?</p>
| [
{
"answer_id": 328159,
"author": "Becca Royal-Gordon",
"author_id": 41222,
"author_profile": "https://Stackoverflow.com/users/41222",
"pm_score": 2,
"selected": false,
"text": "Dagny:~ brent$ time perl -MCGI -e0\n\nreal 0m0.610s\nuser 0m0.036s\nsys 0m0.022s\nDagny:~ brent$ time perl -MCGI -e0\n\nreal 0m0.026s\nuser 0m0.020s\nsys 0m0.006s\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5077/"
] |
328,044 | <p>I have a database table with a large number of rows and one numeric column, and I want to represent this data in memory. I could just use one big integer array and this would be very fast, but the number of rows could be too large for this.</p>
<p>Most of the rows (more than 99%) have a value of zero. Is there an effective data structure I could use that would only allocate memory for rows with non-zero values and would be nearly as fast as an array?</p>
<p>Update: as an example, one thing I tried was a Hashtable, reading the original table and adding any non-zero values, keyed by the row number in the original table. I got the value with a function that returned 0 if the requested index wasn't found, or else the value in the Hashtable. This works but is slow as dirt compared to a regular array - I might not be doing it right.</p>
<p><strong>Update 2: here is sample code.</strong></p>
<pre><code>private Hashtable _rowStates;
private void SetRowState(int rowIndex, int state)
{
if (_rowStates.ContainsKey(rowIndex))
{
if (state == 0)
{
_rowStates.Remove(rowIndex);
}
else
{
_rowStates[rowIndex] = state;
}
}
else
{
if (state != 0)
{
_rowStates.Add(rowIndex, state);
}
}
}
private int GetRowState(int rowIndex)
{
if (_rowStates.ContainsKey(rowIndex))
{
return (int)_rowStates[rowIndex];
}
else
{
return 0;
}
}
</code></pre>
| [
{
"answer_id": 328053,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 1,
"selected": false,
"text": "ContainsKey TryGetValue"
},
{
"answer_id": 328201,
"author": "milot",
"author_id": 22637,
"author_profile": "https://Stackoverflow.com/users/22637",
"pm_score": 0,
"selected": false,
"text": "List<int> myList = new List<int>();\n public class MyDbFields\n{\n public MyDbFields(int count, int nonzero)\n {\n Count = count;\n NonZero = nonzero;\n }\n\n public int Count { get; set; }\n public int NonZero { get; set; }\n}\n List<MyDbFields> fields_list = new List<MyDbFields>();\n fields_list.Add(new MyDbFields(100, 11));\n"
},
{
"answer_id": 328346,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "Dictionary<int, int>"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| [
{
"answer_id": 328068,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 8,
"selected": true,
"text": "List = open(\"filename.txt\").readlines()\n"
},
{
"answer_id": 328070,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 4,
"selected": false,
"text": "my_list = [line.split(',') for line in open(\"filename.txt\")]\n"
},
{
"answer_id": 328072,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "myFile= open( \"SomeFile.txt\", \"r\" )\nfor x in myFile:\n print x\nmyFile.close()\n myFile= open( \"SomeFile.txt\", \"r\" )\nmyLines = list( myFile )\nmyFile.close()\nprint len(myLines), myLines\n someList[i] someList.append(i) List list"
},
{
"answer_id": 328073,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 1,
"selected": false,
"text": "[ list.split(\",\") for line in file ]\n"
},
{
"answer_id": 328074,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": false,
"text": "l = []\nfor line in in_file:\n l.append(line.split(','))\n l = []\nfor line in in_file:\n l.append(line.rstrip().split(','))\n"
},
{
"answer_id": 31923407,
"author": "Absulit",
"author_id": 507186,
"author_profile": "https://Stackoverflow.com/users/507186",
"pm_score": 6,
"selected": false,
"text": "lines_list = open('file.txt').read().splitlines()\n"
},
{
"answer_id": 45547078,
"author": "Jonathan Koren",
"author_id": 4453469,
"author_profile": "https://Stackoverflow.com/users/4453469",
"pm_score": 1,
"selected": false,
"text": "map(str.strip, open('filename').readlines())\n"
},
{
"answer_id": 73239892,
"author": "Andre Nevares",
"author_id": 12065399,
"author_profile": "https://Stackoverflow.com/users/12065399",
"pm_score": 0,
"selected": false,
"text": "\\n with open('your_file.txt') as f:\n list= f.read().splitlines() \n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41795/"
] |
328,061 | <p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
| [
{
"answer_id": 328067,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 7,
"selected": true,
"text": "image = pygame.Surface([640,480], pygame.SRCALPHA, 32)\nimage = image.convert_alpha()\n"
},
{
"answer_id": 353739,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 5,
"selected": false,
"text": "surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple\n"
},
{
"answer_id": 64512639,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 2,
"selected": false,
"text": "set_colorkey() my_surface.set_colorkey((0, 0, 0))\n SRCALPHA my_surface = pygame.Surface((width, height), pygame.SRCALPHA)\n convert_alpha() convert_alpha() my_surface = pygame.Surface((width, height))\nmy_surface = my_surface.convert_alpha()\nmy_surface.fill((0, 0, 0, 0))\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
] |
328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| [
{
"answer_id": 328110,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 5,
"selected": false,
"text": "b-a c-a 0 c a b a b def is_on(a, b, c):\n \"Return true iff point c intersects the line segment from a to b.\"\n # (or the degenerate case that all 3 points are coincident)\n return (collinear(a, b, c)\n and (within(a.x, c.x, b.x) if a.x != b.x else \n within(a.y, c.y, b.y)))\n\ndef collinear(a, b, c):\n \"Return true iff a, b, and c all lie on the same line.\"\n return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)\n\ndef within(p, q, r):\n \"Return true iff q is between p and r (inclusive).\"\n return p <= q <= r or r <= q <= p\n and if a.x != b.x else"
},
{
"answer_id": 328122,
"author": "Cyrille Ka",
"author_id": 39622,
"author_profile": "https://Stackoverflow.com/users/39622",
"pm_score": 8,
"selected": true,
"text": "def isBetween(a, b, c):\n crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)\n\n # compare versus epsilon for floating point values, or != 0 if using integers\n if abs(crossproduct) > epsilon:\n return False\n\n dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)\n if dotproduct < 0:\n return False\n\n squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)\n if dotproduct > squaredlengthba:\n return False\n\n return True\n"
},
{
"answer_id": 328126,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "# epsilon = small constant\n\ndef isBetween(a, b, c):\n lengthca2 = (c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y)\n lengthba2 = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)\n if lengthca2 > lengthba2: return False\n dotproduct = (c.x - a.x)*(b.x - a.x) + (c.y - a.y)*(b.y - a.y)\n if dotproduct < 0.0: return False\n if abs(dotproduct*dotproduct - lengthca2*lengthba2) > epsilon: return False \n return True\n"
},
{
"answer_id": 328154,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 3,
"selected": false,
"text": "ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)\nac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)\nbc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)\n is_on_segment = abs(ac + bc - ab) < EPSILON\n"
},
{
"answer_id": 328193,
"author": "Jules",
"author_id": 40078,
"author_profile": "https://Stackoverflow.com/users/40078",
"pm_score": 6,
"selected": false,
"text": "def distance(a,b):\n return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)\n\ndef is_between(a,c,b):\n return distance(a,c) + distance(c,b) == distance(a,b)\n"
},
{
"answer_id": 328268,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env python\nfrom __future__ import division\n\nepsilon = 1e-6\n\nclass Point:\n def __init__(self, x, y):\n self.x, self.y = x, y\n\nclass LineSegment:\n \"\"\"\n >>> ls = LineSegment(Point(0,0), Point(2,4))\n >>> Point(1, 2) in ls\n True\n >>> Point(.5, 1) in ls\n True\n >>> Point(.5, 1.1) in ls\n False\n >>> Point(-1, -2) in ls\n False\n >>> Point(.1, 0.20000001) in ls\n True\n >>> Point(.1, 0.2001) in ls\n False\n >>> ls = LineSegment(Point(1, 1), Point(3, 5))\n >>> Point(2, 3) in ls\n True\n >>> Point(1.5, 2) in ls\n True\n >>> Point(0, -1) in ls\n False\n >>> ls = LineSegment(Point(1, 2), Point(1, 10))\n >>> Point(1, 6) in ls\n True\n >>> Point(1, 1) in ls\n False\n >>> Point(2, 6) in ls \n False\n >>> ls = LineSegment(Point(-1, 10), Point(5, 10))\n >>> Point(3, 10) in ls\n True\n >>> Point(6, 10) in ls\n False\n >>> Point(5, 10) in ls\n True\n >>> Point(3, 11) in ls\n False\n \"\"\"\n def __init__(self, a, b):\n if a.x > b.x:\n a, b = b, a\n (self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)\n self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None\n\n def __contains__(self, c):\n return (self.x0 <= c.x <= self.x1 and\n min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and\n (not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))\n\n def y(self, x): \n return self.slope * (x - self.x0) + self.y0\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n"
},
{
"answer_id": 328337,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 3,
"selected": false,
"text": "class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nclass Segment:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def is_between(self, c):\n # Check if slope of a to c is the same as a to b ;\n # that is, when moving from a.x to c.x, c.y must be proportionally\n # increased than it takes to get from a.x to b.x .\n\n # Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.\n # => c is after a and before b, or the opposite\n # that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )\n # or 1 ( c == a or c == b)\n\n a, b = self.a, self.b \n\n return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and \n abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and\n abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)\n a = Point(0,0)\nb = Point(50,100)\nc = Point(25,50)\nd = Point(0,8)\n\nprint Segment(a,b).is_between(c)\nprint Segment(a,b).is_between(d)\n"
},
{
"answer_id": 7913523,
"author": "Shankster",
"author_id": 716328,
"author_profile": "https://Stackoverflow.com/users/716328",
"pm_score": 1,
"selected": false,
"text": "c = ma + (1 - m)b, where 0 <= m <= 1\n m = (c.x - b.x)/(a.x - b.x) = (c.y - b.y)/(a.y - b.y)\n def is_on(a, b, c):\n \"\"\"Is c on the line segment ab?\"\"\"\n\n def _is_zero( val ):\n return -epsilon < val < epsilon\n\n x1 = a.x - b.x\n x2 = c.x - b.x\n y1 = a.y - b.y\n y2 = c.y - b.y\n\n if _is_zero(x1) and _is_zero(y1):\n # a and b are the same point:\n # so check that c is the same as a and b\n return _is_zero(x2) and _is_zero(y2)\n\n if _is_zero(x1):\n # a and b are on same vertical line\n m2 = y2 * 1.0 / y1\n return _is_zero(x2) and 0 <= m2 <= 1\n elif _is_zero(y1):\n # a and b are on same horizontal line\n m1 = x2 * 1.0 / x1\n return _is_zero(y2) and 0 <= m1 <= 1\n else:\n m1 = x2 * 1.0 / x1\n if m1 < 0 or m1 > 1:\n return False\n m2 = y2 * 1.0 / y1\n return _is_zero(m2 - m1)\n"
},
{
"answer_id": 9224700,
"author": "edid",
"author_id": 640781,
"author_profile": "https://Stackoverflow.com/users/640781",
"pm_score": 1,
"selected": false,
"text": "Boolean Contains(PointF from, PointF to, PointF pt, double epsilon)\n {\n\n double segmentLengthSqr = (to.X - from.X) * (to.X - from.X) + (to.Y - from.Y) * (to.Y - from.Y);\n double r = ((pt.X - from.X) * (to.X - from.X) + (pt.Y - from.Y) * (to.Y - from.Y)) / segmentLengthSqr;\n if(r<0 || r>1) return false;\n double sl = ((from.Y - pt.Y) * (to.X - from.X) - (from.X - pt.X) * (to.Y - from.Y)) / System.Math.Sqrt(segmentLengthSqr);\n return -epsilon <= sl && sl <= epsilon;\n }\n"
},
{
"answer_id": 11588038,
"author": "bfcoder",
"author_id": 1477165,
"author_profile": "https://Stackoverflow.com/users/1477165",
"pm_score": 2,
"selected": false,
"text": "is_on = (a,b,c) ->\n # \"Return true if point c intersects the line segment from a to b.\"\n # (or the degenerate case that all 3 points are coincident)\n return (collinear(a,b,c) and withincheck(a,b,c))\n\nwithincheck = (a,b,c) ->\n if a[0] != b[0]\n within(a[0],c[0],b[0]) \n else \n within(a[1],c[1],b[1])\n\ncollinear = (a,b,c) ->\n # \"Return true if a, b, and c all lie on the same line.\"\n ((b[0]-a[0])*(c[1]-a[1]) < (c[0]-a[0])*(b[1]-a[1]) + 1000) and ((b[0]-a[0])*(c[1]-a[1]) > (c[0]-a[0])*(b[1]-a[1]) - 1000)\n\nwithin = (p,q,r) ->\n # \"Return true if q is between p and r (inclusive).\"\n p <= q <= r or r <= q <= p\n"
},
{
"answer_id": 13323946,
"author": "Matthew Henry",
"author_id": 1352613,
"author_profile": "https://Stackoverflow.com/users/1352613",
"pm_score": 3,
"selected": false,
"text": "l1 + A(l2 - l1)\n x = l1.x + A(l2.x - l1.x)\ny = l1.y + A(l2.y - l1.y)\n // Vec2 is a simple x/y struct - it could very well be named Point for this use\n\nbool isBetween(double a, double b, double c) {\n // return if c is between a and b\n double larger = (a >= b) ? a : b;\n double smaller = (a != larger) ? a : b;\n\n return c <= larger && c >= smaller;\n}\n\nbool pointOnLine(Vec2<double> p, Vec2<double> l1, Vec2<double> l2) {\n if(l2.x - l1.x == 0) return isBetween(l1.y, l2.y, p.y); // vertical line\n if(l2.y - l1.y == 0) return isBetween(l1.x, l2.x, p.x); // horizontal line\n\n double Ax = (p.x - l1.x) / (l2.x - l1.x);\n double Ay = (p.y - l1.y) / (l2.y - l1.y);\n\n // We want Ax == Ay, so check if the difference is very small (floating\n // point comparison is fun!)\n\n return fabs(Ax - Ay) < 0.000001 && Ax >= 0.0 && Ax <= 1.0;\n}\n"
},
{
"answer_id": 19633299,
"author": "golwig",
"author_id": 507481,
"author_profile": "https://Stackoverflow.com/users/507481",
"pm_score": 1,
"selected": false,
"text": "boolean liesOnSegment(Coordinate a, Coordinate b, Coordinate c) {\n \n double dotProduct = (c.x - a.x) * (c.x - b.x) + (c.y - a.y) * (c.y - b.y);\n return (dotProduct < 0);\n}\n"
},
{
"answer_id": 21453970,
"author": "bradgonesurfing",
"author_id": 158285,
"author_profile": "https://Stackoverflow.com/users/158285",
"pm_score": 1,
"selected": false,
"text": "public static bool IsOnSegment(this Segment2D @this, Point2D c, double tolerance)\n{\n var distanceSquared = tolerance*tolerance;\n // Start of segment to test point vector\n var v = new Vector2D( @this.P0, c ).To3D();\n // Segment vector\n var s = new Vector2D( @this.P0, @this.P1 ).To3D();\n // Dot product of s\n var ss = s*s;\n // k is the scalar we multiply s by to get the projection of c onto s\n // where we assume s is an infinte line\n var k = v*s/ss;\n // Convert our tolerance to the units of the scalar quanity k\n var kd = tolerance / Math.Sqrt( ss );\n // Check that the projection is within the bounds\n if (k <= -kd || k >= (1+kd))\n {\n return false;\n }\n // Find the projection point\n var p = k*s;\n // Find the vector between test point and it's projection\n var vp = (v - p);\n // Check the distance is within tolerance.\n return vp * vp < distanceSquared;\n}\n s * s\n"
},
{
"answer_id": 29301940,
"author": "Jules",
"author_id": 40078,
"author_profile": "https://Stackoverflow.com/users/40078",
"pm_score": 3,
"selected": false,
"text": "def dot(v,w): return v.x*w.x + v.y*w.y\ndef wedge(v,w): return v.x*w.y - v.y*w.x\n\ndef is_between(a,b,c):\n v = a - b\n w = b - c\n return wedge(v,w) == 0 and dot(v,w) > 0\n"
},
{
"answer_id": 46822167,
"author": "kaleidos",
"author_id": 7608542,
"author_profile": "https://Stackoverflow.com/users/7608542",
"pm_score": 0,
"selected": false,
"text": "private bool _isPointOnLine( Vector2 ptLineStart, Vector2 ptLineEnd, Vector2 ptPoint )\n{\n bool bRes = false;\n if((Mathf.Approximately(ptPoint.x, ptLineStart.x) || Mathf.Approximately(ptPoint.x, ptLineEnd.x)))\n {\n if(ptPoint.y > ptLineStart.y && ptPoint.y < ptLineEnd.y)\n {\n bRes = true;\n }\n }\n else if((Mathf.Approximately(ptPoint.y, ptLineStart.y) || Mathf.Approximately(ptPoint.y, ptLineEnd.y)))\n {\n if(ptPoint.x > ptLineStart.x && ptPoint.x < ptLineEnd.x)\n {\n bRes = true;\n }\n }\n return bRes;\n}\n"
},
{
"answer_id": 56850069,
"author": "Tone Škoda",
"author_id": 3572009,
"author_profile": "https://Stackoverflow.com/users/3572009",
"pm_score": 1,
"selected": false,
"text": "public static double CalcDistanceBetween2Points(double x1, double y1, double x2, double y2)\n{\n return Math.Sqrt(Math.Pow (x1-x2, 2) + Math.Pow (y1-y2, 2));\n}\n\npublic static bool PointLinesOnLine (double x, double y, double x1, double y1, double x2, double y2, double allowedDistanceDifference)\n{\n double dist1 = CalcDistanceBetween2Points(x, y, x1, y1);\n double dist2 = CalcDistanceBetween2Points(x, y, x2, y2);\n double dist3 = CalcDistanceBetween2Points(x1, y1, x2, y2);\n return Math.Abs(dist3 - (dist1 + dist2)) <= allowedDistanceDifference;\n}\n"
},
{
"answer_id": 63343210,
"author": "Sagan",
"author_id": 8422658,
"author_profile": "https://Stackoverflow.com/users/8422658",
"pm_score": 0,
"selected": false,
"text": "function getLineDefinition($p1=array(0,0), $p2=array(0,0)){\n \n $k = ($p1[1]-$p2[1])/($p1[0]-$p2[0]);\n $q = $p1[1]-$k*$p1[0];\n \n return array($k, $q);\n \n}\n\nfunction isPointOnLineSegment($line=array(array(0,0),array(0,0)), $pt=array(0,0)){\n \n // GET THE LINE DEFINITION y = k.x + q AS array(k, q) \n $def = getLineDefinition($line[0], $line[1]);\n \n // use the line definition to find y for the x of your point\n $y = $def[0]*$pt[0]+$def[1];\n\n $yMin = min($line[0][1], $line[1][1]);\n $yMax = max($line[0][1], $line[1][1]);\n\n // exclude y values that are outside this segments bounds\n if($y>$yMax || $y<$yMin) return false;\n \n // calculate the difference of your points y value from the reference value calculated from lines definition \n // in ideal cases this would equal 0 but we are dealing with floating point values so we need some threshold value not to lose results\n // this is up to you to fine tune\n $diff = abs($pt[1]-$y);\n \n $thr = 0.000001;\n \n return $diff<=$thr;\n \n}\n"
},
{
"answer_id": 72285835,
"author": "blunova",
"author_id": 14952856,
"author_profile": "https://Stackoverflow.com/users/14952856",
"pm_score": 1,
"selected": false,
"text": "scikit-spatial Line a b >>> point_a = [0, 0]\n>>> point_b = [1, 0]\n\n>>> line = Line.from_points(point_a, point_b)\n side_point Line c line >>> line.side_point([0.5, 0])\n0\n 0 c line"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
] |
328,123 | <p>I have one table that saves comments for a varied set of content types. These are saved in other tables (news, articles, users).
I wonder what's the best way to connect these tables?
In previous projects I used a second table for each kind of content. They held the id of the certain content mapped to ids of the comments table. So for each comment I had the comment entry itself and a 'connector' entry.
An alternative would be to use a separate comments table for any kind of content.
At the end both ways contain some redundancy flaw.</p>
<p>So which one should I use or is there the ONE solution?</p>
| [
{
"answer_id": 328218,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 0,
"selected": false,
"text": "Comments\n-------\nID\nNewsID\nArticleID\nUserID\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35903/"
] |
328,202 | <p>I'm considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID field) but I want different tables to have different ID generation strategies:</p>
<pre><code>@MappedSuperclass
public abstract class Base implements Serializable {
@Id
@Column(name="ID", nullable = false)
private Integer id;
public Integer getId(){return id;}
public void setId(Integer id){this.id = id;}
...
}
@Entity
@Table(name="TABLE_A")
public class TableA extends Base {
// Table_A wants to set an application-defined value for ID
...
}
@Entity
@Table(name="TABLE_B")
public class TableB extends Base {
// How do I specify @GeneratedValue(strategy = AUTO) for ID here?
...
}
</code></pre>
<p>Is there some way to do this? I've tried including the following into <code>TableB</code> but hibernate objected to my having the same column twice and it seems wrong:</p>
<pre><code>@Override // So that we can set Generated strategy
@Id
@GeneratedValue(strategy = AUTO)
public Integer getId() {
return super.getId();
}
</code></pre>
| [
{
"answer_id": 339872,
"author": "LenW",
"author_id": 41292,
"author_profile": "https://Stackoverflow.com/users/41292",
"pm_score": 2,
"selected": false,
"text": "@Override // So that we can set Generated strategy\n@GeneratedValue(strategy = AUTO)\npublic Integer getId() {\n return super.getId();\n}\n"
},
{
"answer_id": 5775227,
"author": "Lenik",
"author_id": 217071,
"author_profile": "https://Stackoverflow.com/users/217071",
"pm_score": 2,
"selected": false,
"text": "Base @MappedSuperclass\nabstract class SuperBase<K> {\n public abstract K getId();\n}\n\n@MappedSuperclass\nclass Base<K> extends SuperBase<K> {\n @Id @GeneratedValue(AUTO)\n public K getId() { ... }\n}\n @GeneratedValue SuperBase"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41861/"
] |
328,215 | <p>I was hanging out in my profiler for a while trying to figure out how to speed up a common log parser which was bottlenecked around the date parsing, and I tried various algorithms to speed things up.</p>
<p>The thing I tried that was fastest for me was also by far the most readable, but potentially non-standard C.</p>
<p>This worked quite well in <a href="http://en.wikipedia.org/wiki/GNU_Compiler_Collection" rel="noreferrer">GCC</a>, <a href="https://en.wikipedia.org/wiki/Intel_C++_Compiler" rel="noreferrer">icc</a>, and my really old and picky SGI compiler. As it's a quite readable optimization, where doesn't it do what I want?</p>
<pre><code>static int parseMonth(const char *input) {
int rv=-1;
int inputInt=0;
int i=0;
for(i=0; i<4 && input[i]; i++) {
inputInt = (inputInt << 8) | input[i];
}
switch(inputInt) {
case 'Jan/': rv=0; break;
case 'Feb/': rv=1; break;
case 'Mar/': rv=2; break;
case 'Apr/': rv=3; break;
case 'May/': rv=4; break;
case 'Jun/': rv=5; break;
case 'Jul/': rv=6; break;
case 'Aug/': rv=7; break;
case 'Sep/': rv=8; break;
case 'Oct/': rv=9; break;
case 'Nov/': rv=10; break;
case 'Dec/': rv=11; break;
}
return rv;
}
</code></pre>
| [
{
"answer_id": 328222,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "char char int"
},
{
"answer_id": 328228,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "int 'Jan/' char int"
},
{
"answer_id": 328240,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 4,
"selected": false,
"text": "if ( !input[0] || !input[1] || !input[2] || input[3] != '/' )\n return -1;\n\nswitch ( input[0] )\n{\n case 'F': return 1; // Feb\n case 'S': return 8; // Sep\n case 'O': return 9; // Oct\n case 'N': return 10; // Nov\n case 'D': return 11; // Dec;\n case 'A': return input[1] == 'p' ? 3 : 7; // Apr, Aug\n case 'M': return input[2] == 'r' ? 2 : 4; // Mar, May\n default: return input[1] == 'a' ? 0 : (input[2] == 'n' ? 5 : 6); // Jan, Jun, Jul\n}\n"
},
{
"answer_id": 328261,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "uint32_t MONTH_JAN = 'J' << 24 + 'a' << 16 + 'n' << 8 + '/';\nuint32_t MONTH_FEB = 'F' << 24 + 'e' << 16 + 'b' << 8 + '/';\n\n...\n\nstatic uint32_t parseMonth(const char *input) {\n uint32_t rv=-1;\n uint32_t inputInt=0;\n int i=0;\n\n for(i=0; i<4 && input[i]; i++) {\n inputInt = (inputInt << 8) | (input[i] & 0x7f); // clear top bit\n }\n\n switch(inputInt) {\n case MONTH_JAN: rv=0; break;\n case MONTH_FEB: rv=1; break;\n\n ...\n }\n\n return rv;\n}\n"
},
{
"answer_id": 328298,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 6,
"selected": true,
"text": "#include <stdio.h>\n\nstatic int parseMonth(const char *input) {\n int rv=-1;\n int inputInt=0;\n int i=0;\n\n for(i=0; i<4 && input[i]; i++) {\n inputInt = (inputInt << 8) | input[i];\n }\n\n switch(inputInt) {\n case 'Jan/': rv=0; break;\n case 'Feb/': rv=1; break;\n case 'Mar/': rv=2; break;\n case 'Apr/': rv=3; break;\n case 'May/': rv=4; break;\n case 'Jun/': rv=5; break;\n case 'Jul/': rv=6; break;\n case 'Aug/': rv=7; break;\n case 'Sep/': rv=8; break;\n case 'Oct/': rv=9; break;\n case 'Nov/': rv=10; break;\n case 'Dec/': rv=11; break;\n }\n\n return rv;\n}\n\nstatic const struct\n{\n char *data;\n int result;\n} test_case[] =\n{\n { \"Jan/\", 0 },\n { \"Feb/\", 1 },\n { \"Mar/\", 2 },\n { \"Apr/\", 3 },\n { \"May/\", 4 },\n { \"Jun/\", 5 },\n { \"Jul/\", 6 },\n { \"Aug/\", 7 },\n { \"Sep/\", 8 },\n { \"Oct/\", 9 },\n { \"Nov/\", 10 },\n { \"Dec/\", 11 },\n { \"aJ/n\", -1 },\n};\n\n#define DIM(x) (sizeof(x)/sizeof(*(x)))\n\nint main(void)\n{\n size_t i;\n int result;\n\n for (i = 0; i < DIM(test_case); i++)\n {\n result = parseMonth(test_case[i].data);\n if (result != test_case[i].result)\n printf(\"!! FAIL !! %s (got %d, wanted %d)\\n\",\n test_case[i].data, result, test_case[i].result);\n }\n return(0);\n}\n $ gcc -O xx.c -o xx\nxx.c:14:14: warning: multi-character character constant\nxx.c:15:14: warning: multi-character character constant\nxx.c:16:14: warning: multi-character character constant\nxx.c:17:14: warning: multi-character character constant\nxx.c:18:14: warning: multi-character character constant\nxx.c:19:14: warning: multi-character character constant\nxx.c:20:14: warning: multi-character character constant\nxx.c:21:14: warning: multi-character character constant\nxx.c:22:14: warning: multi-character character constant\nxx.c:23:14: warning: multi-character character constant\nxx.c:24:14: warning: multi-character character constant\nxx.c:25:14: warning: multi-character character constant\n$ ./xx\n$ cc -o xx xx.c\n$ ./xx\n!! FAIL !! Jan/ (got -1, wanted 0)\n!! FAIL !! Feb/ (got -1, wanted 1)\n!! FAIL !! Mar/ (got -1, wanted 2)\n!! FAIL !! Apr/ (got -1, wanted 3)\n!! FAIL !! May/ (got -1, wanted 4)\n!! FAIL !! Jun/ (got -1, wanted 5)\n!! FAIL !! Jul/ (got -1, wanted 6)\n!! FAIL !! Aug/ (got -1, wanted 7)\n!! FAIL !! Sep/ (got -1, wanted 8)\n!! FAIL !! Oct/ (got -1, wanted 9)\n!! FAIL !! Nov/ (got -1, wanted 10)\n!! FAIL !! Dec/ (got -1, wanted 11)\n$\n #include <stdio.h>\n\n/* MONTH_CODE(\"Jan/\") does not reduce to an integer constant */\n#define MONTH_CODE(x) ((((((x[0]<<8)|x[1])<<8)|x[2])<<8)|x[3])\n\n#define MONTH_JAN (((((('J'<<8)|'a')<<8)|'n')<<8)|'/')\n#define MONTH_FEB (((((('F'<<8)|'e')<<8)|'b')<<8)|'/')\n#define MONTH_MAR (((((('M'<<8)|'a')<<8)|'r')<<8)|'/')\n#define MONTH_APR (((((('A'<<8)|'p')<<8)|'r')<<8)|'/')\n#define MONTH_MAY (((((('M'<<8)|'a')<<8)|'y')<<8)|'/')\n#define MONTH_JUN (((((('J'<<8)|'u')<<8)|'n')<<8)|'/')\n#define MONTH_JUL (((((('J'<<8)|'u')<<8)|'l')<<8)|'/')\n#define MONTH_AUG (((((('A'<<8)|'u')<<8)|'g')<<8)|'/')\n#define MONTH_SEP (((((('S'<<8)|'e')<<8)|'p')<<8)|'/')\n#define MONTH_OCT (((((('O'<<8)|'c')<<8)|'t')<<8)|'/')\n#define MONTH_NOV (((((('N'<<8)|'o')<<8)|'v')<<8)|'/')\n#define MONTH_DEC (((((('D'<<8)|'e')<<8)|'c')<<8)|'/')\n\nstatic int parseMonth(const char *input) {\n int rv=-1;\n int inputInt=0;\n int i=0;\n\n for(i=0; i<4 && input[i]; i++) {\n inputInt = (inputInt << 8) | input[i];\n }\n\n switch(inputInt) {\n case MONTH_JAN: rv=0; break;\n case MONTH_FEB: rv=1; break;\n case MONTH_MAR: rv=2; break;\n case MONTH_APR: rv=3; break;\n case MONTH_MAY: rv=4; break;\n case MONTH_JUN: rv=5; break;\n case MONTH_JUL: rv=6; break;\n case MONTH_AUG: rv=7; break;\n case MONTH_SEP: rv=8; break;\n case MONTH_OCT: rv=9; break;\n case MONTH_NOV: rv=10; break;\n case MONTH_DEC: rv=11; break;\n }\n\n return rv;\n}\n\nstatic const struct\n{\n char *data;\n int result;\n} test_case[] =\n{\n { \"Jan/\", 0 },\n { \"Feb/\", 1 },\n { \"Mar/\", 2 },\n { \"Apr/\", 3 },\n { \"May/\", 4 },\n { \"Jun/\", 5 },\n { \"Jul/\", 6 },\n { \"Aug/\", 7 },\n { \"Sep/\", 8 },\n { \"Oct/\", 9 },\n { \"Nov/\", 10 },\n { \"Dec/\", 11 },\n { \"aJ/n\", -1 },\n { \"/naJ\", -1 },\n};\n\n#define DIM(x) (sizeof(x)/sizeof(*(x)))\n\nint main(void)\n{\n size_t i;\n int result;\n\n for (i = 0; i < DIM(test_case); i++)\n {\n result = parseMonth(test_case[i].data);\n if (result != test_case[i].result)\n printf(\"!! FAIL !! %s (got %d, wanted %d)\\n\",\n test_case[i].data, result, test_case[i].result);\n }\n return(0);\n}\n"
},
{
"answer_id": 328312,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 0,
"selected": false,
"text": "/* union -- demonstrate union for characters */\n\n#include <stdio.h>\n\nunion c4_i {\n char c4[5];\n int i ;\n} ;\n\nunion c4_i ex;\n\nint main (){\n ex.c4[0] = 'a';\n ex.c4[1] = 'b';\n ex.c4[2] = 'c';\n ex.c4[3] = 'd';\n ex.c4[4] = '\\0';\n printf(\"%s 0x%08x\\n\", ex.c4, ex.i );\n return 0;\n}\n bash $ ./union\nabcd 0x64636261\nbash $ \n"
},
{
"answer_id": 328331,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 3,
"selected": false,
"text": "char *months = \"Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec/\";\nchar *p = strnstr(months, input, 4);\nreturn p ? (p - months) / 4 : -1;\n"
},
{
"answer_id": 328724,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 1,
"selected": false,
"text": "Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2\nCopyright 1988-2008 Comeau Computing. All rights reserved.\nMODE:strict errors C99 \n\n\"ComeauTest.c\", line 11: warning: multicharacter character literal (potential\n portability problem)\n case 'Jan/': rv=0; break;\n ^\n\n\"ComeauTest.c\", line 12: warning: multicharacter character literal (potential\n portability problem)\n case 'Feb/': rv=1; break;\n ^\n\n\"ComeauTest.c\", line 13: warning: multicharacter character literal (potential\n portability problem)\n case 'Mar/': rv=2; break;\n ^\n\n\"ComeauTest.c\", line 14: warning: multicharacter character literal (potential\n portability problem)\n case 'Apr/': rv=3; break;\n ^\n\n\"ComeauTest.c\", line 15: warning: multicharacter character literal (potential\n portability problem)\n case 'May/': rv=4; break;\n ^\n\n\"ComeauTest.c\", line 16: warning: multicharacter character literal (potential\n portability problem)\n case 'Jun/': rv=5; break;\n ^\n\n\"ComeauTest.c\", line 17: warning: multicharacter character literal (potential\n portability problem)\n case 'Jul/': rv=6; break;\n ^\n\n\"ComeauTest.c\", line 18: warning: multicharacter character literal (potential\n portability problem)\n case 'Aug/': rv=7; break;\n ^\n\n\"ComeauTest.c\", line 19: warning: multicharacter character literal (potential\n portability problem)\n case 'Sep/': rv=8; break;\n ^\n\n\"ComeauTest.c\", line 20: warning: multicharacter character literal (potential\n portability problem)\n case 'Oct/': rv=9; break;\n ^\n\n\"ComeauTest.c\", line 21: warning: multicharacter character literal (potential\n portability problem)\n case 'Nov/': rv=10; break;\n ^\n\n\"ComeauTest.c\", line 22: warning: multicharacter character literal (potential\n portability problem)\n case 'Dec/': rv=11; break;\n ^\n\n\"ComeauTest.c\", line 1: warning: function \"parseMonth\" was declared but never\n referenced\n static int parseMonth(const char *input) {\n ^\n"
},
{
"answer_id": 332873,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 2,
"selected": false,
"text": " Warning: Excess characters in multibyte character literal ignored.\n Duplicate case label '77'.\n"
}
] | 2008/11/29 | [
"https://Stackoverflow.com/questions/328215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39975/"
] |
328,249 | <p>How do you concatenate characters in java? Concatenating strings would only require a <code>+</code> between the strings, but concatenating chars using <code>+</code> will change the value of the char into ascii and hence giving a numerical output. I want to do <code>System.out.println(char1+char2+char3...</code> and create a String word like this.</p>
<p>I could do </p>
<pre><code>System.out.print(char1);
System.out.print(char2);
System.out.print(char3);
</code></pre>
<p>But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.</p>
<p>Thanks</p>
| [
{
"answer_id": 328253,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 6,
"selected": false,
"text": "String s = new StringBuilder().append(char1).append(char2).append(char3).toString();\n String b = \"b\";\nString s = \"a\" + b + \"c\";\n String s = new StringBuilder(\"a\").append(b).append(\"c\").toString();\n \"\" + char1 + char2 + char3;\n new StringBuilder().append(\"\").append(c).append(c1).append(c2).toString();\n"
},
{
"answer_id": 328255,
"author": "Ewen Cartwright",
"author_id": 41595,
"author_profile": "https://Stackoverflow.com/users/41595",
"pm_score": 2,
"selected": false,
"text": "char StringBuilder sb = new StringBuilder('a').append('b').append('c');\nSystem.out.println(sb.toString);\n"
},
{
"answer_id": 328256,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "System.out.println(\"\" + char1 + char2 + char3...);\n"
},
{
"answer_id": 328257,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "System.out.println(\"\" + char1 + char2 + char3); \n"
},
{
"answer_id": 328334,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 5,
"selected": false,
"text": "String a = \"a\" + \"b\" + \"c\";\nString b = System.getProperty(\"blah\") + \"b\";\n String s = \"\" + 'a' + 'b' + 'c';\n String concat(char... chars) {\n if (chars.length == 0) {\n return \"\";\n }\n StringBuilder s = new StringBuilder(chars.length);\n for (char c : chars) {\n s.append(c);\n }\n return s.toString();\n}\n String s = \"Name: '\" + name + \"'\"; // String name;\n String s = new StringBuilder().append(\"Name: \").append(name).append(\"'\").toString();\n"
},
{
"answer_id": 328531,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 3,
"selected": false,
"text": "System.out.println(new String(new char[]{a,b,c}));\n"
},
{
"answer_id": 1370495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public static void main (String [] args) {\n\n char initialA = 'M';\n char initialB = 'P';\n char initialC = 'T';\n\n System.out.println(\"\" + initialA + initialB + initialC );\n\n\n} \n"
},
{
"answer_id": 15553440,
"author": "Elvis",
"author_id": 2196125,
"author_profile": "https://Stackoverflow.com/users/2196125",
"pm_score": 2,
"selected": false,
"text": "System.out.println(char1+\"\"+char2+char3)\n String s = char1+\"\"+char2+char3;\n"
},
{
"answer_id": 38847199,
"author": "Arun.R",
"author_id": 6694919,
"author_profile": "https://Stackoverflow.com/users/6694919",
"pm_score": -1,
"selected": false,
"text": "System.out.print(a + \"\" + b + \"\" + c);\n"
},
{
"answer_id": 40316604,
"author": "Aky",
"author_id": 770765,
"author_profile": "https://Stackoverflow.com/users/770765",
"pm_score": 2,
"selected": false,
"text": "String.format String s = String.format(\"%s%s\", 'a', 'b'); // s is \"ab\"\n"
},
{
"answer_id": 43458143,
"author": "Sarath Kumar pgm",
"author_id": 7880383,
"author_profile": "https://Stackoverflow.com/users/7880383",
"pm_score": -1,
"selected": false,
"text": " char n1=holdername.charAt(0);\n char n2=holdername.charAt(1);\n char n3=holdername.charAt(2);\n char n4=mobile.charAt(0);\n char n5=mobile.charAt(1);\n char n6=mobile.charAt(2);\n String number=new StringBuilder().append(n1).append(n2).append(n3).append(n4).append(n5).append(n6).toString();\n\n return number;\n}\n"
},
{
"answer_id": 49920362,
"author": "Baisakha Chauhan",
"author_id": 9238502,
"author_profile": "https://Stackoverflow.com/users/9238502",
"pm_score": 1,
"selected": false,
"text": " StringBuilder desc = new StringBuilder(); \n String Description=\"this is my land\"; \n desc=desc.append(Description.charAt(i));\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,264 | <p>When I supply the script with the argument: hi[123].txt it will do exactly what I want.
But if I specify the wildcard character ( hi*.txt ) it will be re-reading some files.</p>
<p>I was wondering how to modify this script to fix that silly problem:</p>
<pre><code>#!/bin/sh
count="0"
total="0"
FILE="$1" #FILE specification is now $1 Specification..
for FILE in $@
do
#if the file is not readable then say so
if [ ! -r $FILE ];
then
echo "File: $FILE not readable"
exit 0
fi
# Start processing readable files
while read line
do
if [[ "$line" =~ ^Total ]];
then
tmp=$(echo $line | cut -d':' -f2)
total=$(expr $total + $tmp)
echo "$FILE (s) have a total of:$tmp "
count=$(expr $count + 1)
fi
done < $FILE
done
echo " Total is: $total"
echo " Number of files read is:$count"
</code></pre>
| [
{
"answer_id": 328286,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "for FILE in $@ for FILE in \"$@\" \"$1\" \"$2\" ... $1 $2 ... \"\" FILE awk -F: '\n/^Total/ { \n total += $2\n # count++ not needed. see below\n print FILENAME \"(s) have a total of: \" $2\n} \n\nEND { \n print \"Total is: \" total\n print \"Number of files read is: \" (ARGC-1) \n}' foo*.txt\n count"
},
{
"answer_id": 328287,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "for FILE in `/bin/ls $@`\ndo\n. . .\n /bin/ls hi1.txt hi1.txt hi1.txt hi1.txt hi*.txt hi[123].txt"
},
{
"answer_id": 328289,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "FILE=\"$1\" #FILE specification is now $1 Specification..\n\nfor FILE in $@\n ...\n BEGIN{\n TOTAL=0;\n COUNT=0;\n FS=':';\n}\n/^Total/{\n TOTAL += $2;\n COUNT++;\n printf(\"File '%s' has a total of %i\",FILENAME,TOTAL);\n}\nEND{\n printf(\"Total is %i\",TOTAL);\n printf(\"Number of files read is%i\",COUNT);\n}\n"
},
{
"answer_id": 328322,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": true,
"text": "echo \"$0: file $FILE not readable\" 1>&2\n $0 perl -na -F: -e '$sum += $F[1] if m/^Total:/; END { print $sum; }' \"$@\"\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40120/"
] |
328,277 | <p>So here's what I've got: </p>
<ul>
<li>An NSTableView with an NSMutableArray data source</li>
<li>FSEvents monitoring a folder that contains the file that contains the data for the table view (Using <a href="http://stuconnolly.com/blog/archive/2008/05/08/fsevents-objectivec-wrapper" rel="nofollow noreferrer">SCEvents</a> for Objective-C abstraction goodness)</li>
<li>The FSEvents triggers the same function that a reload button in the UI does. This function refreshes the table view with a new data source based on the contents of said file via <code>setDataSource:</code>.</li>
</ul>
<p>And here's what happens:</p>
<ul>
<li>If I make a change to the file, the FSEvent gets triggered and the refresh method gets called.</li>
<li>The array that the table view should be accepting does indeed include the changes that triggered the FSEvent.</li>
<li><code>setDataSource:</code> gets sent to the NSTableView with the correct data source.</li>
<li>The changes do not appear in the table view!</li>
</ul>
<p>But then:</p>
<ul>
<li>If I hit the refresh button, which triggers the exact same method as the FSEvent, the table view gets updated with the new data.</li>
</ul>
<p>I also tried replacing the FSEvent with an NSNotification (<code>NSApplicationDidBecomeActiveNotification</code>), but the same thing happens.</p>
<p>Anyone have any idea why this is happening?</p>
<p>Edit: For clarification, the jist of my question is this: Why does my NSTableView reload as it should when triggered by a button press, but not when triggered by an FSEvent or an NSNotification?</p>
<p>Edit: Thanks to <a href="https://stackoverflow.com/questions/328277/nstableview-setdatasource-not-working-when-triggered-by-fsevents#328648">diciu</a>, I've figured out that in fact all of my UI references point to 0x0 when triggered by the event, but then have valid addresses when triggered by the button click. These objects are all declared in IB, so there's no instantiation or allocation for them going on in my code. So my question is now: what can I do to stop these pointers from pointing to nil?</p>
| [
{
"answer_id": 328357,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 1,
"selected": false,
"text": "[myObject performSelector:@selector(reloadAction:) withObject:nil afterDelay:0.0];\n"
},
{
"answer_id": 328583,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 1,
"selected": false,
"text": "NSArray NSTableView NSTableDataSource NSArray setDataSource:"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4103/"
] |
328,281 | <p>A customer sometimes sends POST requests with <code>Content-Length: 0</code> when submitting a form (10 to over 40 fields).</p>
<p>We tested it with different browsers and from different locations but couldn't reproduce the error. The customer is using Internet Explorer 7 and a proxy.</p>
<p>We asked them to let their system administrator see into the problem from their side. Running some tests without the proxy, etc..</p>
<p>In the meantime (half a year later and still no answer) I'm curious if somebody else knows of similar problems with a <code>Content-Length: 0</code> request. Maybe from inside some Windows network with a special proxy for big companies.</p>
<p>Is there a known problem with Internet Explorer 7? With a proxy system? The Windows network itself?</p>
<p>Google only showed something in the context of NTLM (and such) authentication, but we aren't using this in the web application. Maybe it's in the way the proxy operates in the customer's network with Windows logins? (I'm no Windows expert. Just guessing.)</p>
<p>I have no further information about the infrastructure.</p>
<p><strong>UPDATE:</strong> In December 2010 it was possible to inform one administrator about this, incl. links from the answers here. Contact was because of another problem which was caused by the proxy, too. No feedback since then. And the error messages are still there. I'm laughing to prevent me from crying.</p>
<p><strong>UPDATE 2:</strong> This problem exists since mid 2008. Every few months the customer is annoyed and wants it to be fixed ASAP. We send them all the old e-mails again and ask them to contact their administrators to either fix it or run some further tests. In December 2010 we were able to send some information to 1 administrator. No feedback. Problem isn't fixed and we don't know if they even tried. And in May 2011 the customer writes again and wants this to be fixed. The same person who has all the information since 2008.</p>
<p>Thanks for all the answers. You helped a lot of people, as I can see from some comments here. Too bad the real world is this grotesque for me.</p>
<p><strong>UPDATE 3:</strong> May 2012 and I was wondering why we hadn't received another demand to fix this (see UPDATE 2). Looked into the error protocol, which only reports this single error every time it happened (about 15 a day). It stopped end of January 2012. Nobody said anything. They must have done something with their network. Everything is OK now. From summer 2008 to January 2012. Too bad I can't tell you what they have done.</p>
<p><strong>UPDATE 4:</strong> September 2015. The website had to collect some data and deliver it to the main website of the customer. There was an API with an account. Whenever there was a problem they contacted us, even if the problem was clearly on the other side. For a few weeks now we can't send them the data. The account isn't available anymore. They had a relaunch and I can't find the pages anymore that used the data of our site. The bug report isn't answered and nobody complaint. I guess they just ended this project.</p>
<p><strong>UPDATE 5:</strong> March 2017. The API stopped working in the summer of 2015. The customer seems to continue paying for the site and is still accessing it in February 2017. I'm guessing they use it as an archive. They don't create or update any data anymore so this bug probably won't reemerge after the mysterious fix of January 2012. But this would be someone else's problem. I'm leaving.</p>
| [
{
"answer_id": 42594322,
"author": "user1641854",
"author_id": 1641854,
"author_profile": "https://Stackoverflow.com/users/1641854",
"pm_score": 0,
"selected": false,
"text": "curl PUT/POST Content-Length: 0 PUT/POST GET/HEAD curl PUT/POST PUT/POST Content-Length"
},
{
"answer_id": 44852556,
"author": "matthewrwilton",
"author_id": 3639663,
"author_profile": "https://Stackoverflow.com/users/3639663",
"pm_score": 2,
"selected": false,
"text": "Content-Length: 0 http://... https://... https://..."
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41860/"
] |
328,343 | <p>I'm trying to use SharpZipLib to pull specified files from a zip archive. All of the examples I've seen always expect that you want to unzip the entire zip, and do something along the lines of:</p>
<pre><code> FileStream fileStreamIn = new FileStream (sourcePath, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
ZipEntry entry;
while (entry = zipInStream.GetNextEntry() != null)
{
// Unzip file
}
</code></pre>
<p>What I want to do is something like:</p>
<pre><code>ZipEntry entry = zipInStream.SeekToFile("FileName");
</code></pre>
<p>As my needs involve using a zip as a package and only grabbing files into memory as needed.</p>
<p>Is anyone familiar with SharpZipLib? Does anyone know if I can do this without running through the entire zip by hand?</p>
| [
{
"answer_id": 328353,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 7,
"selected": true,
"text": "using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))\nusing (var zf = new ZipFile(fs)) {\n var ze = zf.GetEntry(fileName);\n if (ze == null) {\n throw new ArgumentException(fileName, \"not found in Zip\");\n }\n\n using (var s = zf.GetInputStream(ze)) {\n // do something with ZipInputStream\n }\n}\n"
},
{
"answer_id": 328358,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 4,
"selected": false,
"text": "FastZip.ExtractZip (string zipFileName, string targetDirectory, string fileFilter)\n // A filter is a sequence of independant <see cref=\"Regex\">regular expressions</see> separated by semi-colons ';'\n// Each expression can be prefixed by a plus '+' sign or a minus '-' sign to denote the expression\n// is intended to include or exclude names. If neither a plus or minus sign is found include is the default\n// A given name is tested for inclusion before checking exclusions. Only names matching an include spec\n// and not matching an exclude spec are deemed to match the filter.\n// An empty filter matches any name.\n// </summary>\n// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'\n// \"+\\.dat$;-^dummy\\.dat$\"\n"
},
{
"answer_id": 543848,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": " using (ZipFile zip = ZipFile.Read(sourcePath)\n {\n zip[\"NameOfFileToUnzip.txt\"].Extract();\n }\n using (ZipFile zip = ZipFile.Read(sourcePath)\n {\n Stream s = zip[\"NameOfFileToUnzip.txt\"].OpenReader();\n // fiddle with stream here\n }\n using (ZipFile zip = ZipFile.Read(sourcePath)\n {\n // extract all XML files in the archive\n zip.ExtractSelectedEntries(\"*.xml\");\n }\n // extract all files modified after 15 Jan 2009\n zip.ExtractSelectedEntries(\"mtime > 2009-01-15\");\n // extract all files that are modified after 15 Jan 2009) AND larger than 1mb\n zip.ExtractSelectedEntries(\"mtime > 2009-01-15 and size > 1mb\");\n\n // extract all XML files that are modified after 15 Jan 2009) AND larger than 1mb\n zip.ExtractSelectedEntries(\"name = *.xml and mtime > 2009-01-15 and size > 1mb\");\n using (ZipFile zip1 = ZipFile.Read(ZipFileName))\n {\n var PhotoShopFiles = zip1.SelectEntries(\"*.psd\");\n // the selection is just an ICollection<ZipEntry>\n foreach (ZipEntry e in PhotoShopFiles)\n {\n // examine metadata here, make decision on extraction\n e.Extract();\n }\n }\n"
},
{
"answer_id": 1257593,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "''' <summary>\n''' Extrae un archivo específico comprimido dentro de un archivo zip\n''' </summary>\n''' <param name=\"SourceZipPath\"></param>\n''' <param name=\"FileName\">Nombre del archivo buscado. Debe incluir ruta, si se comprimió usando guardar con FullPath</param>\n''' <param name=\"DestPath\">Ruta de destino del archivo. Ver parámetro OriginalPath.</param>\n''' <param name=\"password\">Si el archivador no tiene contraseña, puede quedar en blanco</param>\n''' <param name=\"OriginalPath\">OriginalPath=1, extraer en la RUTA ORIGINAL. OriginalPath=0, extraer en DestPath</param>\n''' <returns></returns>\n''' <remarks></remarks>\nPublic Function ExtractSpecificZipFile(ByVal SourceZipPath As String, ByVal FileName As String, _\nByVal DestPath As String, ByVal password As String, ByVal OriginalPath As Integer) As Boolean\n Try\n Dim fileStreamIn As FileStream = New FileStream(SourceZipPath, FileMode.Open, FileAccess.Read)\n Dim fileStreamOut As FileStream\n Dim zf As ZipFile = New ZipFile(fileStreamIn)\n\n Dim Size As Integer\n Dim buffer(4096) As Byte\n\n zf.Password = password\n\n Dim Zentry As ZipEntry = zf.GetEntry(FileName)\n\n If (Zentry Is Nothing) Then\n Debug.Print(\"not found in Zip\")\n Return False\n Exit Function\n End If\n\n Dim fstr As ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream\n fstr = zf.GetInputStream(Zentry)\n\n If OriginalPath = 1 Then\n Dim strFullPath As String = Path.GetDirectoryName(Zentry.Name)\n Directory.CreateDirectory(strFullPath)\n fileStreamOut = New FileStream(strFullPath & \"\\\" & Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)\n Else\n fileStreamOut = New FileStream(DestPath + \"\\\" + Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)\n End If\n\n\n Do\n Size = fstr.Read(buffer, 0, buffer.Length)\n fileStreamOut.Write(buffer, 0, Size)\n Loop While (Size > 0)\n\n fstr.Close()\n fileStreamOut.Close()\n fileStreamIn.Close()\n Return True\n Catch ex As Exception\n Return False\n End Try\n\nEnd Function\n"
},
{
"answer_id": 69199369,
"author": "Del Eraser",
"author_id": 6167660,
"author_profile": "https://Stackoverflow.com/users/6167660",
"pm_score": 0,
"selected": false,
"text": " ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);\n\n using (var zf = new ZipFile(fileStreamIn))\n {\n //zf.Password = \"123\";\n var ze = zf.GetEntry(fileName);\n if (ze == null)\n {\n throw new ArgumentException(fileName, \"not found in Zip\");\n }\n\n using (var s = zf.GetInputStream(ze))\n {\n byte[] buffer = new byte[ze.Size];\n s.Read(buffer, 0, (int) ze.Size);\n //string textdata = Encoding.Default.GetString(buffer)\n }\n }\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
328,352 | <p>I'd like to add a logo to the left of my title on my navigation bar. The title property seems to only take an NSString. What's the best way to add an image to the navigation bar?</p>
| [
{
"answer_id": 328363,
"author": "Adam Ernst",
"author_id": 79,
"author_profile": "https://Stackoverflow.com/users/79",
"pm_score": 2,
"selected": false,
"text": "UINavigationItem.titleView"
},
{
"answer_id": 328372,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 6,
"selected": true,
"text": "navigationItem.titleView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@\"title_bar.png\"]]; \n"
},
{
"answer_id": 37939303,
"author": "BlessNeo",
"author_id": 4313847,
"author_profile": "https://Stackoverflow.com/users/4313847",
"pm_score": 0,
"selected": false,
"text": "navigationItem.titleView"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
328,355 | <p>For example, if I have:</p>
<p><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur urna felis, convallis quis, placerat in, elementum quis, libero. Nam quis lacus. Vivamus rhoncus quam et metus. Praesent et velit eget sem vestibulum volutpat. Integer sed risus. Integer quis libero id diam bibendum luctus. Donec eleifend. Curabitur ut sem. Praesent at est ac sem rhoncus interdum. Etiam arcu nulla, molestie dictum, mollis sed, imperdiet sit amet, neque. Fusce at nibh sit amet mi eleifend aliquam. Nunc tristique scelerisque risus. Praesent et velit id magna volutpat volutpat.</div></p>
<p>...and then it's loaded in the browser and I'm hovering my mouse over various words, is there any reasonable way to detect which word is being hovered over? Any unreasonable way?</p>
| [
{
"answer_id": 328404,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "// highlight every word found in a <p>\n$(\"p\").each(\n function () { \n var content = \"\"; \n var words = $(this).html().match(/\\W*\\w+/g) ;\n var in_tag = false ;\n for (i in words) {\n if (words[i].match(/^\\W*</)) {\n in_tag = true ;\n }\n if (words[i].match(/^\\W*>/)) {\n in_tag = false ;\n }\n if (in_tag) {\n content += words[i];\n } else {\n content += words[i].replace(/(\\w+)/,'<span class=\"word\">$1</span>');\n }\n }\n $(this).html(content);\n }\n);\n\n// example event\n\n$(\".word\").mouseover(function() { $(this).css(\"background-color\",\"#FF0\") });\n$(\".word\").mouseout(function() { $(this).css(\"background-color\",\"\") });\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="https://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| [
{
"answer_id": 1463802,
"author": "GeekTantra",
"author_id": 177526,
"author_profile": "https://Stackoverflow.com/users/177526",
"pm_score": 3,
"selected": false,
"text": "from stripogram import html2text\ntext = html2text(your_html_string)\n"
},
{
"answer_id": 3987802,
"author": "xperroni",
"author_id": 476920,
"author_profile": "https://Stackoverflow.com/users/476920",
"pm_score": 6,
"selected": false,
"text": "from HTMLParser import HTMLParser\nfrom re import sub\nfrom sys import stderr\nfrom traceback import print_exc\n\nclass _DeHTMLParser(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.__text = []\n\n def handle_data(self, data):\n text = data.strip()\n if len(text) > 0:\n text = sub('[ \\t\\r\\n]+', ' ', text)\n self.__text.append(text + ' ')\n\n def handle_starttag(self, tag, attrs):\n if tag == 'p':\n self.__text.append('\\n\\n')\n elif tag == 'br':\n self.__text.append('\\n')\n\n def handle_startendtag(self, tag, attrs):\n if tag == 'br':\n self.__text.append('\\n\\n')\n\n def text(self):\n return ''.join(self.__text).strip()\n\n\ndef dehtml(text):\n try:\n parser = _DeHTMLParser()\n parser.feed(text)\n parser.close()\n return parser.text()\n except:\n print_exc(file=stderr)\n return text\n\n\ndef main():\n text = r'''\n <html>\n <body>\n <b>Project:</b> DeHTML<br>\n <b>Description</b>:<br>\n This small script is intended to allow conversion from HTML markup to \n plain text.\n </body>\n </html>\n '''\n print(dehtml(text))\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 8201491,
"author": "Shatu",
"author_id": 501086,
"author_profile": "https://Stackoverflow.com/users/501086",
"pm_score": 7,
"selected": false,
"text": "clean_html import nltk \nfrom urllib import urlopen\n\nurl = \"http://news.bbc.co.uk/2/hi/health/2284783.stm\" \nhtml = urlopen(url).read() \nraw = nltk.clean_html(html) \nprint(raw)\n"
},
{
"answer_id": 9357137,
"author": "Mark",
"author_id": 1220386,
"author_profile": "https://Stackoverflow.com/users/1220386",
"pm_score": 2,
"selected": false,
"text": "from htmllib import HTMLParser, HTMLParseError\nfrom formatter import AbstractFormatter, DumbWriter\np = HTMLParser(AbstractFormatter(DumbWriter()))\ntry: p.feed('hello<br>there'); p.close() #calling close is not usually needed, but let's play it safe\nexcept HTMLParseError: print ':(' #the html is badly malformed (or you found a bug)\n"
},
{
"answer_id": 10650566,
"author": "Andrew",
"author_id": 871765,
"author_profile": "https://Stackoverflow.com/users/871765",
"pm_score": 3,
"selected": false,
"text": "fname = os.tmpnam()\nfname.write(html_source)\nproc = subprocess.Popen(['links', '-dump', fname], \n stdout=subprocess.PIPE,\n stderr=open('/dev/null','w'))\ntext = proc.stdout.read()\n"
},
{
"answer_id": 13633210,
"author": "Nuncjo",
"author_id": 977337,
"author_profile": "https://Stackoverflow.com/users/977337",
"pm_score": 3,
"selected": false,
"text": "s = URL('http://www.clips.ua.ac.be').download()\ns = plaintext(s, keep={'h1':[], 'h2':[], 'strong':[], 'a':['href']})\nprint s\n"
},
{
"answer_id": 13641398,
"author": "speedplane",
"author_id": 234270,
"author_profile": "https://Stackoverflow.com/users/234270",
"pm_score": 2,
"selected": false,
"text": "import BeautifulSoup\ndef getsoup(data, to_unicode=False):\n data = data.replace(\" \", \" \")\n # Fixes for bad markup I've seen in the wild. Remove if not applicable.\n masssage_bad_comments = [\n (re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1)),\n (re.compile('<!WWWAnswer T[=\\w\\d\\s]*>'), lambda match: '<!--' + match.group(0) + '-->'),\n ]\n myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE)\n myNewMassage.extend(masssage_bad_comments)\n return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage,\n convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES \n if to_unicode else None)\n\nremove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else \"\"\n"
},
{
"answer_id": 16423634,
"author": "bit4",
"author_id": 2359101,
"author_profile": "https://Stackoverflow.com/users/2359101",
"pm_score": 4,
"selected": false,
"text": "\"\"\"\nHTML <-> text conversions.\n\"\"\"\nfrom HTMLParser import HTMLParser, HTMLParseError\nfrom htmlentitydefs import name2codepoint\nimport re\n\nclass _HTMLToText(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self._buf = []\n self.hide_output = False\n\n def handle_starttag(self, tag, attrs):\n if tag in ('p', 'br') and not self.hide_output:\n self._buf.append('\\n')\n elif tag in ('script', 'style'):\n self.hide_output = True\n\n def handle_startendtag(self, tag, attrs):\n if tag == 'br':\n self._buf.append('\\n')\n\n def handle_endtag(self, tag):\n if tag == 'p':\n self._buf.append('\\n')\n elif tag in ('script', 'style'):\n self.hide_output = False\n\n def handle_data(self, text):\n if text and not self.hide_output:\n self._buf.append(re.sub(r'\\s+', ' ', text))\n\n def handle_entityref(self, name):\n if name in name2codepoint and not self.hide_output:\n c = unichr(name2codepoint[name])\n self._buf.append(c)\n\n def handle_charref(self, name):\n if not self.hide_output:\n n = int(name[1:], 16) if name.startswith('x') else int(name)\n self._buf.append(unichr(n))\n\n def get_text(self):\n return re.sub(r' +', ' ', ''.join(self._buf))\n\ndef html_to_text(html):\n \"\"\"\n Given a piece of HTML, return the plain text it contains.\n This handles entities and char refs, but not javascript and stylesheets.\n \"\"\"\n parser = _HTMLToText()\n try:\n parser.feed(html)\n parser.close()\n except HTMLParseError:\n pass\n return parser.get_text()\n\ndef text_to_html(text):\n \"\"\"\n Convert the given text to html, wrapping what looks like URLs with <a> tags,\n converting newlines to <br> tags and converting confusing chars into html\n entities.\n \"\"\"\n def f(mo):\n t = mo.group()\n if len(t) == 1:\n return {'&':'&', \"'\":''', '\"':'"', '<':'<', '>':'>'}.get(t)\n return '<a href=\"%s\">%s</a>' % (t, t)\n return re.sub(r'https?://[^] ()\"\\';]+|[&\\'\"<>]', f, text)\n"
},
{
"answer_id": 21505430,
"author": "Wahib Ul Haq",
"author_id": 1016544,
"author_profile": "https://Stackoverflow.com/users/1016544",
"pm_score": 1,
"selected": false,
"text": "status, data = self.imap.fetch(num, '(RFC822)')\nemail_msg = email.message_from_bytes(data[0][1]) \n#email.message_from_string(data[0][1])\n\n#If message is multi part we only want the text version of the body, this walks the message and gets the body.\n\nif email_msg.is_multipart():\n for part in email_msg.walk(): \n if part.get_content_type() == \"text/plain\":\n body = part.get_payload(decode=True) #to control automatic email-style MIME decoding (e.g., Base64, uuencode, quoted-printable)\n body = body.decode()\n elif part.get_content_type() == \"text/html\":\n continue\n"
},
{
"answer_id": 24618186,
"author": "PeYoTlL",
"author_id": 1206829,
"author_profile": "https://Stackoverflow.com/users/1206829",
"pm_score": 8,
"selected": false,
"text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = \"http://news.bbc.co.uk/2/hi/health/2284783.stm\"\nhtml = urlopen(url).read()\nsoup = BeautifulSoup(html, features=\"html.parser\")\n\n# kill all script and style elements\nfor script in soup([\"script\", \"style\"]):\n script.extract() # rip it out\n\n# get text\ntext = soup.get_text()\n\n# break into lines and remove leading and trailing space on each\nlines = (line.strip() for line in text.splitlines())\n# break multi-headlines into a line each\nchunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n# drop blank lines\ntext = '\\n'.join(chunk for chunk in chunks if chunk)\n\nprint(text)\n pip install beautifulsoup4\n"
},
{
"answer_id": 25195237,
"author": "John Lucas",
"author_id": 2472787,
"author_profile": "https://Stackoverflow.com/users/2472787",
"pm_score": 2,
"selected": false,
"text": "lynx -dump html_to_convert.html > converted_html.txt\n import subprocess\n\nwith open('converted_html.txt', 'w') as outputFile:\n subprocess.call(['lynx', '-dump', 'html_to_convert.html'], stdout=testFile)\n"
},
{
"answer_id": 34215991,
"author": "YakovK",
"author_id": 5628025,
"author_profile": "https://Stackoverflow.com/users/5628025",
"pm_score": 2,
"selected": false,
"text": "soffice --headless --invisible --convert-to txt input1.html\n"
},
{
"answer_id": 37595562,
"author": "David Fraga",
"author_id": 4730107,
"author_profile": "https://Stackoverflow.com/users/4730107",
"pm_score": 1,
"selected": false,
"text": "import re\n\nhtml_text = open('html_file.html').read()\ntext_filtered = re.sub(r'<(.*?)>', '', html_text)\n"
},
{
"answer_id": 38816725,
"author": "Waqar Detho",
"author_id": 1312261,
"author_profile": "https://Stackoverflow.com/users/1312261",
"pm_score": 0,
"selected": false,
"text": ">>> import requests\n>>> url = \"http://news.bbc.co.uk/2/hi/health/2284783.stm\"\n>>> res = requests.get(url)\n>>> text = res.text\n"
},
{
"answer_id": 39226132,
"author": "Hodza",
"author_id": 330090,
"author_profile": "https://Stackoverflow.com/users/330090",
"pm_score": 3,
"selected": false,
"text": "import lxml.html as lh\nfrom lxml.html.clean import clean_html\n\ndef lxml_to_text(html):\n doc = lh.fromstring(html)\n doc = clean_html(doc)\n return doc.text_content()\n"
},
{
"answer_id": 39899612,
"author": "Floyd",
"author_id": 6804636,
"author_profile": "https://Stackoverflow.com/users/6804636",
"pm_score": 5,
"selected": false,
"text": "from bs4 import BeautifulSoup\n\ntext = ' '.join(BeautifulSoup(some_html_string, \"html.parser\").findAll(text=True))\n from bs4 import BeautifulSoup\n\nclean_text = ' '.join(BeautifulSoup(some_html_string, \"html.parser\").stripped_strings)\n"
},
{
"answer_id": 40998513,
"author": "racitup",
"author_id": 1241499,
"author_profile": "https://Stackoverflow.com/users/1241499",
"pm_score": 2,
"selected": false,
"text": "decompose extract <p> <a> from bs4 import BeautifulSoup, NavigableString\n\ndef html_to_text(html):\n \"Creates a formatted text email message as a string from a rendered html template (page)\"\n soup = BeautifulSoup(html, 'html.parser')\n # Ignore anything in head\n body, text = soup.body, []\n for element in body.descendants:\n # We use type and not isinstance since comments, cdata, etc are subclasses that we don't want\n if type(element) == NavigableString:\n # We use the assumption that other tags can't be inside a script or style\n if element.parent.name in ('script', 'style'):\n continue\n\n # remove any multiple and leading/trailing whitespace\n string = ' '.join(element.string.split())\n if string:\n if element.parent.name == 'a':\n a_tag = element.parent\n # replace link text with the link\n string = a_tag['href']\n # concatenate with any non-empty immediately previous string\n if ( type(a_tag.previous_sibling) == NavigableString and\n a_tag.previous_sibling.string.strip() ):\n text[-1] = text[-1] + ' ' + string\n continue\n elif element.previous_sibling and element.previous_sibling.name == 'a':\n text[-1] = text[-1] + ' ' + string\n continue\n elif element.parent.name == 'p':\n # Add extra paragraph formatting newline\n string = '\\n' + string\n text += [string]\n doc = '\\n'.join(text)\n return doc\n"
},
{
"answer_id": 41678315,
"author": "rox",
"author_id": 2702193,
"author_profile": "https://Stackoverflow.com/users/2702193",
"pm_score": 2,
"selected": false,
"text": "bleach.clean(html,tags=[],strip=True)"
},
{
"answer_id": 43224356,
"author": "Pravitha V",
"author_id": 1321663,
"author_profile": "https://Stackoverflow.com/users/1321663",
"pm_score": 2,
"selected": false,
"text": ">>> import html2text\n>>>\n>>> h = html2text.HTML2Text()\n>>> # Ignore converting links from HTML\n>>> h.ignore_links = True\n>>> print h.handle(\"<p>Hello, <a href='http://earth.google.com/'>world</a>!\")\nHello, world!\n"
},
{
"answer_id": 46921881,
"author": "troymyname00",
"author_id": 6343136,
"author_profile": "https://Stackoverflow.com/users/6343136",
"pm_score": 1,
"selected": false,
"text": "from bs4 import BeautifulSoup\nimport urllib.request\n\n\ndef processText(webpage):\n\n # EMPTY LIST TO STORE PROCESSED TEXT\n proc_text = []\n\n try:\n news_open = urllib.request.urlopen(webpage.group())\n news_soup = BeautifulSoup(news_open, \"lxml\")\n news_para = news_soup.find_all(\"p\", text = True)\n\n for item in news_para:\n # SPLIT WORDS, JOIN WORDS TO REMOVE EXTRA SPACES\n para_text = (' ').join((item.text).split())\n\n # COMBINE LINES/PARAGRAPHS INTO A LIST\n proc_text.append(para_text)\n\n except urllib.error.HTTPError:\n pass\n\n return proc_text\n"
},
{
"answer_id": 48852269,
"author": "spatel4140",
"author_id": 5923866,
"author_profile": "https://Stackoverflow.com/users/5923866",
"pm_score": 3,
"selected": false,
"text": "from newspaper import Article\n\narticle = Article(url)\narticle.download()\narticle.parse()\narticle.text\n article = Article('')\narticle.set_html(html)\narticle.parse()\narticle.text\n article.nlp()\narticle.summary\n"
},
{
"answer_id": 49684712,
"author": "Vim",
"author_id": 5144870,
"author_profile": "https://Stackoverflow.com/users/5144870",
"pm_score": 2,
"selected": false,
"text": "import urllib.request\nfrom inscriptis import get_text\n\nurl = \"http://www.informationscience.ch\"\nhtml = urllib.request.urlopen(url).read().decode('utf-8')\n\ntext = get_text(html)\nprint(text)\n"
},
{
"answer_id": 49815537,
"author": "saigopi.me",
"author_id": 5208491,
"author_profile": "https://Stackoverflow.com/users/5208491",
"pm_score": 1,
"selected": false,
"text": "url = \"https://www.geeksforgeeks.org/extracting-email-addresses-using-regular-expressions-python/\"\ncon = urlopen(url).read()\nsoup = BeautifulSoup(con,'html.parser')\ntexts = soup.get_text()\nprint(texts)\n"
},
{
"answer_id": 51209579,
"author": "brunql",
"author_id": 938165,
"author_profile": "https://Stackoverflow.com/users/938165",
"pm_score": 0,
"selected": false,
"text": "import re\n\ndef html2text(html):\n res = re.sub('<.*?>', ' ', html, flags=re.DOTALL | re.MULTILINE)\n res = re.sub('\\n+', '\\n', res)\n res = re.sub('\\r+', '', res)\n res = re.sub('[\\t ]+', ' ', res)\n res = re.sub('\\t+', '\\t', res)\n res = re.sub('(\\n )+', '\\n ', res)\n return res\n"
},
{
"answer_id": 54296631,
"author": "Uri Goren",
"author_id": 1097347,
"author_profile": "https://Stackoverflow.com/users/1097347",
"pm_score": 2,
"selected": false,
"text": "<p>hello world</p>I love you\n Hello world\nI love you\n import re\nimport html\ndef html2text(htm):\n ret = html.unescape(htm)\n ret = ret.translate({\n 8209: ord('-'),\n 8220: ord('\"'),\n 8221: ord('\"'),\n 160: ord(' '),\n })\n ret = re.sub(r\"\\s\", \" \", ret, flags = re.MULTILINE)\n ret = re.sub(\"<br>|<br />|</p>|</div>|</h\\d>\", \"\\n\", ret, flags = re.IGNORECASE)\n ret = re.sub('<.*?>', ' ', ret, flags=re.DOTALL)\n ret = re.sub(r\" +\", \" \", ret)\n return ret\n"
},
{
"answer_id": 57679193,
"author": "Mike Q",
"author_id": 1618630,
"author_profile": "https://Stackoverflow.com/users/1618630",
"pm_score": 1,
"selected": false,
"text": "import urllib2\nfrom bs4 import BeautifulSoup\n def read_website_to_text(url):\n page = urllib2.urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n for script in soup([\"script\", \"style\"]):\n script.extract() \n text = soup.get_text()\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n return str(text.encode('utf-8'))\n"
},
{
"answer_id": 62661784,
"author": "kodlan",
"author_id": 1346212,
"author_profile": "https://Stackoverflow.com/users/1346212",
"pm_score": 2,
"selected": false,
"text": "from selectolax.parser import HTMLParser\n\ndef get_text_selectolax(html):\n tree = HTMLParser(html)\n\n if tree.body is None:\n return None\n\n for tag in tree.css('script'):\n tag.decompose()\n for tag in tree.css('style'):\n tag.decompose()\n\n text = tree.body.text(separator='')\n text = \" \".join(text.split()) # this will remove all the whitespaces\n return text\n"
},
{
"answer_id": 68552982,
"author": "Haider",
"author_id": 1970830,
"author_profile": "https://Stackoverflow.com/users/1970830",
"pm_score": 0,
"selected": false,
"text": "import selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport pyperclip\nimport time\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.lazada.com.ph/products/nike-womens-revolution-5-running-shoes-black-i1262506154-s4552606107.html?spm=a2o4l.seller.list.3.6f5d7b6cHO8G2Y&mp=1&freeshipping=1\")\n\n# Scroll down to end of the page to let all javascript code load its content\nlenOfPage = driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;\")\nmatch=False\nwhile(match==False):\n lastCount = lenOfPage\n time.sleep(1)\n lenOfPage = driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;\")\n if lastCount==lenOfPage:\n match=True\n\n# copy from the webpage\nelement = driver.find_element_by_tag_name('body')\nelement.send_keys(Keys.CONTROL,'a')\nelement.send_keys(Keys.CONTROL,'c')\nalltext = pyperclip.paste()\nalltext = alltext.replace(\"\\n\", \" \").replace(\"\\r\", \" \") # cleaning the copied text\nprint(alltext )\n from inscriptis import get_text\ntext = get_text(driver.page_source)\n"
},
{
"answer_id": 69073151,
"author": "Cam",
"author_id": 11515528,
"author_profile": "https://Stackoverflow.com/users/11515528",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\nhttp = r'https://www.ibm.com/docs/en/cmofz/10.1.0?topic=SSQHWE_10.1.0/com.ibm.ondemand.mp.doc/arsa0257.htm'\ntable = pd.read_html(http)\ndf = table[0]\ndf\n\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] |
328,381 | <p>I'm a php guy, but I have to do some small project in JSP.
I'm wondering if there's an equivalent to htmlentities function (of php) in JSP.</p>
| [
{
"answer_id": 328386,
"author": "Florin",
"author_id": 34565,
"author_profile": "https://Stackoverflow.com/users/34565",
"pm_score": 3,
"selected": true,
"text": "public static String stringToHTMLString(String string) {\n StringBuffer sb = new StringBuffer(string.length());\n // true if last char was blank\n boolean lastWasBlankChar = false;\n int len = string.length();\n char c;\n\n for (int i = 0; i < len; i++)\n {\n c = string.charAt(i);\n if (c == ' ') {\n // blank gets extra work,\n // this solves the problem you get if you replace all\n // blanks with , if you do that you loss \n // word breaking\n if (lastWasBlankChar) {\n lastWasBlankChar = false;\n sb.append(\" \");\n }\n else {\n lastWasBlankChar = true;\n sb.append(' ');\n }\n }\n else {\n lastWasBlankChar = false;\n //\n // HTML Special Chars\n if (c == '\"')\n sb.append(\""\");\n else if (c == '&')\n sb.append(\"&\");\n else if (c == '<')\n sb.append(\"<\");\n else if (c == '>')\n sb.append(\">\");\n else if (c == '\\n')\n // Handle Newline\n sb.append(\"<br/>\");\n else {\n int ci = 0xffff & c;\n if (ci < 160 )\n // nothing special only 7 Bit\n sb.append(c);\n else {\n // Not 7 Bit use the unicode system\n sb.append(\"&#\");\n sb.append(new Integer(ci).toString());\n sb.append(';');\n }\n }\n }\n }\n return sb.toString();\n}\n"
},
{
"answer_id": 10797222,
"author": "Aleksei Egorov",
"author_id": 936670,
"author_profile": "https://Stackoverflow.com/users/936670",
"pm_score": 3,
"selected": false,
"text": "org.apache.commons.lang.StringEscapeUtils.escapeHtml\n"
},
{
"answer_id": 25023168,
"author": "Miron Balcerzak",
"author_id": 1694963,
"author_profile": "https://Stackoverflow.com/users/1694963",
"pm_score": 2,
"selected": false,
"text": "<c:out value=\"${string}\" escapeXml=\"true\" />\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
328,382 | <p>What to do when after all probing, a reportedly valid object return 'undefined' for any attribute probed? I use jQuery, <code>$('selector').mouseover(function() { });</code> Everything returns 'undefined' for <code>$(this)</code> inside the function scope. The selector is a 'area' for a map tag and I'm looking for its parent attributes.</p>
| [
{
"answer_id": 328418,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "function listProperties(obj) {\n var propList = \"\";\n for(var propName in obj) {\n if(typeof(obj[propName]) != \"undefined\") {\n propList += (propName + \", \");\n }\n }\n alert(propList);\n}\n undefined"
},
{
"answer_id": 328440,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "selector $('area#selector')\n $('#selector')\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34565/"
] |
328,384 | <p>I have an associative array, ie</p>
<pre><code>$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
</code></pre>
<p>then I do</p>
<pre><code>// seek to first prime greater than 10000
reset($primes);
while(next($primes) < 10000) {}
prev($primes);
// iterate until target found
while($p = next($primes)) {
$res = doSomeCalculationsOn($p);
if( IsPrime($res) )
return $p;
}
</code></pre>
<p>The problem is that IsPrime also loops through the $primes array,</p>
<pre><code>function IsPrime($num) {
global $primesto, $primes, $lastprime;
if ($primesto >= $num)
// using the assoc array lets me do this as a lookup
return isset($primes[$num]);
$root = (int) sqrt($num);
if ($primesto < $root)
CalcPrimesTo($root);
foreach($primes as $p) { // <- Danger, Will Robinson!
if( $num % $p == 0 )
return false;
if ($p >= $root)
break;
}
return true;
}
</code></pre>
<p>which trashes the array pointer I am iterating on.</p>
<p>I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?</p>
| [
{
"answer_id": 328388,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 3,
"selected": false,
"text": "$state = key($array);\n reset($array);\n\nwhile(key($array) != $state)\n next($array);\n"
},
{
"answer_id": 328457,
"author": "Stepan Mazurov",
"author_id": 40786,
"author_profile": "https://Stackoverflow.com/users/40786",
"pm_score": 0,
"selected": false,
"text": "$awesomePrimes=$primes;\n $awesomePrimes"
},
{
"answer_id": 328703,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": true,
"text": "foreach ($primes as $p) {\n if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {\n return $p;\n }\n}\n"
},
{
"answer_id": 328739,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "int -> int $pointer = array(\n 0 => 2,\n 1 => 3,\n 2 => 5,\n // ...\n);\n $prime $prime[$pointer[$i]]"
},
{
"answer_id": 328808,
"author": "farzad",
"author_id": 9394,
"author_profile": "https://Stackoverflow.com/users/9394",
"pm_score": 0,
"selected": false,
"text": "$primesLength = count($primes); // this is to avoid calling of count() so many times.\nfor ($counter=0 ; $counter < $primesLength ; $counter++) {\n $p = $primesLength[$counter];\n if( $num % $p == 0 )\n return false;\n\n if ($p >= $root)\n break;\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33258/"
] |
328,387 | <p>I need help to replace all \n (new line) caracters for <br /> in a String, but not those \n inside [code][/code] tags.
My brain is burning, I can't solve this by my own :(</p>
<p>Example:</p>
<pre><code>test test test
test test test
test
test
[code]some
test
code
[/code]
more text
</code></pre>
<p>Should be:</p>
<pre><code>test test test<br />
test test test<br />
test<br />
test<br />
<br />
[code]some
test
code
[/code]<br />
<br />
more text<br />
</code></pre>
<p>Thanks for your time.
Best regards.</p>
| [
{
"answer_id": 328392,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 4,
"selected": true,
"text": "stack elementStack;\n\nforeach(char in string) {\n if(string-from-char == \"[code]\") {\n elementStack.push(\"code\");\n string-from-char = \"\";\n }\n\n if(string-from-char == \"[/code]\") {\n elementStack.popTo(\"code\");\n string-from-char = \"\";\n }\n\n if(char == \"\\n\" && !elementStack.contains(\"code\")) {\n char = \"<br/>\\n\";\n }\n}\n"
},
{
"answer_id": 328413,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 1,
"selected": false,
"text": "Matcher m = escapePattern.matcher(input);\nwhile(m.find()) {\n String key = nextKey();\n escaped.put(key,m.group());\n m.appendReplacement(output1,\"TOKEN-\"+key);\n}\nm.appendTail(output1);\nMatcher m2 = newlinePatten.matcher(output1);\nwhile(m2.find()) {\n m.appendReplacement(output2,newlineReplacement);\n}\nm2.appendTail(output2);\nMatcher m3 = Pattern.compile(\"TOKEN-(\\\\d+)\").matcher(output2); \nwhile(m3.find()) {\n m.appendReplacement(finalOutput,escaped.get(m3.group(1)));\n}\nm.appendTail(finalOutput);\n"
},
{
"answer_id": 328429,
"author": "shsmurfy",
"author_id": 2188962,
"author_profile": "https://Stackoverflow.com/users/2188962",
"pm_score": 2,
"selected": false,
"text": "(\\[code\\].*\\[/code\\])\n [code] [/code] output = []\ndef add_brs(str):\n return str.replace('\\n','<br/>\\n')\n# the first block will *not* have a matching [/code] tag\nblocks = input.split('[code]')\noutput.push(add_brs(blocks[0]))\n# for all the rest of the blocks, only add <br/> tags to\n# the segment after the [/code] segment\nfor block in blocks[1:]:\n if len(block.split('[/code]'))!=1:\n raise ParseException('Too many or few [/code] tags')\n else:\n # the segment in the code block is pre, everything\n # after is post\n pre, post = block.split('[/code]')\n output.push(pre)\n output.push(add_brs(post))\n# finally join all the processed segments together\noutput = \"\".join(output)\n"
},
{
"answer_id": 328664,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 2,
"selected": false,
"text": "private final static String PATTERN = \"\\\\*+\";\n\npublic static void main(String args[]) {\n Pattern p = Pattern.compile(\"(.*?)(\\\\[/?code\\\\])\", Pattern.DOTALL);\n String s = \"test 1 ** [code]test 2**blah[/code] test3 ** blah [code] test * 4 [code] test 5 * [/code] * test 6[/code] asdf **\";\n Matcher m = p.matcher(s);\n StringBuffer sb = new StringBuffer(); // note: it has to be a StringBuffer not a StringBuilder because of the Pattern API\n int codeDepth = 0;\n while (m.find()) {\n if (codeDepth == 0) {\n m.appendReplacement(sb, m.group(1).replaceAll(PATTERN, \"\"));\n } else {\n m.appendReplacement(sb, m.group(1));\n }\n if (m.group(2).equals(\"[code]\")) {\n codeDepth++;\n } else {\n codeDepth--;\n }\n sb.append(m.group(2));\n }\n if (codeDepth == 0) {\n StringBuffer sb2 = new StringBuffer();\n m.appendTail(sb2);\n sb.append(sb2.toString().replaceAll(PATTERN, \"\"));\n } else {\n m.appendTail(sb);\n }\n System.out.printf(\"Original: %s%n\", s);\n System.out.printf(\"Processed: %s%n\", sb);\n}\n"
},
{
"answer_id": 328685,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "import java.util.regex.*;\n\nclass Test\n{\n static final String testString = \"foo\\nbar\\n[code]\\nprint'';\\nprint{'c'};\\n[/code]\\nbar\\nfoo\";\n static final String replaceString = \"<br>\\n\";\n public static void main(String args[])\n {\n Pattern p = Pattern.compile(\"(.+?)(\\\\[code\\\\].*?\\\\[/code\\\\])?\", Pattern.DOTALL);\n Matcher m = p.matcher(testString);\n StringBuilder result = new StringBuilder();\n while (m.find()) \n {\n result.append(m.group(1).replaceAll(\"\\\\n\", replaceString));\n if (m.group(2) != null)\n {\n result.append(m.group(2));\n }\n }\n System.out.println(result.toString());\n }\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/328387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.